<commit_before>$dripBot = (function($, $dripBot) {

	if($dripBot instanceof Object) {
		console.log("Refusing to run two dripBots (this could have unintended side effects).  Please refresh to update.");
		return $dripBot;
	}

	var version = '1.0',
	stage1Pid = -1,
	stage2Pid = -1,
	stage3Pid = -1,
	clickerPid = -1,
	clickInterval = 30,
	BPSThreshold = 7 * 1000 * 1000,
	powerups = {},
	timeOfLeaderChange = 0,
	currentLeader = '',
	benevolentLeader = false;
	showPops = false;
	topThing = null;

	var clickButton = $('a#btn-addMem'),
	dripButton = $('button#btn-addGlobalMem'),
	modalButton = 'input.vex-dialog-button-primary';

	function OTB(o, upgrade) {
		if(upgrade) {
			this.isUpgrade = true;
			this.item = o;
			if(o.powerup) {
				if(o.powerup.name == 'Cursor') {
					this.bps = o.powerup.totalBps * 0.1 + getClickingBps() * 0.1;
				} else {
					this.bps = o.powerup.totalBps * 0.1;
				}
			}
			this.realPrice = o.price;
			this.price = o.price;
		} else {
			this.isUpgrade = false;
			this.bps = o.currentBps;
			this.item = o;
			this.realPrice = o.currentPrice;
			this.price = o.currentPrice;
		}
		if(getCapacity() < this.realPrice) {
			this.price = (this.realPrice - getCapacity()) * 2 + getCapacity();
		}

		if(! this.item.available) {
			this.timeToPurchase = (this.price - localStats.byteCount) / localStats.bps;
		} else {
			this.timeToPurchase = 0;
		}
	}

	var buyPowerup = function(name) {
		$(powerups[name]).click();
	}

	var getOTBList = function() {
		var powerupsAndUpgrades = []
		localStats.powerUps.slice(0).forEach(function(e) {
			powerupsAndUpgrades.push(new OTB(e, false));
			if(e.upgrades.length) {
				e.upgrades.forEach(function(u) {
					if((!u._purchased) && u._unlocked) {
						powerupsAndUpgrades.push(new OTB(u, true));
					}
				});
			}
		});
		return powerupsAndUpgrades;
	}

	var sortOTBList = function(otbList) {
		return otbList.sort(function(a,b) {
			var sign = 1,
			shorter,
			longer,
			delta;
			if(b.timeToPurchase >= a.timeToPurchase) {
				shorter = a;
				longer = b;
				sign = 1;
			} else {
				shorter = b;
				longer = a;
				sign = -1;
			}
			var delta = longer.timeToPurchase - shorter.timeToPurchase;
			var newLongerPrice = longer.price + shorter.bps * delta;
			return (shorter.price / shorter.bps - newLongerPrice / longer.bps) * sign; // Adjust based on which was shorter.
		});
	}

	var getNewTopThing = function() {
		topThing = null;
		localStats.specialUpgrades.forEach(function(u) {
			if(!u._purchased && u.available) {
				topThing = new OTB(u, true);
			}
		});
		if(topThing == null) {
			topThing = sortOTBList(getOTBList())[0];
		}
		console.log("Next purchase" + (topThing.isUpgrade ? " (upgrade)" : "") + ": " + topThing.item.name);
	}

	var i = 1;
	localStats.powerUps.forEach(function(pu) { powerups[pu.name] = '#pu' + i++; });

	var getLeader = function() {
		return $('div#leaderBoard table tbody').children('tr').first().children('td').eq(1).text();
	}

	var getClickingBps = function() {
		return CoffeeCup.calcBytesPerClick() * 20;
	}

	var clickCup = function() {
		clickButton.click();
	}

	var drip = function() {
		dripButton.click();
	}

	var getBytes = function() {
		return localStats.byteCount;
	}

	var getCapacity = function() {
		return localStats.memoryCapacity;
	}

	var atMaxBytes = function() {
		return getBytes() == getCapacity();
	}

	var getBPS = function() {
		return localStats.bps;
	}

	var atBPSCap = function() {
		return getBPS() >= BPSThreshold;
	}

	var getMyName = function() {
		return networkUser.userName;
	}

	var getSortedUpgradeList = function() {
		var upgrades = [];
		localStats.powerUps.forEach(function(e) {
			e.upgrades.forEach(function(u) {
				if(u._unlocked && ! u._purchased) {
					upgrades.push(u);
				}
			});
		});
		localStats.specialUpgrades.forEach(function(u) {
			if(!u._purchased) {
				upgrades.push(u);
			}
		});

		upgrades.sort(function(a,b) {
			return a.price - b.price;
		});
		return upgrades;
	}

	var buyUpgrade = function(name) {
		// Not thread safe!  If someone else uses the bytes we'll never know.
		var i = 1;
		getSortedUpgradeList().forEach(function(u) {
			if(u.name == name) {
				var upgrade = $('#upg' + i);
				upgrade.click();

				for(var n=0; n<localStats.specialUpgrades.length; n++) {
					if(localStats.specialUpgrades[n].name == name) {
						$(modalButton).click();
						break;
					}
				}
				return true;
			}
			i++;
		});
		return false;
	}

	var setBPSThreshold = function(num) {
		if(num && num > 0) {
			BPSThreshold = num * 1000 * 1000;
		}
		return BPSThreshold;
	}

	var setClickInterval = function(num) {
		if(num && num > 0) {
			clickInterval = num;
		}
		if(clickerPid != -1) {
			clearInterval(clickerPid);
			clickerPid = setInterval(function() { clickCup(); }, clickInterval);
		}
		return clickInterval;
	}

	var setBenevolentLeader = function(bool) {
		benevolentLeader = bool || false;
		return benevolentLeader;
	}

	var setShowPops = function(bool) {
		showPops = bool || false;
		return showPops;
	}

	var stage1 = function() {
		if(story.state == 6) {
			drip();
		}

		if(story.state == 9) {
			buyPowerup('Cursor');
		}

		if(story.state == 11) {
			buyUpgrade('Enhanced Precision');
		}

		if(story.state == 12) {
			console.log("Proceeding to stage 2 (Purchase).");
			clearInterval(stage1Pid);
			stage2Pid = setInterval(function() { stage2(); }, 500);
			return;
		}

		if(story.state != 12 && atMaxBytes()) {
			drip();
		}
	}

	var stage2 = function() {
		if(atBPSCap()) {
			console.log("Proceeding to stage 3 (Win).");
			topThing = null;
			clearInterval(stage2Pid);
			stage3Pid = setInterval(function() { stage3(); }, 500);
			return;
		}

		if(topThing == null) {
			getNewTopThing();
		}

		if(getBytes() >= topThing.realPrice) {
			if(topThing.isUpgrade) {
				buyUpgrade(topThing.item.name);
			} else {
				buyPowerup(topThing.item.name);
			}

			getNewTopThing();
		} else {
			if(getCapacity() < topThing.realPrice) {
				if((getBytes() + getCapacity()) >= topThing.realPrice || atMaxBytes()) {
					drip();
				}
			}
        }
	}

	var stage3 = function() {
		if(!atBPSCap()) {
			console.log("Reverting to stage 2 (Purchase).");
			currentLeader = null;
			timeOfLeaderChange = null;
			clearInterval(stage3Pid);
			stage2Pid = setInterval(function() { stage2(); }, 500);
			return;
		}

		var leaderName = getLeader();
		if(!currentLeader) {
			currentLeader = getMyName();
		}

		if (leaderName != getMyName()) {
			if(currentLeader == getMyName()) {
				currentLeader = leaderName;
				timeOfLeaderChange = $.now();
				console.log("As of " + timeOfLeaderChange + " there is one fairer in the land... it is '" + leaderName + "'.");

			} else if(leaderName != currentLeader) {
				console.log("Leader changed from '" + currentLeader + "' to '" + leaderName + "'.");
				currentLeader = leaderName;
			}
			drip();

		} else {
			if (currentLeader != leaderName) {
				currentLeader = leaderName;
				var diffTime = $.time;
				console.log("As of " + $.now() + " you are the fairest of them all (it took " + diffTime + " to recover).");
			}

			if(!benevolentLeader) {
				drip();
			}
		}
	}

	var stop = function() {
		clearInterval(stage1Pid);
		clearInterval(stage2Pid);
		clearInterval(stage3Pid);
		clearInterval(clickerPid);
		stage1Pid = -1;
		stage2Pid = -1;
		stage3Pid = -1;
		clickerPid = -1;
	}

	var start = function() {
		console.log('Starting DripBot v' + version + '!');
		if (story.inProgress) {
			console.log("Starting or resuming story.");
			stage1Pid = setInterval(function() { stage1(); }, 100);
		} else if(!atBPSCap()) {
			console.log("Resuming stage 2 (Purchase).");
			stage2Pid = setInterval(function() { stage2(); }, 500);
		} else {
			console.log("Resuming stage 3 (Win).");
			stage3Pid = setInterval(function() { stage3(); }, 500);
		}
		clickerPid = setInterval(function() { clickCup(); }, clickInterval);
	}

	var restart = function() {
		stop();
		start();
	}

	var init = function() {
		document.hasFocus = function() { return true; };
		AnonymousUserManager.canDrip = function() { return true; };
		popManager.oldNewPop = popManager.newPop;
		popManager.newPop = function(e, t, a) {
			if(showPops || (e.indexOf('addMem') == -1 && e != 'chartContainer')) {
				popManager.oldNewPop(e,t,a);
			}
		}
		clickCup();
		setTimeout(function() { start(); }, 500);
	}

	init();

	return {
		buyPowerup: buyPowerup,
		buyUpgrade: buyUpgrade,

		getSortedUpgradeList: getSortedUpgradeList,
		getOTBList: getOTBList,
		sortOTBList: sortOTBList,

		click: clickCup,
		drip: drip,

		setBPSThreshold: setBPSThreshold,
		setBenevolentLeader: setBenevolentLeader,
		setShowPops: setShowPops,
		setClickInterval: setClickInterval,

		stop: stop,
		restart: restart
	};
}($, $dripBot));
<commit_msg>Null check was incorrect, sorry.<commit_after>$dripBot = (function($, $dripBot) {

	if($dripBot instanceof Object) {
		console.log("Refusing to run two dripBots (this could have unintended side effects).  Please refresh to update.");
		return $dripBot;
	}

	var version = '1.0',
	stage1Pid = -1,
	stage2Pid = -1,
	stage3Pid = -1,
	clickerPid = -1,
	clickInterval = 30,
	BPSThreshold = 7 * 1000 * 1000,
	powerups = {},
	timeOfLeaderChange = 0,
	currentLeader = '',
	benevolentLeader = false;
	showPops = false;
	topThing = null;

	var clickButton = $('a#btn-addMem'),
	dripButton = $('button#btn-addGlobalMem'),
	modalButton = 'input.vex-dialog-button-primary';

	function OTB(o, upgrade) {
		if(upgrade) {
			this.isUpgrade = true;
			this.item = o;
			if(o.powerup) {
				if(o.powerup.name == 'Cursor') {
					this.bps = o.powerup.totalBps * 0.1 + getClickingBps() * 0.1;
				} else {
					this.bps = o.powerup.totalBps * 0.1;
				}
			}
			this.realPrice = o.price;
			this.price = o.price;
		} else {
			this.isUpgrade = false;
			this.bps = o.currentBps;
			this.item = o;
			this.realPrice = o.currentPrice;
			this.price = o.currentPrice;
		}
		if(getCapacity() < this.realPrice) {
			this.price = (this.realPrice - getCapacity()) * 2 + getCapacity();
		}

		if(! this.item.available) {
			this.timeToPurchase = (this.price - localStats.byteCount) / localStats.bps;
		} else {
			this.timeToPurchase = 0;
		}
	}

	var buyPowerup = function(name) {
		$(powerups[name]).click();
	}

	var getOTBList = function() {
		var powerupsAndUpgrades = []
		localStats.powerUps.slice(0).forEach(function(e) {
			powerupsAndUpgrades.push(new OTB(e, false));
			if(e.upgrades.length) {
				e.upgrades.forEach(function(u) {
					if((!u._purchased) && u._unlocked) {
						powerupsAndUpgrades.push(new OTB(u, true));
					}
				});
			}
		});
		return powerupsAndUpgrades;
	}

	var sortOTBList = function(otbList) {
		return otbList.sort(function(a,b) {
			var sign = 1,
			shorter,
			longer,
			delta;
			if(b.timeToPurchase >= a.timeToPurchase) {
				shorter = a;
				longer = b;
				sign = 1;
			} else {
				shorter = b;
				longer = a;
				sign = -1;
			}
			var delta = longer.timeToPurchase - shorter.timeToPurchase;
			var newLongerPrice = longer.price + shorter.bps * delta;
			return (shorter.price / shorter.bps - newLongerPrice / longer.bps) * sign; // Adjust based on which was shorter.
		});
	}

	var getNewTopThing = function() {
		topThing = null;
		localStats.specialUpgrades.forEach(function(u) {
			if(!u._purchased && u.available) {
				topThing = new OTB(u, true);
			}
		});
		if(topThing == null) {
			topThing = sortOTBList(getOTBList())[0];
		}
		console.log("Next purchase" + (topThing.isUpgrade ? " (upgrade)" : "") + ": " + topThing.item.name);
	}

	var i = 1;
	localStats.powerUps.forEach(function(pu) { powerups[pu.name] = '#pu' + i++; });

	var getLeader = function() {
		return $('div#leaderBoard table tbody').children('tr').first().children('td').eq(1).text();
	}

	var getClickingBps = function() {
		return CoffeeCup.calcBytesPerClick() * 20;
	}

	var clickCup = function() {
		clickButton.click();
	}

	var drip = function() {
		dripButton.click();
	}

	var getBytes = function() {
		return localStats.byteCount;
	}

	var getCapacity = function() {
		return localStats.memoryCapacity;
	}

	var atMaxBytes = function() {
		return getBytes() == getCapacity();
	}

	var getBPS = function() {
		return localStats.bps;
	}

	var atBPSCap = function() {
		return getBPS() >= BPSThreshold;
	}

	var getMyName = function() {
		return networkUser.userName;
	}

	var getSortedUpgradeList = function() {
		var upgrades = [];
		localStats.powerUps.forEach(function(e) {
			e.upgrades.forEach(function(u) {
				if(u._unlocked && ! u._purchased) {
					upgrades.push(u);
				}
			});
		});
		localStats.specialUpgrades.forEach(function(u) {
			if(!u._purchased) {
				upgrades.push(u);
			}
		});

		upgrades.sort(function(a,b) {
			return a.price - b.price;
		});
		return upgrades;
	}

	var buyUpgrade = function(name) {
		// Not thread safe!  If someone else uses the bytes we'll never know.
		var i = 1;
		getSortedUpgradeList().forEach(function(u) {
			if(u.name == name) {
				var upgrade = $('#upg' + i);
				upgrade.click();

				for(var n=0; n<localStats.specialUpgrades.length; n++) {
					if(localStats.specialUpgrades[n].name == name) {
						$(modalButton).click();
						break;
					}
				}
				return true;
			}
			i++;
		});
		return false;
	}

	var setBPSThreshold = function(num) {
		if(num && num > 0) {
			BPSThreshold = num * 1000 * 1000;
		}
		return BPSThreshold;
	}

	var setClickInterval = function(num) {
		if(num && num > 0) {
			clickInterval = num;
		}
		if(clickerPid != -1) {
			clearInterval(clickerPid);
			clickerPid = setInterval(function() { clickCup(); }, clickInterval);
		}
		return clickInterval;
	}

	var setBenevolentLeader = function(bool) {
		benevolentLeader = bool || false;
		return benevolentLeader;
	}

	var setShowPops = function(bool) {
		showPops = bool || false;
		return showPops;
	}

	var stage1 = function() {
		if(story.state == 6) {
			drip();
		}

		if(story.state == 9) {
			buyPowerup('Cursor');
		}

		if(story.state == 11) {
			buyUpgrade('Enhanced Precision');
		}

		if(story.state == 12) {
			console.log("Proceeding to stage 2 (Purchase).");
			clearInterval(stage1Pid);
			stage2Pid = setInterval(function() { stage2(); }, 500);
			return;
		}

		if(story.state != 12 && atMaxBytes()) {
			drip();
		}
	}

	var stage2 = function() {
		if(atBPSCap()) {
			console.log("Proceeding to stage 3 (Win).");
			topThing = null;
			clearInterval(stage2Pid);
			stage3Pid = setInterval(function() { stage3(); }, 500);
			return;
		}

		if(topThing == null) {
			getNewTopThing();
		}

		if(getBytes() >= topThing.realPrice) {
			if(topThing.isUpgrade) {
				buyUpgrade(topThing.item.name);
			} else {
				buyPowerup(topThing.item.name);
			}

			getNewTopThing();
		} else {
			if(getCapacity() < topThing.realPrice) {
				if((getBytes() + getCapacity()) >= topThing.realPrice || atMaxBytes()) {
					drip();
				}
			}
        }
	}

	var stage3 = function() {
		if(!atBPSCap()) {
			console.log("Reverting to stage 2 (Purchase).");
			currentLeader = null;
			timeOfLeaderChange = null;
			clearInterval(stage3Pid);
			stage2Pid = setInterval(function() { stage2(); }, 500);
			return;
		}

		var leaderName = getLeader();
		if(!currentLeader) {
			currentLeader = getMyName();
		}

		if (leaderName != getMyName()) {
			if(currentLeader == getMyName()) {
				currentLeader = leaderName;
				timeOfLeaderChange = $.now();
				console.log("As of " + timeOfLeaderChange + " there is one fairer in the land... it is '" + leaderName + "'.");

			} else if(leaderName != currentLeader) {
				console.log("Leader changed from '" + currentLeader + "' to '" + leaderName + "'.");
				currentLeader = leaderName;
			}
			drip();

		} else {
			if (currentLeader != leaderName) {
				currentLeader = leaderName;
				var diffTime = $.time;
				console.log("As of " + $.now() + " you are the fairest of them all (it took " + diffTime + " to recover).");
			}

			if(!benevolentLeader) {
				drip();
			}
		}
	}

	var stop = function() {
		clearInterval(stage1Pid);
		clearInterval(stage2Pid);
		clearInterval(stage3Pid);
		clearInterval(clickerPid);
		stage1Pid = -1;
		stage2Pid = -1;
		stage3Pid = -1;
		clickerPid = -1;
	}

	var start = function() {
		console.log('Starting DripBot v' + version + '!');
		if (story.inProgress) {
			console.log("Starting or resuming story.");
			stage1Pid = setInterval(function() { stage1(); }, 100);
		} else if(!atBPSCap()) {
			console.log("Resuming stage 2 (Purchase).");
			stage2Pid = setInterval(function() { stage2(); }, 500);
		} else {
			console.log("Resuming stage 3 (Win).");
			stage3Pid = setInterval(function() { stage3(); }, 500);
		}
		clickerPid = setInterval(function() { clickCup(); }, clickInterval);
	}

	var restart = function() {
		stop();
		start();
	}

	var init = function() {
		document.hasFocus = function() { return true; };
		AnonymousUserManager.canDrip = function() { return true; };
		popManager.oldNewPop = popManager.newPop;
		popManager.newPop = function(e, t, a) {
			if(showPops || (e.indexOf('addMem') == -1 && e != 'chartContainer')) {
				popManager.oldNewPop(e,t,a);
			}
		}
		clickCup();
		setTimeout(function() { start(); }, 500);
	}

	init();

	return {
		buyPowerup: buyPowerup,
		buyUpgrade: buyUpgrade,

		getSortedUpgradeList: getSortedUpgradeList,
		getOTBList: getOTBList,
		sortOTBList: sortOTBList,

		click: clickCup,
		drip: drip,

		setBPSThreshold: setBPSThreshold,
		setBenevolentLeader: setBenevolentLeader,
		setShowPops: setShowPops,
		setClickInterval: setClickInterval,

		stop: stop,
		restart: restart
	};
}($, (typeof($dripBot) !== 'undefined' ? $dripBot : null)));
<|endoftext|>


<commit_before>// element.js - Javascript class which facilitates work with the DOM
// v. 1.0.7
// (c) 2011 SirAnthony <anthony at adsorbtion.org>
// http://github.com/SirAnthony/element.js/

var element = new ( function(){

    this.init = function(){
        var ua = navigator.userAgent.toLowerCase();
        if (! (ua.indexOf("msie") != -1 && ua.indexOf("webtv") == -1) ) {
            if ( !isUndef(Node) && !isUndef(Node.prototype) && isFunction(Node.prototype.__defineGetter__)){
                Node.prototype.__defineGetter__("innerText", function() { return this.textContent; });
                Node.prototype.__defineSetter__("innerText", function(val){this.textContent ="";
                    this.appendChild(document.createTextNode(val));});
            }
        }
    }

    this.downTree = function(funct, obj, er){
        if(!funct || !obj) return;
        for(var i=0; i < obj.childNodes.length; i++){
            var e = funct(obj.childNodes[i]);
            if(e) return e;
        }
        if(er) return true;
    }

    this.addOption = function(obj, arr, sel){
        var opts = new Array();
        var selected = null;
        if(isArray(sel))
            selected = sel;
        else if(isString(sel))
            selected = new Array(sel);

        if(isArray(arr)){ //isArray?
            for(var i=0; i < arr.length; i++){
                if(isArray(arr[i]) && arr[i].length == 2)
                    opts.push(this.create('option', {value: arr[i][0], text: arr[i][1]}));
                else
                    opts.push(this.create('option', {value: arr[i], text: arr[i]}));
            }
        }else{//isHash?
            for(var i in arr)
                opts.push(this.create('option', {value: i, text: arr[i]}));
        }
        if(selected){
            for(var i=0; i < opts.length; i++){
                for(var j=0; j < selected.length; j++){
                    if(opts[i].value == selected[j])
                        opts[i].selected = 'selected';
                }
            }
        }
        if(obj)
            this.appendChild(obj, opts);
        else
            return opts;
    }

    this.getSelected = function(obj){
        var sel = obj.childNodes;
        var select;
        if(sel)
            for(select in sel){ if(sel[select].selected) break; }
        return select;
    }

    this.removeAllChilds = function(el){
        if(!el) return;
        while(el.hasChildNodes()){
            el.removeChild(el.lastChild);
        }
    }

    this.create = function(elem, params, childs){
        if(!elem || elem == '') elem = 'text';
        var elm = document.createElement(elem);
        for(var i in params){
            if(i == 'choices'){
                this.addOption(elm, params[i], params['value']);
            }else if(i == 'style' && isHash(params[i])){
                for(var j in params[i])
                    elm.style[j] = params[i][j];
            }else{
                elm[i] = params[i];
            }
        }
        if(childs)
            this.appendChild(elm, childs);
        return elm;
    }

    this.remove = function(elem){
        if(!elem) return;
        if(isArray(elem)){
            for(var el in elem)
                this.remove(elem[el]);
        }else{
            this.removeAllChilds(elem);
            if(elem.parentNode)
                elem.parentNode.removeChild(elem);
        }
    }

    this.appendChild = function(o, arr){
        function deepCopy(obj){
            if(isArray(obj)){
                var out = [];
                var len = obj.length;
                for(var i = 0 ; i < len; i++)
                    out[i] = arguments.callee(obj[i]);
                return out;
            }
            if(isHash(obj)){
                var out = {};
                for(var i in obj)
                    out[i] = arguments.callee(obj[i]);
                return out;
            }
            return obj;
        }
        this.appendChildNoCopy(o, deepCopy(arr));
    }

    this.appendChildNoCopy = function(obj, arr){
        var ar = new Array();
        if(isArray(arr)){
            ar = arr;
        }else{
            if(isFunction(arr))
                arr = arr();
            if(isString(arr)){
                try{
                    arr = eval(arr);
                }catch(e){}
            }
            ar.push(arr);
        }
        var l = ar.length;
        for(var i=0; i < l; i++){
            if(!ar[i] || (!isElement(ar[i]) && !isArray(ar[i]) && !isHash(ar[i]) && !isString(ar[i]))) continue;
            if(isHash(ar[i])){
                var elems = ar[i];
                for(var key in elems){
                    if(elems[key] && !isHash(elems[key]))
                        continue;
                    ar[i] = this.create(key, elems[key]);
                }
            }else if(isString(ar[i])){
                ar[i] = this.create(ar[i]);
            }
            if(isArray(ar[i])){
                this.appendChildNoCopy(ar[i-1], ar[i]);
            }else{
                obj.appendChild(ar[i]);
            }
        }
    }

    //Insert elem before(after if next) obj
    this.insert = function(obj, elem, next){
        if(isHash(elem)){
            var el;
            for(var key in elem){
                if(!isHash(elem[key])) continue;
                el = this.create(key, elem[key]);
            }
            elem = el;
        }else if(isArray(elem)){
            var el = elem.shift();
            elem = elem.shift();
            if(isElement(el)){
                element.appendChild(el, elem);
                elem = el;
            }else if(isHash(el)){
                for(var i in el)
                    if(el.hasOwnProperty(i)){
                        elem = this.create(i, el[i], elem)
                        break;
                    }
            }else if(isString(el)){
                elem = this.create(el, null, elem)
            }else{
                throw new Error(el + ' is not element.');
            }
        }
        var ins = next ? obj.nextSibling : obj
        obj.parentNode.insertBefore(elem, ins);
    }

    this.getOffset = function(obj, parent){
        if(!obj) return;
        parent = parent ? parent : document.body;
        var el = obj;
        var offset = {top: el.offsetTop, left: el.offsetLeft};
        if((el = el.offsetParent) && el != parent){
            do {
                offset.top += el.offsetTop;
                offset.left += el.offsetLeft;
            } while(el.offsetParent != parent && (el = el.offsetParent));
        }
        return offset;
    }

})();

function isElement(object){return !!(object && object.nodeType == 1);}
function isArray(object){return object != null && typeof object == "object" &&
    'splice' in object && 'join' in object;}
function isHash(object) {
    return object &&
        typeof object=="object" &&
        (object==window||object instanceof Object) &&
        !object.nodeName &&
        !isArray(object);
}
function isFunction(object){return typeof object == "function";}
function isString(object){return typeof object == "string";}
function isNumber(object){return typeof object == "number";}
function isError(object){return object instanceof Error ||
    (typeof e === 'object' && objectToString(e) === '[object Error]');}
function isUndef(object){return typeof object == "undefined";}

element.init();
<commit_msg>Some ie fixes.<commit_after>// element.js - Javascript class which facilitates work with the DOM
// v. 1.0.7
// (c) 2011 SirAnthony <anthony at adsorbtion.org>
// http://github.com/SirAnthony/element.js/

var element = new ( function(){

    this.init = function(){
        var ua = navigator.userAgent.toLowerCase();
        if (! (ua.indexOf("msie") != -1 && ua.indexOf("webtv") == -1) ) {
            if ( !isUndef(Node) && !isUndef(Node.prototype) && isFunction(Node.prototype.__defineGetter__)){
                Node.prototype.__defineGetter__("innerText", function() { return this.textContent; });
                Node.prototype.__defineSetter__("innerText", function(val){this.textContent ="";
                    this.appendChild(document.createTextNode(val));});
            }
        }
    }

    this.downTree = function(funct, obj, er){
        if(!funct || !obj) return;
        for(var i=0; i < obj.childNodes.length; i++){
            var e = funct(obj.childNodes[i]);
            if(e) return e;
        }
        if(er) return true;
    }

    this.addOption = function(obj, arr, sel){
        var opts = new Array();
        var selected = null;
        if(isArray(sel))
            selected = sel;
        else if(isString(sel) || isNumber(sel)){
            selected = new Array();
            selected.push(sel);
        }

        if(isArray(arr)){ //isArray?
            for(var i=0; i < arr.length; i++){
                if(isArray(arr[i]) && arr[i].length == 2)
                    opts.push(this.create('option', {value: arr[i][0], innerText: arr[i][1]}));
                else
                    opts.push(this.create('option', {value: arr[i], innerText: arr[i]}));
            }
        }else{//isHash?
            for(var i in arr)
                opts.push(this.create('option', {value: i, innerText: arr[i]}));
        }
        if(selected){
            for(var i=0; i < opts.length; i++){
                for(var j=0; j < selected.length; j++){
                    if(opts[i].value == selected[j])
                        opts[i].selected = 'selected';
                }
            }
        }
        if(obj)
            this.appendChild(obj, opts);
        else
            return opts;
    }

    this.getSelected = function(obj){
        var sel = obj.childNodes;
        var select;
        if(sel)
            for(select in sel){ if(sel[select].selected) break; }
        return select;
    }

    this.removeAllChilds = function(el){
        if(!el) return;
        while(el.hasChildNodes()){
            el.removeChild(el.lastChild);
        }
    }

    this.create = function(elem, params, childs){
        if(!elem || elem == '') elem = 'text';
        var elm = document.createElement(elem);
        for(var i in params){
            if(i == 'choices'){
                this.addOption(elm, params[i], params['value']);
            }else if(i == 'style' && isHash(params[i])){
                for(var j in params[i])
                    elm.style[j] = params[i][j];
            }else{
                elm[i] = params[i];
            }
        }
        if(childs)
            this.appendChild(elm, childs);
        return elm;
    }

    this.remove = function(elem){
        if(!elem) return;
        if(isArray(elem)){
            for(var el=0; el<elem.length; el++)
                this.remove(elem[el]);
        }else{
            this.removeAllChilds(elem);
            if(elem.parentNode)
                elem.parentNode.removeChild(elem);
        }
    }

    this.appendChild = function(o, arr){
        function deepCopy(obj){
            if(isArray(obj)){
                var out = [];
                var len = obj.length;
                for(var i = 0 ; i < len; i++)
                    out[i] = arguments.callee(obj[i]);
                return out;
            }
            if(isHash(obj)){
                var out = {};
                for(var i in obj)
                    out[i] = arguments.callee(obj[i]);
                return out;
            }
            return obj;
        }
        this.appendChildNoCopy(o, deepCopy(arr));
    }

    this.appendChildNoCopy = function(obj, arr){
        var ar = new Array();
        if(isArray(arr)){
            ar = arr;
        }else{
            if(isFunction(arr))
                arr = arr();
            if(isString(arr)){
                try{
                    arr = eval(arr);
                }catch(e){}
            }
            ar.push(arr);
        }
        var l = ar.length;
        for(var i=0; i < l; i++){
            if(!ar[i] || (!isElement(ar[i]) && !isArray(ar[i]) && !isHash(ar[i]) && !isString(ar[i]))) continue;
            if(isHash(ar[i])){
                var elems = ar[i];
                for(var key in elems){
                    if(elems[key] && !isHash(elems[key]))
                        continue;
                    ar[i] = this.create(key, elems[key]);
                }
            }else if(isString(ar[i])){
                ar[i] = this.create(ar[i]);
            }
            if(isArray(ar[i])){
                this.appendChildNoCopy(ar[i-1], ar[i]);
            }else{
                obj.appendChild(ar[i]);
            }
        }
    }

    //Insert elem before(after if next) obj
    this.insert = function(obj, elem, next){
        if(isHash(elem)){
            var el;
            for(var key in elem){
                if(!isHash(elem[key])) continue;
                el = this.create(key, elem[key]);
            }
            elem = el;
        }else if(isArray(elem)){
            var el = elem.shift();
            elem = elem.shift();
            if(isElement(el)){
                element.appendChild(el, elem);
                elem = el;
            }else if(isHash(el)){
                for(var i in el)
                    if(el.hasOwnProperty(i)){
                        elem = this.create(i, el[i], elem)
                        break;
                    }
            }else if(isString(el)){
                elem = this.create(el, null, elem)
            }else{
                throw new Error(el + ' is not element.');
            }
        }
        var ins = next ? obj.nextSibling : obj
        obj.parentNode.insertBefore(elem, ins);
    }

    this.getOffset = function(obj, parent){
        if(!obj) return;
        parent = parent ? parent : document.body;
        var el = obj;
        var offset = {top: el.offsetTop, left: el.offsetLeft};
        if((el = el.offsetParent) && el != parent){
            do {
                offset.top += el.offsetTop;
                offset.left += el.offsetLeft;
            } while(el.offsetParent != parent && (el = el.offsetParent));
        }
        return offset;
    }

})();

function isElement(object){return !!(object && object.nodeType == 1);}
function isArray(object){return object != null && typeof object == "object" &&
    'splice' in object && 'join' in object;}
function isHash(object) {
    return object &&
        typeof object=="object" &&
        (object==window||object instanceof Object) &&
        !object.nodeName &&
        !isArray(object);
}
function isFunction(object){return typeof object == "function";}
function isString(object){return typeof object == "string";}
function isNumber(object){return typeof object == "number";}
function isError(object){return object instanceof Error ||
    (typeof e === 'object' && objectToString(e) === '[object Error]');}
function isUndef(object){return typeof object == "undefined";}

element.init();
<|endoftext|>


<commit_before>/*! emitter.js v0.0.0 - Nicolas Gallagher - MIT license */

;(function (global) {

'use strict';

function Emitter() {
}

/**
 * Expose `Emitter`
 */

// node export
if (typeof exports === 'object') {
    module.exports = Emitter;
}
// amd export
else if (typeof define === 'function' && define.amd) {
    define(function () {
        return Emitter;
    });
}
// browser global
else {
    global.Emitter = Emitter;
}

}(this));
<commit_msg>Implement `getListeners` method<commit_after>/*! emitter.js v0.0.0 - Nicolas Gallagher - MIT license */

;(function (global) {

'use strict';

function Emitter() {
}

/**
 * Returns an array of callbacks for the specified event.
 * The event registry will be initialized if required.
 *
 * @param {String} event
 * @return {Function[]} callbacks
 * @api public
 */

Emitter.prototype.getListeners = function (event) {
    // get the registry; create it if missing
    var registry = this._registry || (this._registry = {});
    // get the array of callbacks for an event; create it if missing
    var callbacks = registry[event] || (registry[event] = []);

    return callbacks;
};

/**
 * Expose `Emitter`
 */

// node export
if (typeof exports === 'object') {
    module.exports = Emitter;
}
// amd export
else if (typeof define === 'function' && define.amd) {
    define(function () {
        return Emitter;
    });
}
// browser global
else {
    global.Emitter = Emitter;
}

}(this));
<|endoftext|>


<commit_before>var NUMBERS = ['int32', 'int64', 'uint32', 'uint64', 'sint32', 'sint64', 'bool', 'enum', 'float', 'double'];
var varint = require('varint');

var encodeDouble = function(num) {
	var buf = new Buffer(8);
	buf.writeDoubleBE(num, 0);
	return buf;
};

var encodeBoolean = function(val) {
	return new Buffer(varint.encode(val ? 1 : 0));
};

var encodeField = function(field, type) {
	return new Buffer(varint.encode(field << 3 | type));
};

var encodeVarint = function(num) {
	return new Buffer(varint.encode(num));
};

var push = function(pool, val) {
	pool.push(val);
	return val.length;
};

var compile = function(schema) {
	var subtype = function(main) {
		if (!main.fields.length) return function(obj, pool) { return 0; };
		return main.fields
			.map(function(field, i) {
				var tag = field.tag || i;
				var key = field.name;

				var ondouble = function(obj, pool) {
					return push(pool, encodeField(tag, 5)) + push(pool, encodeDouble(obj[key]));
				};

				var onboolean = function(obj, pool) {
					return push(pool, encodeBoolean(obj[key]));
				};

				var onvarint = function(obj, pool) {
					return push(pool, encodeField(tag, 0)) + push(pool, obj[key]);
				};

				var onbytes = function(obj, pool) {
					var val = obj[key];
					return push(pool, encodeField(tag, 2)) + push(pool, encodeVarint(val.length)) + push(pool, val);
				};

				var onstring = function(obj, pool) {
					var val = new Buffer(obj[key]);
					return push(pool, encodeField(tag, 2)) + push(pool, encodeVarint(val.length)) + push(pool, val);
				};

				var onobject = function(type) {
					var enc = subtype(type);

					return function(obj, pool) {
						var offset = push(pool, encodeField(tag, 2));
						var i = pool.push(null)-1;
						var len = enc(obj[key], pool);
						pool[i] = encodeVarint(len);
						return offset + pool[i].length + len;
					};
				};

				var onarray = function(type) {
					var enc = subtype(type.items);

					return function(obj, pool) {
						var offset = push(pool, encodeField(tag, 2));
						var i = pool.push(null)-1;
						var len = 0;

						obj[key].forEach(function(item) {
							len += enc(item, pool);
						});

						pool[i] = encodeVarint(len);
						return offset + pool[i].length + len;
					};
				};

				switch (field.type) {
					case 'int32':
					case 'int64':
					case 'uint32':
					case 'uint64':
					case 'sint32':
					case 'sint64':
					case 'enum':
					return onvarint;

					case 'float':
					case 'double':
					case 'number':
					return ondouble;

					case 'bytes':
					return onbytes;

					case 'string':
					return onstring;

					case 'bool':
					return onboolean;

					case 'object':
					return onobject(field);

					case 'array':
					return onarray(field);
				}

				if (messages[field.type]) return onsubtype(messages[field.type]);

				throw new Error('Unsupported field type: '+field.type);
			})
			.reduce(function(a, b) {
				return function(obj, pool) {
					return a(obj, pool) + b(obj, pool);
				};
			});
	};

	var enc = subtype(schema);
	return function(obj) {
		var pool = [];
		return Buffer.concat(pool, enc(obj, pool));
	};
};

module.exports = compile;<commit_msg>support optional fields<commit_after>var NUMBERS = ['int32', 'int64', 'uint32', 'uint64', 'sint32', 'sint64', 'bool', 'enum', 'float', 'double'];
var varint = require('varint');

var encodeDouble = function(num) {
	var buf = new Buffer(8);
	buf.writeDoubleBE(num, 0);
	return buf;
};

var encodeBoolean = function(val) {
	return new Buffer(varint.encode(val ? 1 : 0));
};

var encodeField = function(field, type) {
	return new Buffer(varint.encode(field << 3 | type));
};

var encodeVarint = function(num) {
	return new Buffer(varint.encode(num));
};

var push = function(pool, val) {
	pool.push(val);
	return val.length;
};

var compile = function(schema) {
	var subtype = function(main) {
		if (!main.fields.length) return function(obj, pool) { return 0; };
		return main.fields
			.map(function(field, i) {
				var tag = field.tag || i;
				var key = field.name;

				var wrap = function(fn) {
					if (field.required) return fn;
					return function(obj, pool) {
						if (obj[key] === undefined || obj[key] === null) return 0;
						return fn(obj, pool);
					}
				};

				var ondouble = wrap(function(obj, pool) {
					return push(pool, encodeField(tag, 5)) + push(pool, encodeDouble(obj[key]));
				});

				var onboolean = wrap(function(obj, pool) {
					return push(pool, encodeBoolean(obj[key]));
				});

				var onvarint = wrap(function(obj, pool) {
					return push(pool, encodeField(tag, 0)) + push(pool, obj[key]);
				});

				var onbytes = wrap(function(obj, pool) {
					var val = obj[key];
					return push(pool, encodeField(tag, 2)) + push(pool, encodeVarint(val.length)) + push(pool, val);
				});

				var onstring = wrap(function(obj, pool) {
					var val = new Buffer(obj[key]);
					return push(pool, encodeField(tag, 2)) + push(pool, encodeVarint(val.length)) + push(pool, val);
				});

				var onobject = function(type) {
					var enc = subtype(type);

					return wrap(function(obj, pool) {
						var offset = push(pool, encodeField(tag, 2));
						var i = pool.push(null)-1;
						var len = enc(obj[key], pool);
						pool[i] = encodeVarint(len);
						return offset + pool[i].length + len;
					});
				};

				var onarray = function(type) {
					var enc = subtype(type.items);

					return wrap(function(obj, pool) {
						var offset = push(pool, encodeField(tag, 2));
						var i = pool.push(null)-1;
						var len = 0;

						obj[key].forEach(function(item) {
							len += enc(item, pool);
						});

						pool[i] = encodeVarint(len);
						return offset + pool[i].length + len;
					});
				};

				switch (field.type) {
					case 'int32':
					case 'int64':
					case 'uint32':
					case 'uint64':
					case 'sint32':
					case 'sint64':
					case 'enum':
					return onvarint;

					case 'float':
					case 'double':
					case 'number':
					return ondouble;

					case 'bytes':
					return onbytes;

					case 'string':
					return onstring;

					case 'bool':
					return onboolean;

					case 'object':
					return onobject(field);

					case 'array':
					return onarray(field);
				}

				if (messages[field.type]) return onsubtype(messages[field.type]);

				throw new Error('Unsupported field type: '+field.type);
			})
			.reduce(function(a, b) {
				return function(obj, pool) {
					return a(obj, pool) + b(obj, pool);
				};
			});
	};

	var enc = subtype(schema);
	return function(obj) {
		var pool = [];
		return Buffer.concat(pool, enc(obj, pool));
	};
};

module.exports = compile;<|endoftext|>


<commit_before>module.exports = {
  extends: './non-rules-config.js',
  rules: {
    'import/extensions': 'error',
    'import/newline-after-import': 'error',
    'import/no-named-as-default': 'error',
    'import/no-amd': 'error',
    'import/no-commonjs': 'off',
    'import/no-named-default': 'error',
    'import/no-namespace': 'off',
    'import/no-nodejs-modules': 'off',
    'import/order': [
      1,
      {
        groups: [
          'builtin',
          ['external', 'internal'],
          'parent',
          ['sibling', 'index'],
        ],
      },
    ],
  },
}
<commit_msg>fix: disable import/newline-after-import<commit_after>module.exports = {
  extends: './non-rules-config.js',
  rules: {
    'import/extensions': 'error',
    'import/newline-after-import': 'off',
    'import/no-named-as-default': 'error',
    'import/no-amd': 'error',
    'import/no-commonjs': 'off',
    'import/no-named-default': 'error',
    'import/no-namespace': 'off',
    'import/no-nodejs-modules': 'off',
    'import/order': [
      1,
      {
        groups: [
          'builtin',
          ['external', 'internal'],
          'parent',
          ['sibling', 'index'],
        ],
      },
    ],
  },
}
<|endoftext|>


<commit_before>/**
 * Deal with various features of the fancy "Forms UI" type implementaion
 */
(function($) {
	var fapi = window.wpFormsApi = window.wpFormsApi || {}
		, media = wp.media;

	// Adjust styles to account for variations when using box-sizing
	$.widget('custom.postListMenu', $.ui.autocomplete, {
		_resizeMenu: function() {
			this.menu.element.width($(this.element).outerWidth());
			$(this.menu.element).css('z-index', 10000000);
		},
	});

	// Multiple-list field
	var initializeMultiple = function(context) {
		$(context).find('.wp-form-multiple').each(function() {
			var $container = $(this)
			  , $list = $container.find('.wp-form-multiple-list')
			  , $tmpl = $container.find('.wp-form-multiple-template')
			;
			// do not re-initialize
			if ($container.data('initialized')) {
				return;
			}

			function reindex() {
				// Note which elements are checked to prevent radio buttons from losing
				// their checked state when elements are renamed (and there is a brief
				// name collision!)
				var $checked = $list.find(':checked');

				$list.find('> li').each(function(i) {
					var $item = $(this);

					$item.find('*').each(function() {
						// Replace patterns like -2- or [4] with -$index- and [$index] in attributes
						// Not exactly super safe, but easy
						for(var j = 0; j < this.attributes.length; j++) {
							this.attributes[j].value = this.attributes[j].value.replace(
								/([ \w_\[\]-]+[\[-])\d+([\]-][ \w_\[\]-]+)/g, '$1' + i + '$2');
						}
					});
				});

				$checked.prop('checked', true);
			}

			$list.sortable({
				handle: '.sort-multiple-item',
				update: reindex
			});

			$container
				// Add a new multiple item on click
				.on('click', '.add-multiple-item', function() {
					var $t = $(this),
						count = $list.children('li').length,
						$html = $($tmpl.text().replace(/%INDEX%/g, count));

					initialize($html);

					$list.append($html);
				})

				// Remove an item item on click
				.on('click', '.remove-multiple-item', function() {
					var $t = $(this),
						$item = $t.parents('li');

					$item.remove();

					reindex();
				});

			// prevent double init which would register multiple click handlers
			$container.data('initialized',true);
		});
	}

	// Image field
	if (media && typeof media == 'function') {
		var WPFormImageField = media.View.extend({
			template: media.template('wp-form-attachment-field'),
			events: {
				'change .wp-form-attachment-id': 'update',
				'click .attachment-delete': 'removeAttachment',
				'click .attachment-container': 'selectAttachment'
			},

			selectAttachment: function() {
				var view = this,
					frameOpts = {
						frame: 'select',
						title: this.input_type == 'image' ? "Select Image" : "Select Attachment"
					};

				if(this.input_type == 'image') {
					frameOpts.library = { type: 'image' };
				}

				media.frame = media(frameOpts).open();

				media.frame.on('select', function(el) {
					var image = this.get('library').get('selection').single();

					view.model.set(image.attributes);
				});
			},

			removeAttachment: function() {
				this.model.clear();
			},

			initialize: function() {
				if(!this.model) {
					this.model = new Backbone.Model();
				}

				this.model.on('change', this.render, this);
			},

			prepare: function() {
				var data = this.model.toJSON();

				data.input_name = this.input_name;
				data.input_type = this.input_type;

				return data;
			},

			update: function() {
				var view = this,
					$field = this.$el.find('.wp-form-attachment-id'),
					attachmentId = $field.val(),
					attachment = media.model.Attachment.get(attachmentId).clone();

				view.model.clear({ silent: true });
				view.model.set({ id: attachmentId });

				$field.addClass('ui-dirty');

				attachment.fetch()
					.done(function() {
						$field.removeClass('ui-dirty');
						view.model.set(this.attributes);
					})
					.fail(function() {
						$field.addClass('ui-dirty');
					});
			}
		});

		var initializeAttachments = function(context) {
			$(context).find('.select-attachment-field').each(function() {
				var view = new WPFormImageField({
					model: media.model.Attachment.get(this.value).clone()
				});

				view.model.fetch();

				// Don't save input name as part of the model as it should be invariant
				view.input_name = this.name;
				view.input_type = $(this).data('attachment-type');

				view.render();

				view.$el.attr('class', $(this).attr('class'));
				view.$el.data('view', view);

				$(this).replaceWith(view.$el);
			});
		}
	}

	var initializePostSelect = function(context, args) {
		args = args || {};

		$(context).find('.wp-form-post-select').each(function() {
			var items = new Backbone.Collection(),
			  $input = $(this),
			  $field = $input.prev('input'),
			  model = new Backbone.Model({ id: $input.val() });

			if($field.length == 0) {
				$field = $('<input type="text" />');
			}

			$(this).before($field);

			if($input.data('title')) {
				$field.val($input.data('title'));
				model.set('title', $input.data('title'));
			}

			$field.attr('placeholder', $input.attr('placeholder'));

			var update = function(ev, ui) {
				var id = ui.item && ui.item.model.get('id');

				$input.val(id);
				$input.trigger('selected', ui.item);
			};

			// Extend jQuery UI autocomplete with a custom resizer
			$field.postListMenu(_.extend(args, {
				source: function(request, response) {
					var attrs = { term: request.term };

					if($input.data('post-type')) {
						attrs['post_type'] = $input.data('post-type').split(' ');
					}

					wp.ajax.post('wp_form_search_posts', attrs)
						.done(function(data) {
							response(_.map(data, function(v) {
								v.id = v.ID;

								var itemModel = new Backbone.Model(v);

								items.remove(v.id);
								items.add(itemModel);

								return {
									label: v.post_title,
									value: v.post_title,
									model: itemModel
								}
							}));
						})
						.fail(function(data) {
							response([]);
						});
				},
				change: update,
				select: update,
				minLength: 0
			}));

			$input.trigger('selected', { model: model });
		});
	}

	var initializeTermSelect = function(context) {
		$(context).find('.wp-form-term-select').each(function() {
			var items = new Backbone.Collection(),
			  $input = $(this),
			  $field = $input.prev('input');

			if($field.length == 0) {
				$field = $('<input type="text" />');
			}

			$(this).before($field);

			if($input.data('name')) {
				$field.val($input.data('name'));
			}

			$field.attr('placeholder', $input.attr('placeholder'));
			$field.attr('class', $input.attr('class').replace(/\bwp-form-[^\s]*\s*/g, ''));

			var update = function(ev, ui) {
				var id = ui.item ? ui.item.model.get('term_id') : '',
						label = ui.item ? ui.item.model.get('name') : '';

				$input.val(id);
				$input.trigger('selected', ui.item);
			};

			$field.autocomplete({
				source: function(request, response) {
					var attrs = { term: request.term };

					if($input.data('taxonomy')) {
						attrs['taxonomy'] = $input.data('taxonomy');
					}

					wp.ajax.post('wp_form_search_terms', attrs)
						.done(function(data) {
							response(_.map(data, function(v) {
								v.id = v.ID;

								var itemModel = new Backbone.Model(v);

								items.remove(v.id);
								items.add(itemModel);

								return {
									label: v.name,
									value: v.name,
									model: itemModel
								}
							}));
						})
						.fail(function(data) {
							response([]);
						});
				},
				change: update,
				select: update,
				minLength: 0
			});
		});
	}

	function initializeConditionalLogic(context) {
		$(context).find('[data-conditional]').on('change', conditionalLogicInputChange).trigger('change');
	}

	function conditionalLogicInputChange() {
		var $this = $(this)
		  , conditions = $this.data('conditional')
			// For checkboxes, we cannot use .val() because it will always
			// return the value attribute regardless if the checkbox is checked
		  , inputValue = $this.is(':checkbox:not(:checked)') ? false : $this.val()
		;

		// no conditions? bail!
		if (!conditions || typeof conditions !== 'object') return;

		// loop through conditions and apply classes
		// { 'element value': { 'target selector': 'class to add', ... }, ... }
		for (var value in conditions) {
			if (conditions[value] && typeof conditions[value] === 'object') {
				for (var selector in conditions[value]) {
					$(selector).toggleClass(conditions[value][selector], value == inputValue);
				}
			}
		}
	}

	function initialize(context) {
		if (media && typeof media == 'function') {
			initializeAttachments(context);
		}

		initializePostSelect(context);
		initializeTermSelect(context);
		initializeConditionalLogic(context);
		initializeMultiple(context);
	}

	$(function() {
		initialize('body');
	});

	fapi.setup = initialize;

	if (media && typeof media == 'function') {
		fapi.initializeAttachments = initializeAttachments;
	}

	fapi.initializePostSelect = initializePostSelect;
	fapi.initializeTermSelect = initializeTermSelect;
	fapi.initializeConditionalLogic = initializeConditionalLogic;
	fapi.initializeMultiple = initializeMultiple;
})(jQuery);
<commit_msg>Use instanceof instead! Its prettier<commit_after>/**
 * Deal with various features of the fancy "Forms UI" type implementaion
 */
(function($) {
	var fapi = window.wpFormsApi = window.wpFormsApi || {}
		, media = wp.media;

	// Adjust styles to account for variations when using box-sizing
	$.widget('custom.postListMenu', $.ui.autocomplete, {
		_resizeMenu: function() {
			this.menu.element.width($(this.element).outerWidth());
			$(this.menu.element).css('z-index', 10000000);
		},
	});

	// Multiple-list field
	var initializeMultiple = function(context) {
		$(context).find('.wp-form-multiple').each(function() {
			var $container = $(this)
			  , $list = $container.find('.wp-form-multiple-list')
			  , $tmpl = $container.find('.wp-form-multiple-template')
			;
			// do not re-initialize
			if ($container.data('initialized')) {
				return;
			}

			function reindex() {
				// Note which elements are checked to prevent radio buttons from losing
				// their checked state when elements are renamed (and there is a brief
				// name collision!)
				var $checked = $list.find(':checked');

				$list.find('> li').each(function(i) {
					var $item = $(this);

					$item.find('*').each(function() {
						// Replace patterns like -2- or [4] with -$index- and [$index] in attributes
						// Not exactly super safe, but easy
						for(var j = 0; j < this.attributes.length; j++) {
							this.attributes[j].value = this.attributes[j].value.replace(
								/([ \w_\[\]-]+[\[-])\d+([\]-][ \w_\[\]-]+)/g, '$1' + i + '$2');
						}
					});
				});

				$checked.prop('checked', true);
			}

			$list.sortable({
				handle: '.sort-multiple-item',
				update: reindex
			});

			$container
				// Add a new multiple item on click
				.on('click', '.add-multiple-item', function() {
					var $t = $(this),
						count = $list.children('li').length,
						$html = $($tmpl.text().replace(/%INDEX%/g, count));

					initialize($html);

					$list.append($html);
				})

				// Remove an item item on click
				.on('click', '.remove-multiple-item', function() {
					var $t = $(this),
						$item = $t.parents('li');

					$item.remove();

					reindex();
				});

			// prevent double init which would register multiple click handlers
			$container.data('initialized',true);
		});
	}

	// Image field
	if (media && typeof media == 'function') {
		var WPFormImageField = media.View.extend({
			template: media.template('wp-form-attachment-field'),
			events: {
				'change .wp-form-attachment-id': 'update',
				'click .attachment-delete': 'removeAttachment',
				'click .attachment-container': 'selectAttachment'
			},

			selectAttachment: function() {
				var view = this,
					frameOpts = {
						frame: 'select',
						title: this.input_type == 'image' ? "Select Image" : "Select Attachment"
					};

				if(this.input_type == 'image') {
					frameOpts.library = { type: 'image' };
				}

				media.frame = media(frameOpts).open();

				media.frame.on('select', function(el) {
					var image = this.get('library').get('selection').single();

					view.model.set(image.attributes);
				});
			},

			removeAttachment: function() {
				this.model.clear();
			},

			initialize: function() {
				if(!this.model) {
					this.model = new Backbone.Model();
				}

				this.model.on('change', this.render, this);
			},

			prepare: function() {
				var data = this.model.toJSON();

				data.input_name = this.input_name;
				data.input_type = this.input_type;

				return data;
			},

			update: function() {
				var view = this,
					$field = this.$el.find('.wp-form-attachment-id'),
					attachmentId = $field.val(),
					attachment = media.model.Attachment.get(attachmentId).clone();

				view.model.clear({ silent: true });
				view.model.set({ id: attachmentId });

				$field.addClass('ui-dirty');

				attachment.fetch()
					.done(function() {
						$field.removeClass('ui-dirty');
						view.model.set(this.attributes);
					})
					.fail(function() {
						$field.addClass('ui-dirty');
					});
			}
		});

		var initializeAttachments = function(context) {
			$(context).find('.select-attachment-field').each(function() {
				var view = new WPFormImageField({
					model: media.model.Attachment.get(this.value).clone()
				});

				view.model.fetch();

				// Don't save input name as part of the model as it should be invariant
				view.input_name = this.name;
				view.input_type = $(this).data('attachment-type');

				view.render();

				view.$el.attr('class', $(this).attr('class'));
				view.$el.data('view', view);

				$(this).replaceWith(view.$el);
			});
		}
	}

	var initializePostSelect = function(context, args) {
		args = args || {};

		$(context).find('.wp-form-post-select').each(function() {
			var items = new Backbone.Collection(),
			  $input = $(this),
			  $field = $input.prev('input'),
			  model = new Backbone.Model({ id: $input.val() });

			if($field.length == 0) {
				$field = $('<input type="text" />');
			}

			$(this).before($field);

			if($input.data('title')) {
				$field.val($input.data('title'));
				model.set('title', $input.data('title'));
			}

			$field.attr('placeholder', $input.attr('placeholder'));

			var update = function(ev, ui) {
				var id = ui.item && ui.item.model.get('id');

				$input.val(id);
				$input.trigger('selected', ui.item);
			};

			// Extend jQuery UI autocomplete with a custom resizer
			$field.postListMenu(_.extend(args, {
				source: function(request, response) {
					var attrs = { term: request.term };

					if($input.data('post-type')) {
						attrs['post_type'] = $input.data('post-type').split(' ');
					}

					wp.ajax.post('wp_form_search_posts', attrs)
						.done(function(data) {
							response(_.map(data, function(v) {
								v.id = v.ID;

								var itemModel = new Backbone.Model(v);

								items.remove(v.id);
								items.add(itemModel);

								return {
									label: v.post_title,
									value: v.post_title,
									model: itemModel
								}
							}));
						})
						.fail(function(data) {
							response([]);
						});
				},
				change: update,
				select: update,
				minLength: 0
			}));

			$input.trigger('selected', { model: model });
		});
	}

	var initializeTermSelect = function(context) {
		$(context).find('.wp-form-term-select').each(function() {
			var items = new Backbone.Collection(),
			  $input = $(this),
			  $field = $input.prev('input');

			if($field.length == 0) {
				$field = $('<input type="text" />');
			}

			$(this).before($field);

			if($input.data('name')) {
				$field.val($input.data('name'));
			}

			$field.attr('placeholder', $input.attr('placeholder'));
			$field.attr('class', $input.attr('class').replace(/\bwp-form-[^\s]*\s*/g, ''));

			var update = function(ev, ui) {
				var id = ui.item ? ui.item.model.get('term_id') : '',
						label = ui.item ? ui.item.model.get('name') : '';

				$input.val(id);
				$input.trigger('selected', ui.item);
			};

			$field.autocomplete({
				source: function(request, response) {
					var attrs = { term: request.term };

					if($input.data('taxonomy')) {
						attrs['taxonomy'] = $input.data('taxonomy');
					}

					wp.ajax.post('wp_form_search_terms', attrs)
						.done(function(data) {
							response(_.map(data, function(v) {
								v.id = v.ID;

								var itemModel = new Backbone.Model(v);

								items.remove(v.id);
								items.add(itemModel);

								return {
									label: v.name,
									value: v.name,
									model: itemModel
								}
							}));
						})
						.fail(function(data) {
							response([]);
						});
				},
				change: update,
				select: update,
				minLength: 0
			});
		});
	}

	function initializeConditionalLogic(context) {
		$(context).find('[data-conditional]').on('change', conditionalLogicInputChange).trigger('change');
	}

	function conditionalLogicInputChange() {
		var $this = $(this)
		  , conditions = $this.data('conditional')
			// For checkboxes, we cannot use .val() because it will always
			// return the value attribute regardless if the checkbox is checked
		  , inputValue = $this.is(':checkbox:not(:checked)') ? false : $this.val()
		;

		// no conditions? bail!
		if (!(conditions instanceof Object)) return;

		// loop through conditions and apply classes
		// { 'element value': { 'target selector': 'class to add', ... }, ... }
		for (var value in conditions) {
			if (conditions[value] instanceof Object) {
				for (var selector in conditions[value]) {
					$(selector).toggleClass(conditions[value][selector], value == inputValue);
				}
			}
		}
	}

	function initialize(context) {
		if (media && typeof media == 'function') {
			initializeAttachments(context);
		}

		initializePostSelect(context);
		initializeTermSelect(context);
		initializeConditionalLogic(context);
		initializeMultiple(context);
	}

	$(function() {
		initialize('body');
	});

	fapi.setup = initialize;

	if (media && typeof media == 'function') {
		fapi.initializeAttachments = initializeAttachments;
	}

	fapi.initializePostSelect = initializePostSelect;
	fapi.initializeTermSelect = initializeTermSelect;
	fapi.initializeConditionalLogic = initializeConditionalLogic;
	fapi.initializeMultiple = initializeMultiple;
})(jQuery);
<|endoftext|>


<commit_before>// Copyright (C) 2016 The Android Open Source Project
//
// 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.
(function() {
  'use strict';

  // Eagerly render Polymer components when backgrounded. (Skips
  // requestAnimationFrame.)
  // @see https://github.com/Polymer/polymer/issues/3851
  // TODO: Reassess after Polymer 2.0 upgrade.
  // @see Issue 4699
  Polymer.RenderStatus._makeReady();

  Polymer({
    is: 'gr-app',

    /**
     * Fired when the URL location changes.
     *
     * @event location-change
     */

    properties: {
      params: Object,
      keyEventTarget: {
        type: Object,
        value() { return document.body; },
      },

      _account: {
        type: Object,
        observer: '_accountChanged',
      },
      _serverConfig: Object,
      _version: String,
      _showChangeListView: Boolean,
      _showDashboardView: Boolean,
      _showChangeView: Boolean,
      _showDiffView: Boolean,
      _showSettingsView: Boolean,
      _showProjectListView: Boolean,
      _showAdminProject: Boolean,
      _showPluginListView: Boolean,
      _showAdminView: Boolean,
      _showCLAView: Boolean,
      _viewState: Object,
      _lastError: Object,
      _lastSearchPage: String,
      _path: String,
    },

    listeners: {
      'page-error': '_handlePageError',
      'title-change': '_handleTitleChange',
      'location-change': '_handleLocationChange',
    },

    observers: [
      '_viewChanged(params.view)',
    ],

    behaviors: [
      Gerrit.BaseUrlBehavior,
      Gerrit.KeyboardShortcutBehavior,
    ],

    keyBindings: {
      '?': '_showKeyboardShortcuts',
    },

    created() {
      // If shadow dom cookie is set, reload the page using shadow dom.
      if (util.getCookie('USE_SHADOW_DOM') === 'true') {
        if (!window.location.href.includes('?dom=shadow')) {
          window.location.href = window.location.href + '?dom=shadow';
        }
      }
    },

    ready() {
      this.$.router.start();

      this.$.restAPI.getAccount().then(account => {
        this._account = account;
      });
      this.$.restAPI.getConfig().then(config => {
        this._serverConfig = config;
      });
      this.$.restAPI.getVersion().then(version => {
        this._version = version;
      });

      this.$.reporting.appStarted();
      this._viewState = {
        changeView: {
          changeNum: null,
          patchRange: null,
          selectedFileIndex: 0,
          showReplyDialog: false,
          diffMode: null,
          numFilesShown: null,
          scrollTop: 0,
        },
        changeListView: {
          query: null,
          offset: 0,
          selectedChangeIndex: 0,
        },
        dashboardView: {
          selectedChangeIndex: 0,
        },
      };
    },

    _accountChanged(account) {
      if (!account) { return; }

      // Preferences are cached when a user is logged in; warm them.
      this.$.restAPI.getPreferences();
      this.$.restAPI.getDiffPreferences();
      this.$.errorManager.knownAccountId =
          this._account && this._account._account_id || null;
    },

    _viewChanged(view) {
      this.$.errorView.classList.remove('show');
      this.set('_showChangeListView', view === 'gr-change-list-view');
      this.set('_showDashboardView', view === 'gr-dashboard-view');
      this.set('_showChangeView', view === 'gr-change-view');
      this.set('_showDiffView', view === 'gr-diff-view');
      this.set('_showSettingsView', view === 'gr-settings-view');
      this.set('_showGroupListView', view === 'gr-admin-group-list');
      this.set('_showProjectListView', view === 'gr-admin-project-list');
      this.set('_showAdminProject', view === 'gr-admin-project');
      this.set('_showPluginListView', view === 'gr-admin-plugin-list');
      this.set('_showAdminView', view === 'gr-admin-view');
      this.set('_showCLAView', view === 'gr-cla-view');
      if (this.params.justRegistered) {
        this.$.registration.open();
      }
      this.$.header.unfloat();
      this.$.footer.unfloat();
    },

    _loginTapHandler(e) {
      e.preventDefault();
      page.show('/login/' + encodeURIComponent(
          window.location.pathname + window.location.hash));
    },

    // Argument used for binding update only.
    _computeLoggedIn(account) {
      return !!(account && Object.keys(account).length > 0);
    },

    _computeShowGwtUiLink(config) {
      return config.gerrit.web_uis && config.gerrit.web_uis.includes('GWT');
    },

    _handlePageError(e) {
      const props = [
        '_showChangeListView',
        '_showDashboardView',
        '_showChangeView',
        '_showDiffView',
        '_showSettingsView',
      ];
      for (const showProp of props) {
        this.set(showProp, false);
      }

      this.$.errorView.classList.add('show');
      const response = e.detail.response;
      const err = {text: [response.status, response.statusText].join(' ')};
      if (response.status === 404) {
        err.emoji = '¯\\_(ツ)_/¯';
        this._lastError = err;
      } else {
        err.emoji = 'o_O';
        response.text().then(text => {
          err.moreInfo = text;
          this._lastError = err;
        });
      }
    },

    _handleLocationChange(e) {
      const hash = e.detail.hash.substring(1);
      let pathname = e.detail.pathname;
      if (pathname.startsWith('/c/') && parseInt(hash, 10) > 0) {
        pathname += '@' + hash;
      }
      this.set('_path', pathname);
      this._handleSearchPageChange();
    },

    _handleSearchPageChange() {
      if (!this.params) {
        return;
      }
      const viewsToCheck = ['gr-change-list-view', 'gr-dashboard-view'];
      if (viewsToCheck.includes(this.params.view)) {
        this.set('_lastSearchPage', location.pathname);
      }
    },

    _handleTitleChange(e) {
      if (e.detail.title) {
        document.title = e.detail.title + ' · Gerrit Code Review';
      } else {
        document.title = '';
      }
    },

    _showKeyboardShortcuts(e) {
      if (this.shouldSuppressKeyboardShortcut(e)) { return; }
      this.$.keyboardShortcuts.open();
    },

    _handleKeyboardShortcutDialogClose() {
      this.$.keyboardShortcuts.close();
    },

    _handleAccountDetailUpdate(e) {
      this.$.mainHeader.reload();
      if (this.params.view === 'gr-settings-view') {
        this.$$('gr-settings-view').reloadAccountDetail();
      }
    },

    _handleRegistrationDialogClose(e) {
      this.params.justRegistered = false;
      this.$.registration.close();
    },
  });
})();
<commit_msg>Fix Polylint warning<commit_after>// Copyright (C) 2016 The Android Open Source Project
//
// 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.
(function() {
  'use strict';

  // Eagerly render Polymer components when backgrounded. (Skips
  // requestAnimationFrame.)
  // @see https://github.com/Polymer/polymer/issues/3851
  // TODO: Reassess after Polymer 2.0 upgrade.
  // @see Issue 4699
  Polymer.RenderStatus._makeReady();

  Polymer({
    is: 'gr-app',

    /**
     * Fired when the URL location changes.
     *
     * @event location-change
     */

    properties: {
      params: Object,
      keyEventTarget: {
        type: Object,
        value() { return document.body; },
      },

      _account: {
        type: Object,
        observer: '_accountChanged',
      },
      _serverConfig: Object,
      _version: String,
      _showChangeListView: Boolean,
      _showDashboardView: Boolean,
      _showChangeView: Boolean,
      _showDiffView: Boolean,
      _showSettingsView: Boolean,
      _showProjectListView: Boolean,
      _showAdminProject: Boolean,
      _showPluginListView: Boolean,
      _showAdminView: Boolean,
      _showCLAView: Boolean,
      _showGroupListView: Boolean,
      _viewState: Object,
      _lastError: Object,
      _lastSearchPage: String,
      _path: String,
    },

    listeners: {
      'page-error': '_handlePageError',
      'title-change': '_handleTitleChange',
      'location-change': '_handleLocationChange',
    },

    observers: [
      '_viewChanged(params.view)',
    ],

    behaviors: [
      Gerrit.BaseUrlBehavior,
      Gerrit.KeyboardShortcutBehavior,
    ],

    keyBindings: {
      '?': '_showKeyboardShortcuts',
    },

    created() {
      // If shadow dom cookie is set, reload the page using shadow dom.
      if (util.getCookie('USE_SHADOW_DOM') === 'true') {
        if (!window.location.href.includes('?dom=shadow')) {
          window.location.href = window.location.href + '?dom=shadow';
        }
      }
    },

    ready() {
      this.$.router.start();

      this.$.restAPI.getAccount().then(account => {
        this._account = account;
      });
      this.$.restAPI.getConfig().then(config => {
        this._serverConfig = config;
      });
      this.$.restAPI.getVersion().then(version => {
        this._version = version;
      });

      this.$.reporting.appStarted();
      this._viewState = {
        changeView: {
          changeNum: null,
          patchRange: null,
          selectedFileIndex: 0,
          showReplyDialog: false,
          diffMode: null,
          numFilesShown: null,
          scrollTop: 0,
        },
        changeListView: {
          query: null,
          offset: 0,
          selectedChangeIndex: 0,
        },
        dashboardView: {
          selectedChangeIndex: 0,
        },
      };
    },

    _accountChanged(account) {
      if (!account) { return; }

      // Preferences are cached when a user is logged in; warm them.
      this.$.restAPI.getPreferences();
      this.$.restAPI.getDiffPreferences();
      this.$.errorManager.knownAccountId =
          this._account && this._account._account_id || null;
    },

    _viewChanged(view) {
      this.$.errorView.classList.remove('show');
      this.set('_showChangeListView', view === 'gr-change-list-view');
      this.set('_showDashboardView', view === 'gr-dashboard-view');
      this.set('_showChangeView', view === 'gr-change-view');
      this.set('_showDiffView', view === 'gr-diff-view');
      this.set('_showSettingsView', view === 'gr-settings-view');
      this.set('_showGroupListView', view === 'gr-admin-group-list');
      this.set('_showProjectListView', view === 'gr-admin-project-list');
      this.set('_showAdminProject', view === 'gr-admin-project');
      this.set('_showPluginListView', view === 'gr-admin-plugin-list');
      this.set('_showAdminView', view === 'gr-admin-view');
      this.set('_showCLAView', view === 'gr-cla-view');
      if (this.params.justRegistered) {
        this.$.registration.open();
      }
      this.$.header.unfloat();
      this.$.footer.unfloat();
    },

    _loginTapHandler(e) {
      e.preventDefault();
      page.show('/login/' + encodeURIComponent(
          window.location.pathname + window.location.hash));
    },

    // Argument used for binding update only.
    _computeLoggedIn(account) {
      return !!(account && Object.keys(account).length > 0);
    },

    _computeShowGwtUiLink(config) {
      return config.gerrit.web_uis && config.gerrit.web_uis.includes('GWT');
    },

    _handlePageError(e) {
      const props = [
        '_showChangeListView',
        '_showDashboardView',
        '_showChangeView',
        '_showDiffView',
        '_showSettingsView',
      ];
      for (const showProp of props) {
        this.set(showProp, false);
      }

      this.$.errorView.classList.add('show');
      const response = e.detail.response;
      const err = {text: [response.status, response.statusText].join(' ')};
      if (response.status === 404) {
        err.emoji = '¯\\_(ツ)_/¯';
        this._lastError = err;
      } else {
        err.emoji = 'o_O';
        response.text().then(text => {
          err.moreInfo = text;
          this._lastError = err;
        });
      }
    },

    _handleLocationChange(e) {
      const hash = e.detail.hash.substring(1);
      let pathname = e.detail.pathname;
      if (pathname.startsWith('/c/') && parseInt(hash, 10) > 0) {
        pathname += '@' + hash;
      }
      this.set('_path', pathname);
      this._handleSearchPageChange();
    },

    _handleSearchPageChange() {
      if (!this.params) {
        return;
      }
      const viewsToCheck = ['gr-change-list-view', 'gr-dashboard-view'];
      if (viewsToCheck.includes(this.params.view)) {
        this.set('_lastSearchPage', location.pathname);
      }
    },

    _handleTitleChange(e) {
      if (e.detail.title) {
        document.title = e.detail.title + ' · Gerrit Code Review';
      } else {
        document.title = '';
      }
    },

    _showKeyboardShortcuts(e) {
      if (this.shouldSuppressKeyboardShortcut(e)) { return; }
      this.$.keyboardShortcuts.open();
    },

    _handleKeyboardShortcutDialogClose() {
      this.$.keyboardShortcuts.close();
    },

    _handleAccountDetailUpdate(e) {
      this.$.mainHeader.reload();
      if (this.params.view === 'gr-settings-view') {
        this.$$('gr-settings-view').reloadAccountDetail();
      }
    },

    _handleRegistrationDialogClose(e) {
      this.params.justRegistered = false;
      this.$.registration.close();
    },
  });
})();
<|endoftext|>


<commit_before>/*
 * ControllerBase
 */
define(function () {
    console.log('CORE: controllerBase called');
    function controllerBase(id) {
        this.id = id;
    };
    controllerBase.prototype = {
		setModelController: function (modelController) {
			console.log('CORE: controllerBase setModelController(modelController) called');
			this.modelController = modelController;
		},
		setModelEvent: function (modelEvent) {
			console.log('CORE: controllerBase setModelEvent(modelEvent) called');
			this.modelEvent = modelEvent;
			this.modelController.setModelEvent(modelEvent);
		},
		setModelService: function (modelService) {
			console.log('CORE: controllerBase setModelService(modelService) called');
			this.modelService = modelService;
			this.modelController.setModelService(modelService);
		},
        setModel: function (model) {
        	console.log('CORE: controllerBase setModel(model) called');
            this.model = model;
            this.modelController.setModel(model);
        },
		loadModel: function (id) {
			console.log('CORE: controllerBase loadModel(id) called');
			this.modelController.loadModel(id);
		},
        setConfig: function (config) {
        	console.log('CORE: controllerBase setConfig(config) called');
            this.config = config;
            this.modelController.setConfig(config);
            this.viewController.setConfig(config);
        },
		setServiceBus: function (serviceBus) {
			console.log('CORE: controllerBase setServiceBus(serviceBus) called');
			this.serviceBus = serviceBus;
            this.modelController.setServiceBus(serviceBus);
            this.viewController.setServiceBus(serviceBus);
		},
		setViewController: function (viewController) {
			console.log('CORE: controllerBase setViewController(viewController) called');
			this.viewController = viewController;
		},
		setViewEvent: function (viewEvent) {
			console.log('CORE: controllerBase setViewEvent(viewEvent) called');
			this.viewEvent = viewEvent;
			this.viewController.setViewEvent(viewEvent);
		},
		setViewService: function (viewService) {
			console.log('CORE: controllerBase setViewService(viewService) called');
			this.viewService = viewService;
			this.viewController.setViewService(viewService);
		},
		setView: function (view) {
			console.log('CORE: controllerBase setView(view) called');
			this.view = view;
			this.viewController.setView(view);
		},
		loadView: function (id) {
			console.log('CORE: controllerBase loadView(id) called');
			this.viewController.loadView(id);
		},
        renderView: function (bodyDom) {
        	console.log('CORE: controllerBase renderView(bodyDom) called');
			this.viewController.renderView(bodyDom);
        //    bodyDom.prepend('
Controller ' + this.id + ' says "' +
        //              this.model.getTitle() + '"
');
        }
    };
    return controllerBase;
});
<commit_msg>Updated<commit_after>/*
 * ControllerBase
 */
define(function () {
    console.log('CORE: controllerBase called');
    function controllerBase(id) {
        this.id = id;
    };
    controllerBase.prototype = {
		setModelController: function (modelController) {
			console.log('CORE: controllerBase setModelController(modelController) called');
			this.modelController = modelController;
		},
		setModelEvent: function (modelEvent) {
			console.log('CORE: controllerBase setModelEvent(modelEvent) called');
			this.modelEvent = modelEvent;
			this.modelController.setModelEvent(modelEvent);
		},
		setModelService: function (modelService) {
			console.log('CORE: controllerBase setModelService(modelService) called');
			this.modelService = modelService;
			this.modelController.setModelService(modelService);
		},
        setModel: function (model) {
        	console.log('CORE: controllerBase setModel(model) called');
            this.model = model;
            this.modelController.setModel(model);
        },
		loadModel: function (id) {
			console.log('CORE: controllerBase loadModel(id) called');
			this.modelController.loadModel(id);
		},
		setViewController: function (viewController) {
			console.log('CORE: controllerBase setViewController(viewController) called');
			this.viewController = viewController;
		},
        setConfig: function (config) {
        	console.log('CORE: controllerBase setConfig(config) called');
            this.config = config;
            this.modelController.setConfig(config);
            this.viewController.setConfig(config);
        },
		setServiceBus: function (serviceBus) {
			console.log('CORE: controllerBase setServiceBus(serviceBus) called');
			this.serviceBus = serviceBus;
            this.modelController.setServiceBus(serviceBus);
            this.viewController.setServiceBus(serviceBus);
		},
		setViewEvent: function (viewEvent) {
			console.log('CORE: controllerBase setViewEvent(viewEvent) called');
			this.viewEvent = viewEvent;
			this.viewController.setViewEvent(viewEvent);
		},
		setViewService: function (viewService) {
			console.log('CORE: controllerBase setViewService(viewService) called');
			this.viewService = viewService;
			this.viewController.setViewService(viewService);
		},
		setView: function (view) {
			console.log('CORE: controllerBase setView(view) called');
			this.view = view;
			this.viewController.setView(view);
		},
		loadView: function (id) {
			console.log('CORE: controllerBase loadView(id) called');
			this.viewController.loadView(id);
		},
        renderView: function (bodyDom) {
        	console.log('CORE: controllerBase renderView(bodyDom) called');
			this.viewController.renderView(bodyDom);
        //    bodyDom.prepend('
Controller ' + this.id + ' says "' +
        //              this.model.getTitle() + '"
');
        }
    };
    return controllerBase;
});
<|endoftext|>


<commit_before>'use strict';

var JSIGSnippet = require('../lib/jsig-snippet.js');

JSIGSnippet.test('function overloading works', {
    snippet: function m() {/*
        foo('').split('');
        foo(2).split('');
        foo(2) + 4;
        foo('') + 4;
        foo({}) + 4;

        function foo(x) {
            return x;
        }
    */},
    header: function h() {/*
        foo : ((String) => String) &
            ((Number) => Number)
    */}
}, function t(snippet, assert) {
    var meta = snippet.compile();
    assert.equal(meta.errors.length, 3, 'expected three errors');

    var err1 = meta.errors[0];
    assert.equal(err1.type, 'jsig.verify.non-existant-field');
    assert.equal(err1.fieldName, 'split');
    assert.equal(err1.objName, 'foo(2)');
    assert.equal(err1.expected, '{ split: T }');
    assert.equal(err1.actual, 'Number');
    assert.equal(err1.line, 2);

    var err2 = meta.errors[1];
    assert.equal(err2.type,
        'jsig.sub-type.intersection-operator-call-mismatch');
    assert.equal(err2.expected,
        '(String, String) => String & (Number, Number) => Number');
    assert.equal(err2.actual, '[String, Number]');
    assert.equal(err2.operator, '+');
    assert.equal(err2.line, 4);

    var err3 = meta.errors[2];
    assert.equal(err3.type, 'jsig.verify.function-overload-call-mismatch');
    assert.equal(err3.expected, '(String) => String & (Number) => Number');
    assert.equal(err3.actual, '[{}]');
    assert.equal(err3.funcName, 'foo');
    assert.equal(err3.line, 5);

    assert.end();
});
<commit_msg>test: write test for function overload based on str type<commit_after>'use strict';

var JSIGSnippet = require('../lib/jsig-snippet.js');

JSIGSnippet.test('function overloading works', {
    snippet: function m() {/*
        foo('').split('');
        foo(2).split('');
        foo(2) + 4;
        foo('') + 4;
        foo({}) + 4;

        function foo(x) {
            return x;
        }
    */},
    header: function h() {/*
        foo : ((String) => String) &
            ((Number) => Number)
    */}
}, function t(snippet, assert) {
    var meta = snippet.compile();
    assert.equal(meta.errors.length, 3, 'expected three errors');

    var err1 = meta.errors[0];
    assert.equal(err1.type, 'jsig.verify.non-existant-field');
    assert.equal(err1.fieldName, 'split');
    assert.equal(err1.objName, 'foo(2)');
    assert.equal(err1.expected, '{ split: T }');
    assert.equal(err1.actual, 'Number');
    assert.equal(err1.line, 2);

    var err2 = meta.errors[1];
    assert.equal(err2.type,
        'jsig.sub-type.intersection-operator-call-mismatch');
    assert.equal(err2.expected,
        '(String, String) => String & (Number, Number) => Number');
    assert.equal(err2.actual, '[String, Number]');
    assert.equal(err2.operator, '+');
    assert.equal(err2.line, 4);

    var err3 = meta.errors[2];
    assert.equal(err3.type, 'jsig.verify.function-overload-call-mismatch');
    assert.equal(err3.expected, '(String) => String & (Number) => Number');
    assert.equal(err3.actual, '[{}]');
    assert.equal(err3.funcName, 'foo');
    assert.equal(err3.line, 5);

    assert.end();
});

JSIGSnippet.test('overloading based on string argument', {
    snippet: function m() {/*
        on("str", x);
        on("num", y);

        function x(a) {
            a.split("");
        }
        function y(b) {
            b + 4;
        }

        function on(str, listener) {
        }
    */},
    header: function h() {/*
        on: ((str: "str", (String) => void) => void) &
            ((str: "num", (Number) => void) => void)
    */}
}, function t(snippet, assert) {
    snippet.compileAndCheck(assert);
    assert.end();
});
<|endoftext|>


<commit_before>module.exports = function (context, message) {
    var google = require('googleapis');
    var googleAuth = require('google-auth-library');

    var directory = google.admin('directory_v1');
    var groupssettings = google.groupssettings('v1');

    var client_email = process.env.client_email;
    var private_key = process.env.private_key;
    var user_address = 'igor@googleapps.wrdsb.ca';

    // *sigh* because Azure Functions application settings can't handle newlines, let's add them ourselves:
    private_key = private_key.split('\\n').join("\n");

    // prep our credentials for G Suite APIs
    var jwtClient = new google.auth.JWT(
        client_email,
        null,
        private_key,
        ['https://www.googleapis.com/auth/admin.directory.group','https://www.googleapis.com/auth/apps.groups.settings'], // an array of auth scopes
        user_address
    );

    var params = {
        auth: jwtClient,
        alt: "json",
        customer: process.env.CUSTOMER_ID,
        maxResults: 200
    };

    // stores our Groups in the end
    var groups = {};
    var admin_created_groups = {};

    jwtClient.authorize(function(err, tokens) {
        if (err) {
            context.log(err);
            return;
        }
        getGroups(params, function() {
           context.log('Final results: Got ' + Object.getOwnPropertyNames(groups).length + ' groups.');
           context.bindings.allGroups = JSON.stringify(groups);
           context.bindings.adminCreatedGroups = JSON.stringify(admin_created_groups);
           context.done();
        });
    });

    function getGroups(params, callback) {
        directory.groups.list(params, function(err, result) {
            if (err) {
                context.log(result);
                context.done(err);
            }
            context.log(result);
            context.log('Got ' + result.groups.length + ' groups.');
            result.groups.forEach(function(group) {
                groups[group.email] = group;
                if (group.adminCreated) {
                    admin_created_groups[group.email] = group;
                }
            });
            if (result.nextPageToken) {
                params.pageToken = result.nextPageToken;
                getGroups(params, callback);
            } else {
                callback();
            }
        });
    }
};
<commit_msg>log number of admin-created groups found<commit_after>module.exports = function (context, message) {
    var google = require('googleapis');
    var googleAuth = require('google-auth-library');

    var directory = google.admin('directory_v1');
    var groupssettings = google.groupssettings('v1');

    var client_email = process.env.client_email;
    var private_key = process.env.private_key;
    var user_address = 'igor@googleapps.wrdsb.ca';

    // *sigh* because Azure Functions application settings can't handle newlines, let's add them ourselves:
    private_key = private_key.split('\\n').join("\n");

    // prep our credentials for G Suite APIs
    var jwtClient = new google.auth.JWT(
        client_email,
        null,
        private_key,
        ['https://www.googleapis.com/auth/admin.directory.group','https://www.googleapis.com/auth/apps.groups.settings'], // an array of auth scopes
        user_address
    );

    var params = {
        auth: jwtClient,
        alt: "json",
        customer: process.env.CUSTOMER_ID,
        maxResults: 200
    };

    // stores our Groups in the end
    var groups = {};
    var admin_created_groups = {};

    jwtClient.authorize(function(err, tokens) {
        if (err) {
            context.log(err);
            return;
        }
        getGroups(params, function() {
           context.log('Final results: Got ' + Object.getOwnPropertyNames(groups).length + ' groups and ' + Object.getOwnPropertyNames(groups).length + ' admin-created groups.');
           context.bindings.allGroups = JSON.stringify(groups);
           context.bindings.adminCreatedGroups = JSON.stringify(admin_created_groups);
           context.done();
        });
    });

    function getGroups(params, callback) {
        directory.groups.list(params, function(err, result) {
            if (err) {
                context.log(result);
                context.done(err);
            }
            context.log(result);
            context.log('Got ' + result.groups.length + ' groups.');
            result.groups.forEach(function(group) {
                groups[group.email] = group;
                if (group.adminCreated) {
                    admin_created_groups[group.email] = group;
                }
            });
            if (result.nextPageToken) {
                params.pageToken = result.nextPageToken;
                getGroups(params, callback);
            } else {
                callback();
            }
        });
    }
};
<|endoftext|>


<commit_before>/*!
    jQuery.kineticScrollbar a0.1
    Dave Taylor http://the-taylors.org/jquery.kinetic

    This plugin depends on two other plugins
    ----------------------------------------
    jQuery UI Slider
    https://github.com/davetayls/jquery.kinetic
    https://github.com/brandonaaron/jquery-mousewheel

    @license The MIT License (MIT)
    @preserve Copyright (c) <2011> <Dave Taylor http://the-taylors.org>
*/
/*jslint browser: true, vars: true, white: true, forin: true */
/*global define,require */
(function($){
    'use strict';

    var /** @const */ DEFAULT_SETTINGS    = {
          speed: 30
        , barCss: {
            position: 'absolute'
          }
        , handleCss: {
            position: 'absolute'
          }
        }
    ;

    /** add scrollTo method to jquery.kinetic */
    $.kinetic.callMethods.scrollTo = function(settings, options){

        this.scrollLeft = settings.scrollLeft = options.left;
        this.scrollTop  = settings.scrollTop  = options.top;

        if (typeof settings.moved === 'function') {
            settings.moved.call($(this), settings);
        }

    };

    var getProperties = function($wrapper) {
        var wrapper       = $wrapper[0]
        ,   height        = $wrapper.height()
        ,   width         = $wrapper.width()
        ,   left          = wrapper.scrollLeft + width
        ,   top           = wrapper.scrollTop
        ,   step          = (wrapper.scrollHeight - height) / 100
        ,   barStep       = height / 100
        ,   handleHeight  = height / (wrapper.scrollHeight / height)
        ,   stepTop       = 100 - Math.ceil(wrapper.scrollTop/step)
        ,   handleTop     = stepTop * barStep
        ;
        return {
            step: step
        ,   barStep: barStep
        ,   stepTop: stepTop
        ,   height: height
        ,   width: width
        ,   left:  left
        ,   top: top
        ,   handleHeight: handleHeight
        ,   handleTop: handleTop
        };

    };

    $.fn.kineticScrollbar = function(options) {
        var settings = $.extend({}, DEFAULT_SETTINGS, options);
        return this.each(function(){
            var $wrapper = $(this)
            ,   wrapper    = this
            ,   ksettings  = $wrapper.data($.kinetic.settingsKey)
            ,   oldMoved   = ksettings.moved
            ,   $outer     = $('
')
            ,   $bar       = $('
').css(settings.barCss)
            ,   $handle    = $('
').css(settings.handleCss).appendTo($bar)
            ,   isHandle   = false
            ,   properties = getProperties($wrapper)
            ;
            $wrapper
                .wrap($outer)
                .after($bar)
                .addClass('kineticScrollbar-active');

            var moved = function(settings) {
                properties = getProperties($wrapper);

                if (!isHandle) {
                    $bar.slider('value', properties.stepTop);
                }
                if (oldMoved) {
                    oldMoved.apply(this, arguments);
                }
            };
            ksettings.moved = moved;

            //set up the slider
            var sliderMove = function(event, ui) {
                isHandle = true;
                properties = getProperties($wrapper);

                $wrapper.kinetic('scrollTo', {
                    left: wrapper.scrollLeft
                    ,   top:  (100 - ui.value) * properties.step
                });

                isHandle = false;
            };
            $bar.slider({
                orientation: 'vertical',
                min: 0,
                max: 100,
                value: 100,
                slide: sliderMove,
                change: sliderMove
            });

            $wrapper.mousewheel(function(event, delta, deltaX, deltaY) {
                var xShift   = ksettings.x ? deltaX * settings.speed : 0
                ,   yShift     = ksettings.y ? -(deltaY * settings.speed) : 0
                ,   scrollLeft = wrapper.scrollLeft
                ,   scrollTop  = wrapper.scrollTop
                ,   isScrolling = true
                ;

                if (!ksettings.y) {
                    isScrolling = Math.abs(deltaX) > 0.02;
                }
                if (!ksettings.x) {
                    isScrolling = isScrolling && Math.abs(deltaY) > 0.02;
                }

                if (isScrolling) {
                    $wrapper.kinetic('scrollTo', {
                          left: scrollLeft+xShift
                        , top:  scrollTop+yShift
                    });
                    event.preventDefault(); //stop any default behaviour
                }

            });

        });

    };

}(window.jQuery));
<commit_msg>remove scrollbar as not finished or used<commit_after><|endoftext|>