<commit_before>/* jshint devel: true */
var PewPew = {};

!function() {
	'use strict';

	/**
	 * Upgrade class
	 */
	function Upgrade(name, maxLevel, baseCost) {
		var self = this;
		this.name = name;
		this.maxLevel = maxLevel;
		this.level = 0;
		this.baseCost = baseCost;
		/**
		 * The current upgrade's cost
		 */
		this.cost = function cost() {
			return (self.level + 1) * baseCost;
		};
		/**
		 * The upgrade's element id, used to change info on upgrade tab
		 */
		this.getElementId = function getElementId() {
			return "upgrade-" + self.name;
		};
		/**
		 * Fired when this upgrade is bought
		 */
		this.onBuy = function onBuy() {
			document.getElementById(self.getElementId() + "-cost").innerHTML = self
					.cost();
			document.getElementById(self.getElementId() + "-level").innerHTML = self.level;
		};
		/**
		 * generates this upgrade's HTML for upgrade tab
		 */
		this.getHtml = function getHtml() {
			return '
'
					+ self.name + "
" + 'Level: 0
'
					+ 'Cost: '
					+ self.cost() + "" + "
";
		};
		/**
		 * Tries to buy this upgrade, buys the upgrade for player if he has enough money
		 */
		this.tryBuy = function tryBuy() {
			if (self.level >= self.maxLevel) {
				return false;
			}
			if (PewPew.player.money < self.cost()) {
				return false;
			}
			PewPew.player.substractMoney(self.cost());
			self.level++;
			self.onBuy();
		};
	}

	/**
	 * player singleton
	 */
	PewPew.player = {
		money : 0,
		upgrades : {
			damage : new Upgrade("damage", 10, 50),
			income : new Upgrade("income", 10, 100),
			range: new Upgrade("Hit Area", 15, 50)
		},
		/**
		 * The player's current income bonus
		 * @returns {Number}
		 */
		income : function income() {
			return this.upgrades.income.level;
		},
		/**
		 * The player's current damage from hit
		 * @returns {Number}
		 */
		damage : function damage() {
			return this.upgrades.damage.level + 1;
		},
		/**
		 * changes the player's money
		 * @param newMoney the new amount to set
		 */
		changeMoney : function changeMoney(newMoney) {
			this.money = newMoney;
			document.getElementById("money").innerHTML = this.money;
		},
		/**
		 * Adds money to player
		 * @param money the amount to be given
		 */
		addMoney : function addMoney(money) {
			this.changeMoney(this.money + money);
		},
		/**
		 * Removes money from player
		 * @param money the amount to be removed
		 */
		substractMoney : function substractMoney(money) {
			this.addMoney(-money);
		},
		score : 0,
		/**
		 * Adds score to player
		 * @param toAdd the amount
		 */
		addScore : function addScore(toAdd){
			this.score+=toAdd;
			//check the advance to the next level
			if(PewPew.game.levels[PewPew.game.level]<=this.score)
				PewPew.game.level++;
		}
	};
	/**
	 * Fill upgrades tab
	 */
	var html = "";
	for ( var upgrade in PewPew.player.upgrades) {
		if (PewPew.player.upgrades.hasOwnProperty(upgrade)) {
			html += PewPew.player.upgrades[upgrade].getHtml();
		}
	}
	document.getElementById("upgrade-tiles").innerHTML = html;
	// add the event listeners to the created buttons
	var upg;
	for (upgrade in PewPew.player.upgrades) {
		if (PewPew.player.upgrades.hasOwnProperty(upgrade)) {
			upg = PewPew.player.upgrades[upgrade];
			document.getElementById(upg.getElementId()).addEventListener(
					"click", upg.tryBuy);

		}
	}

	/**
	 * Enemy class
	 */
	function Enemy(hp, x, y, image, value) {
		var self = this;
		this.hp = hp;
		this.x = x;
		this.y = y;
		this.setX = function setX(x) {
			self.x = x;
			PewPew.canvas.redraw();
		};
		this.setY = function setY(y) {
			self.y = y;
			PewPew.canvas.redraw();
		};
		this.setXY = function setXY(x, y) {
			self.x = x;
			self.y = y;
			PewPew.canvas.redraw();
		};
		this.image = image;
		this.value = value;
		/**
		 * deals damage to the enemy
		 * @param damage
		 */
		this.receiveDamage = function receiveDamage(damage) {
			self.hp -= damage;
			if (self.hp <= 0) {
				self.onDestroy();
			}
		};
		/**
		 * called when an enemy is destroyed, adds score and money to player and removes the enemy from game
		 */
		this.onDestroy = function onDestroy() {
			PewPew.player.addMoney(self.value + PewPew.player.income());
			PewPew.player.addScore(self.value);
			var index = PewPew.game.enemies.indexOf(self);
			if (index > -1) {
				PewPew.game.enemies.splice(index, 1);
			}
			// redraw the scene
			PewPew.canvas.redraw();
		};
		/**
		 * Checks if the enemy is hit by touching at given coords
		 */
		this.checkHit = function checkHit(x, y){
			return x >= self.x && x <= self.x + self.width && y >= self.y && y <= self.y + self.height;
		};
		this.canvasImage = new Image();
		this.canvasImage.src = this.image;
		this.width=self.canvasImage.width;
		this.height=self.canvasImage.height;
		this.canvasImage.onload = function() {
			PewPew.canvas.context.drawImage(self.canvasImage, self.x, self.y);
			self.width = self.canvasImage.width;
			self.height = self.canvasImage.height;
		};

		PewPew.game.enemies[PewPew.game.enemies.length] = self;
	}

	//The enemy templates
	function Fighter(x, y) {
		Enemy.call(this, 1, x, y, "img/fighter.png", 1);
	}
	Fighter.prototype = Object.create(Enemy.prototype);

	function Mook(x, y) {
		Enemy.call(this, 2, x, y, "img/mook.png", 2);
	}
	Mook.prototype = Object.create(Enemy.prototype);

	function Bomber(x, y) {
		Enemy.call(this, 5, x, y, "img/bomber.png", 5);
	}
	Bomber.prototype = Object.create(Enemy.prototype);

	PewPew.game = {
		level : 1,
		levels : [0,50,200,500,2500,10000,50000,200000,1000000],
		enemies : [],
		/**
		 * handles the hitting the enemies
		 * @param evt the touch event into game area
		 */
		handleHit : function handleHit(evt) {
			evt.preventDefault();
			var touches = evt.changedTouches;
			var touchId, x, y;
			for (var i = 0; i < evt.changedTouches.length; i++) {
				touchId = evt.changedTouches[i].identifier;
				x = evt.changedTouches[i].clientX-PewPew.canvas.element.getBoundingClientRect().left;
				y = evt.changedTouches[i].clientY-PewPew.canvas.element.getBoundingClientRect().top;
				for ( var enemy in PewPew.game.enemies) {
					enemy = PewPew.game.enemies[enemy];
					// test if the enemy is hit
					if (enemy.checkHit(x,y)) {
						enemy.receiveDamage(PewPew.player.damage());
					}
				}
			}

		},
		/**
		 * Spawns an enemy into game and moves him into random place ingame
		 * @param enemy
		 */
		spawnEnemy : function spawnEnemy(enemy) {
			var x = Math.floor(Math.random() * (PewPew.canvas.element.width-enemy.width));
			var y = Math.floor(Math.random() * (PewPew.canvas.element.height-enemy.height));
			enemy.setXY(x, y);
		}

	};
	/**
	 * The game canvas holder where the enemies are spawned
	 */
	PewPew.canvas = {
		element : document.getElementById("canvas"),
		context : null,
		/**
		 * redraws all the enemies alive in game
		 */
		redraw : function redraw() {
			this.context.clearRect(0, 0, PewPew.canvas.element.width,
					PewPew.canvas.element.height);
			for ( var enemy in PewPew.game.enemies) {
				enemy = PewPew.game.enemies[enemy];
				PewPew.canvas.context.drawImage(enemy.canvasImage, enemy.x,
						enemy.y);
			}
		},
	};
	PewPew.canvas.context = PewPew.canvas.element.getContext("2d");
	PewPew.canvas.element.addEventListener("touchstart", PewPew.game.handleHit
			.bind(PewPew.game));

	//The enemy spawning loop
	window.setInterval(function() {
		switch(PewPew.game.level){
		case 1:
			if(Math.random()<=0.33){
				PewPew.game.spawnEnemy(new Fighter(0, 0));
			}
			break;
		case 2:
			if(Math.random()<=0.33){
				if(Math.random()<=0.33){
					PewPew.game.spawnEnemy(new Mook(0, 0));
				}else{
					PewPew.game.spawnEnemy(new Fighter(0, 0));
				}
			}
			break;
		case 3:
			if(Math.random()<=0.66){
				if(Math.random()<=0.66){
					PewPew.game.spawnEnemy(new Mook(0, 0));
				}else{
					PewPew.game.spawnEnemy(new Fighter(0, 0));
				}
			}
			break;

		case 4:
		default:
			if(Math.random()<=0.1){
				PewPew.game.spawnEnemy(new Bomber(0, 0));
				PewPew.game.spawnEnemy(new Fighter(0, 0));
			}else if(Math.random()<=0.66){
				PewPew.game.spawnEnemy(new Mook(0, 0));
			}else{
				PewPew.game.spawnEnemy(new Fighter(0, 0));
			}
			break;
		}
	}, 1000);
}();<commit_msg>Implement the range upgrade<commit_after>/* jshint devel: true */
var PewPew = {};

!function() {
	'use strict';

	/**
	 * Upgrade class
	 */
	function Upgrade(name, maxLevel, baseCost) {
		var self = this;
		this.name = name;
		this.maxLevel = maxLevel;
		this.level = 0;
		this.baseCost = baseCost;
		/**
		 * The current upgrade's cost
		 */
		this.cost = function cost() {
			return (self.level + 1) * baseCost;
		};
		/**
		 * The upgrade's element id, used to change info on upgrade tab
		 */
		this.getElementId = function getElementId() {
			return "upgrade-" + self.name;
		};
		/**
		 * Fired when this upgrade is bought
		 */
		this.onBuy = function onBuy() {
			document.getElementById(self.getElementId() + "-cost").innerHTML = self
					.cost();
			document.getElementById(self.getElementId() + "-level").innerHTML = self.level;
		};
		/**
		 * generates this upgrade's HTML for upgrade tab
		 */
		this.getHtml = function getHtml() {
			return '
'
					+ self.name + "
" + 'Level: 0
'
					+ 'Cost: '
					+ self.cost() + "" + "
";
		};
		/**
		 * Tries to buy this upgrade, buys the upgrade for player if he has enough money
		 */
		this.tryBuy = function tryBuy() {
			if (self.level >= self.maxLevel) {
				return false;
			}
			if (PewPew.player.money < self.cost()) {
				return false;
			}
			PewPew.player.substractMoney(self.cost());
			self.level++;
			self.onBuy();
		};
	}

	/**
	 * player singleton
	 */
	PewPew.player = {
		money : 0,
		upgrades : {
			damage : new Upgrade("damage", 10, 50),
			income : new Upgrade("income", 10, 100),
			range: new Upgrade("Hit Area", 15, 50)
		},
		/**
		 * The player's current income bonus
		 * @returns {Number}
		 */
		income : function income() {
			return this.upgrades.income.level;
		},
		/**
		 * The player's current damage from hit
		 * @returns {Number}
		 */
		damage : function damage() {
			return this.upgrades.damage.level + 1;
		},
		/**
		 * changes the player's money
		 * @param newMoney the new amount to set
		 */
		changeMoney : function changeMoney(newMoney) {
			this.money = newMoney;
			document.getElementById("money").innerHTML = this.money;
		},
		/**
		 * Adds money to player
		 * @param money the amount to be given
		 */
		addMoney : function addMoney(money) {
			this.changeMoney(this.money + money);
		},
		/**
		 * Removes money from player
		 * @param money the amount to be removed
		 */
		substractMoney : function substractMoney(money) {
			this.addMoney(-money);
		},
		score : 0,
		/**
		 * Adds score to player
		 * @param toAdd the amount
		 */
		addScore : function addScore(toAdd){
			this.score+=toAdd;
			//check the advance to the next level
			if(PewPew.game.levels[PewPew.game.level]<=this.score)
				PewPew.game.level++;
		}
	};
	/**
	 * Fill upgrades tab
	 */
	var html = "";
	for ( var upgrade in PewPew.player.upgrades) {
		if (PewPew.player.upgrades.hasOwnProperty(upgrade)) {
			html += PewPew.player.upgrades[upgrade].getHtml();
		}
	}
	document.getElementById("upgrade-tiles").innerHTML = html;
	// add the event listeners to the created buttons
	var upg;
	for (upgrade in PewPew.player.upgrades) {
		if (PewPew.player.upgrades.hasOwnProperty(upgrade)) {
			upg = PewPew.player.upgrades[upgrade];
			document.getElementById(upg.getElementId()).addEventListener(
					"click", upg.tryBuy);

		}
	}

	/**
	 * Enemy class
	 */
	function Enemy(hp, x, y, image, value) {
		var self = this;
		this.hp = hp;
		this.x = x;
		this.y = y;
		this.setX = function setX(x) {
			self.x = x;
			PewPew.canvas.redraw();
		};
		this.setY = function setY(y) {
			self.y = y;
			PewPew.canvas.redraw();
		};
		this.setXY = function setXY(x, y) {
			self.x = x;
			self.y = y;
			PewPew.canvas.redraw();
		};
		this.image = image;
		this.value = value;
		/**
		 * deals damage to the enemy
		 * @param damage
		 */
		this.receiveDamage = function receiveDamage(damage) {
			self.hp -= damage;
			if (self.hp <= 0) {
				self.onDestroy();
			}
		};
		/**
		 * called when an enemy is destroyed, adds score and money to player and removes the enemy from game
		 */
		this.onDestroy = function onDestroy() {
			PewPew.player.addMoney(self.value + PewPew.player.income());
			PewPew.player.addScore(self.value);
			var index = PewPew.game.enemies.indexOf(self);
			if (index > -1) {
				PewPew.game.enemies.splice(index, 1);
			}
			// redraw the scene
			PewPew.canvas.redraw();
		};
		/**
		 * Checks if the enemy is hit by touching at given coords
		 */
		this.checkHit = function checkHit(x, y){
			if(x>=self.x){
				if(x<=self.x+self.width){
					//x in this
					if(y>=self.y){
						if(y<=self.y+self.height){
							//y in this
							return true;
						}else{
							//y below this
							return y-(self.y+self.height)<=PewPew.player.upgrades.range.level;
						}
					}else{
						//y above this
						return self.y-y<=PewPew.player.upgrades.range.level;
					}
				}else{
					//x right of this
					if(y>=self.y){
						if(y<=self.y+self.height){
							//y in this
							return x-(self.x+self.width)<=PewPew.player.upgrades.range.level;
						}else{
							//y below this
							return Math.pow(x-(self.x+self.width), 2)+Math.pow(y-(self.y+self.height),2)<=Math.pow(PewPew.player.upgrades.range.level, 2);
						}
					}else{
						//y above this
						return Math.pow(x-(self.x+self.width), 2)+Math.pow(self.y-y,2)<=Math.pow(PewPew.player.upgrades.range.level, 2);
					}
				}
			}else{
				//x left of this
				if(y>=self.y){
					if(y<=self.y+self.height){
						//y in this
						return self.x-x<=PewPew.player.upgrades.range.level;
					}else{
						//y below this
						return Math.pow(self.x-x, 2)+Math.pow(y-(self.y+self.height),2)<=Math.pow(PewPew.player.upgrades.range.level, 2);
					}
				}else{
					//y above this
					return Math.pow(self.x-x, 2)+Math.pow(self.y-y,2)<=Math.pow(PewPew.player.upgrades.range.level, 2);
				}
			}
		};
		this.canvasImage = new Image();
		this.canvasImage.src = this.image;
		this.width=self.canvasImage.width;
		this.height=self.canvasImage.height;
		this.canvasImage.onload = function() {
			PewPew.canvas.context.drawImage(self.canvasImage, self.x, self.y);
			self.width = self.canvasImage.width;
			self.height = self.canvasImage.height;
		};

		PewPew.game.enemies[PewPew.game.enemies.length] = self;
	}

	//The enemy templates
	function Fighter(x, y) {
		Enemy.call(this, 1, x, y, "img/fighter.png", 1);
	}
	Fighter.prototype = Object.create(Enemy.prototype);

	function Mook(x, y) {
		Enemy.call(this, 2, x, y, "img/mook.png", 2);
	}
	Mook.prototype = Object.create(Enemy.prototype);

	function Bomber(x, y) {
		Enemy.call(this, 5, x, y, "img/bomber.png", 5);
	}
	Bomber.prototype = Object.create(Enemy.prototype);

	PewPew.game = {
		level : 1,
		levels : [0,50,200,500,2500,10000,50000,200000,1000000],
		enemies : [],
		/**
		 * handles the hitting the enemies
		 * @param evt the touch event into game area
		 */
		handleHit : function handleHit(evt) {
			evt.preventDefault();
			var touches = evt.changedTouches;
			var touchId, x, y;
			for (var i = 0; i < evt.changedTouches.length; i++) {
				touchId = evt.changedTouches[i].identifier;
				x = evt.changedTouches[i].clientX-PewPew.canvas.element.getBoundingClientRect().left;
				y = evt.changedTouches[i].clientY-PewPew.canvas.element.getBoundingClientRect().top;
				for ( var enemy in PewPew.game.enemies) {
					enemy = PewPew.game.enemies[enemy];
					// test if the enemy is hit
					if (enemy.checkHit(x,y)) {
						enemy.receiveDamage(PewPew.player.damage());
					}
				}
			}

		},
		/**
		 * Spawns an enemy into game and moves him into random place ingame
		 * @param enemy
		 */
		spawnEnemy : function spawnEnemy(enemy) {
			var x = Math.floor(Math.random() * (PewPew.canvas.element.width-enemy.width));
			var y = Math.floor(Math.random() * (PewPew.canvas.element.height-enemy.height));
			enemy.setXY(x, y);
		}

	};
	/**
	 * The game canvas holder where the enemies are spawned
	 */
	PewPew.canvas = {
		element : document.getElementById("canvas"),
		context : null,
		/**
		 * redraws all the enemies alive in game
		 */
		redraw : function redraw() {
			this.context.clearRect(0, 0, PewPew.canvas.element.width,
					PewPew.canvas.element.height);
			for ( var enemy in PewPew.game.enemies) {
				enemy = PewPew.game.enemies[enemy];
				PewPew.canvas.context.drawImage(enemy.canvasImage, enemy.x,
						enemy.y);
			}
		},
	};
	PewPew.canvas.context = PewPew.canvas.element.getContext("2d");
	PewPew.canvas.element.addEventListener("touchstart", PewPew.game.handleHit
			.bind(PewPew.game));

	//The enemy spawning loop
	window.setInterval(function() {
		switch(PewPew.game.level){
		case 1:
			if(Math.random()<=0.33){
				PewPew.game.spawnEnemy(new Fighter(0, 0));
			}
			break;
		case 2:
			if(Math.random()<=0.33){
				if(Math.random()<=0.33){
					PewPew.game.spawnEnemy(new Mook(0, 0));
				}else{
					PewPew.game.spawnEnemy(new Fighter(0, 0));
				}
			}
			break;
		case 3:
			if(Math.random()<=0.66){
				if(Math.random()<=0.66){
					PewPew.game.spawnEnemy(new Mook(0, 0));
				}else{
					PewPew.game.spawnEnemy(new Fighter(0, 0));
				}
			}
			break;

		case 4:
		default:
			if(Math.random()<=0.1){
				PewPew.game.spawnEnemy(new Bomber(0, 0));
				PewPew.game.spawnEnemy(new Fighter(0, 0));
			}else if(Math.random()<=0.66){
				PewPew.game.spawnEnemy(new Mook(0, 0));
			}else{
				PewPew.game.spawnEnemy(new Fighter(0, 0));
			}
			break;
		}
	}, 1000);
}();<|endoftext|>


<commit_before>$( document ).ready(function() {
    $(".logo").addClass("animated fadeInUp visible");
    setTimeout(function(){
        $("h1").addClass("animated fadeInUp visible");
    }, 1000);
    setTimeout(function(){
        $("h2").addClass("animated fadeInUp visible");
    }, 2000);
    setTimeout(function(){
        $(".scroll-down").addClass("animated fadeInUp visible");
    }, 2600);
});<commit_msg>remove extraneous js<commit_after>$( document ).ready(function() {
    // $(".logo").addClass("animated fadeInUp visible");
    setTimeout(function(){
        $("h1").addClass("animated fadeInUp visible");
    }, 1000);
    setTimeout(function(){
        $("h2").addClass("animated fadeInUp visible");
    }, 2000);
    setTimeout(function(){
        $(".scroll-down").addClass("animated fadeInUp visible");
    }, 2600);
});<|endoftext|>


<commit_before>/* Standard page footer JavaScript */

const MCDCONNECTED = [
    {
	'link': 'https://twitter.com/search?q=IAM%20Design%20Method',
        'class': 'fa fa-twitter'
    },

    {
	'link': 'https://www.facebook.com/MiamiCollegeOfDesign/',
	'class': 'fa fa-facebook'
    },

    {
	'link': 'https://github.com/MiamiCollegeDesign',
	'class': 'fa fa-github'
    },

    {
//	'link': 'https://www.google.com',
//	'class': 'fa fa-google-plus'
    },

    {
//	'link': 'https://youtube.com',
//	'class': 'fa fa-youtube-play'
    },

    {
//	'link': 'https://instagram.com',
//	'class': 'fa fa-instagram'
    },
];

const MCDABOUT = [
    {
        'link': './calendar.html',
        'title': 'Academic Calendar',
        'item': '7'
    },

    {
	'link': './program.html',
        'title': 'Degree Programs',
        'item': '2'
    },

    {
	'link': './courses.html',
        'title': 'Course Descriptions',
        'item': '3'
    },

    {
	'link': './admissions.html',
        'title': 'Admissions',
        'item': '4'
    },

    {
	'link': './financial-aid.html',
        'title': 'Financial Aid',
        'item': '5'
    },

    {
	'link': './docs/Catalog.pdf',
        'title': 'Catalog',
        'item': '1'
    },
];

const MCDINVOLVED = [
    {
	'link': './campus.html',
        'title': 'Campus',
        'item': '9'
    },

    {
	'link': './events.html',
        'title': 'Upcoming Events',
        'item': '6'
    },

    {
        'link': './miami2040.html',
        'title': 'Miami 2040',
        'item': '8'
    },

    {
	'link': './contact.html',
        'title': 'Contact Us',
        'item': '10'
    },
];

const MCDADMIN = [
    {
	'link': './about.html',
        'title': 'About',
        'item': '11'
    },

    {
        'link': './students.html',
        'title': 'Students',
        'item': '12'
    },

    {
        'link': './faculty.html',
        'title': 'Faculty',
        'item': '13'
    },

    {
        'link': './staff.html',
        'title': 'Staff',
        'item': '14'
    },
];

var footer = {
    pageFooter: function() {
        var footerElement = document.getElementById('footer');
        var content = '';
        content += '
';
	content += '
';
	content += '
';
	content += '
';
	content += '
';

        // MCD CONNECTED
        content += '
';
	content += '
';
	content += '

CONNECT
';
	content += '
';

        for (var i = 0; i < MCDCONNECTED.length; i++) {
            // class is the only required field
            if ('class' in MCDCONNECTED[i]) {
		if ('link' in MCDCONNECTED[i]) {
		    content += '';
		}

		content += '';
		if ('link' in MCDCONNECTED[i]) {
		    content += '';
		}
	    }
	}

        content += '
'
	content += '
';

        // MCD ABOUT
        content += '

PROGRAM
';
        content += '
';
	content += '
';

        for (var i = 0; i < MCDABOUT.length; i++) {
            // title is the only required field
            if ('title' in MCDABOUT[i]) {
                if ('item' in MCDABOUT[i]) {
                    var item = MCDABOUT[i]['item'];
		} else {
                    var item = '404';
                }

		content += '
 ';
		if ('link' in MCDABOUT[i]) {
		    content += '';
		}

                content += MCDABOUT[i]['title'];
		if ('link' in MCDABOUT[i]) {
		    content += '';
		}
                content += '
';
	    }
	}

        content += '
';
	content += '
';
	content += '
';

        // MCD INVOLVED
        content += '

ACTIVITIES
';
        content += '
';
	content += '
';

        for (var i = 0; i < MCDINVOLVED.length; i++) {
            // title is the only required field
            if ('title' in MCDINVOLVED[i]) {
                if ('item' in MCDINVOLVED[i]) {
                    var item = MCDINVOLVED[i]['item'];
		} else {
                    var item = '404';
                }

		content += '
 ';
		if ('link' in MCDINVOLVED[i]) {
		    content += '';
		}

                content += MCDINVOLVED[i]['title'];
		if ('link' in MCDINVOLVED[i]) {
		    content += '';
		}
                content += '
';
	    }
	}

        content += '
';
	content += '
';
	content += '
';

	// MCD ADMIN
        content += '

PEOPLE
';
        content += '
';
	content += '
';

        for (var i = 0; i < MCDADMIN.length; i++) {
            // title is the only required field
            if ('title' in MCDADMIN[i]) {
                if ('item' in MCDADMIN[i]) {
                    var item = MCDADMIN[i]['item'];
		} else {
                    var item = '404';
                }

		content += '
 ';
		if ('link' in MCDADMIN[i]) {
		    content += '';
		}

                content += MCDADMIN[i]['title'];
		if ('link' in MCDADMIN[i]) {
		    content += '';
		}
                content += '
';
	    }
	}

        content += '
';
	content += '
';
	content += '
';

        // Close footer divs
	content += '
';
	content += '
';
	content += '
';

        // Copyright
	content += '
';
        content += '
© 2016 Miami College of Design
';
        content += '
   +1 (800) 848-0398          hello@miamicollegeofdesign.com       Last modified 1 November 2016
';
	content += '
';

	content += '';

        footerElement.innerHTML = content;
    },

}
<commit_msg>add portfolio workshop link<commit_after>/* Standard page footer JavaScript */

const MCDCONNECTED = [
    {
	'link': 'https://twitter.com/search?q=IAM%20Design%20Method',
        'class': 'fa fa-twitter'
    },

    {
	'link': 'https://www.facebook.com/MiamiCollegeOfDesign/',
	'class': 'fa fa-facebook'
    },

    {
	'link': 'https://github.com/MiamiCollegeDesign',
	'class': 'fa fa-github'
    },

    {
//	'link': 'https://www.google.com',
//	'class': 'fa fa-google-plus'
    },

    {
//	'link': 'https://youtube.com',
//	'class': 'fa fa-youtube-play'
    },

    {
//	'link': 'https://instagram.com',
//	'class': 'fa fa-instagram'
    },
];

const MCDABOUT = [
    {
        'link': './calendar.html',
        'title': 'Academic Calendar',
        'item': '7'
    },

    {
	'link': './program.html',
        'title': 'Degree Programs',
        'item': '2'
    },

    {
	'link': './courses.html',
        'title': 'Course Descriptions',
        'item': '3'
    },

    {
	'link': './admissions.html',
        'title': 'Admissions',
        'item': '4'
    },

    {
	'link': './financial-aid.html',
        'title': 'Financial Aid',
        'item': '5'
    },

    {
	'link': './docs/Catalog.pdf',
        'title': 'Catalog',
        'item': '1'
    },

];

const MCDINVOLVED = [
    {
	'link': './campus.html',
        'title': 'Campus',
        'item': '9'
    },

    {
	'link': './events.html',
        'title': 'Upcoming Events',
        'item': '6'
    },

    {
        'link': './miami2040.html',
        'title': 'Miami 2040',
        'item': '8'
    },

    {
	'link': './workshop.html',
        'title': 'Portfolio Workshops',
        'item': '9'
    },

    {
	'link': './contact.html',
        'title': 'Contact Us',
        'item': '10'
    },
];

const MCDADMIN = [
    {
	'link': './about.html',
        'title': 'About',
        'item': '11'
    },

    {
        'link': './students.html',
        'title': 'Students',
        'item': '12'
    },

    {
        'link': './faculty.html',
        'title': 'Faculty',
        'item': '13'
    },

    {
        'link': './staff.html',
        'title': 'Staff',
        'item': '14'
    },
];

var footer = {
    pageFooter: function() {
        var footerElement = document.getElementById('footer');
        var content = '';
        content += '
';
	content += '
';
	content += '
';
	content += '
';
	content += '
';

        // MCD CONNECTED
        content += '
';
	content += '
';
	content += '

CONNECT
';
	content += '
';

        for (var i = 0; i < MCDCONNECTED.length; i++) {
            // class is the only required field
            if ('class' in MCDCONNECTED[i]) {
		if ('link' in MCDCONNECTED[i]) {
		    content += '';
		}

		content += '';
		if ('link' in MCDCONNECTED[i]) {
		    content += '';
		}
	    }
	}

        content += '
'
	content += '
';

        // MCD ABOUT
        content += '

PROGRAM
';
        content += '
';
	content += '
';

        for (var i = 0; i < MCDABOUT.length; i++) {
            // title is the only required field
            if ('title' in MCDABOUT[i]) {
                if ('item' in MCDABOUT[i]) {
                    var item = MCDABOUT[i]['item'];
		} else {
                    var item = '404';
                }

		content += '
 ';
		if ('link' in MCDABOUT[i]) {
		    content += '';
		}

                content += MCDABOUT[i]['title'];
		if ('link' in MCDABOUT[i]) {
		    content += '';
		}
                content += '
';
	    }
	}

        content += '
';
	content += '
';
	content += '
';

        // MCD INVOLVED
        content += '

ACTIVITIES
';
        content += '
';
	content += '
';

        for (var i = 0; i < MCDINVOLVED.length; i++) {
            // title is the only required field
            if ('title' in MCDINVOLVED[i]) {
                if ('item' in MCDINVOLVED[i]) {
                    var item = MCDINVOLVED[i]['item'];
		} else {
                    var item = '404';
                }

		content += '
 ';
		if ('link' in MCDINVOLVED[i]) {
		    content += '';
		}

                content += MCDINVOLVED[i]['title'];
		if ('link' in MCDINVOLVED[i]) {
		    content += '';
		}
                content += '
';
	    }
	}

        content += '
';
	content += '
';
	content += '
';

	// MCD ADMIN
        content += '

PEOPLE
';
        content += '
';
	content += '
';

        for (var i = 0; i < MCDADMIN.length; i++) {
            // title is the only required field
            if ('title' in MCDADMIN[i]) {
                if ('item' in MCDADMIN[i]) {
                    var item = MCDADMIN[i]['item'];
		} else {
                    var item = '404';
                }

		content += '
 ';
		if ('link' in MCDADMIN[i]) {
		    content += '';
		}

                content += MCDADMIN[i]['title'];
		if ('link' in MCDADMIN[i]) {
		    content += '';
		}
                content += '
';
	    }
	}

        content += '
';
	content += '
';
	content += '
';

        // Close footer divs
	content += '
';
	content += '
';
	content += '
';

        // Copyright
	content += '
';
        content += '
© 2016 Miami College of Design
';
        content += '
   +1 (800) 848-0398          hello@miamicollegeofdesign.com       Last modified 1 November 2016
';
	content += '
';

	content += '';

        footerElement.innerHTML = content;
    },

}
<|endoftext|>


<commit_before>var fifooter = "
 \

  \

 \
 \
 \
FusionInventory 9.1+1.0 - Copyleft \
© \
2010-2016 by FusionInventory Team \
 \
	 \

 \

 \

"

$(window).bind("load", function() { $("#footer").after(fifooter); })

<commit_msg>Fix footer.<commit_after>var fifooter = "
 \
 \
FusionInventory 9.1+1.0 - Copyleft \
© \
2010-2016 by FusionInventory Team \
";

$(window).bind("load", function() {
   $('#footer').css('height', 'auto');
   $("#footer td.right").append(fifooter);
});
<|endoftext|>


<commit_before>"use strict";

// ---------------------------------------------------------------------------

const bter = require ('./bter.js');

// ---------------------------------------------------------------------------

module.exports = class gateio extends bter {

    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'gateio',
            'name': 'Gate.io',
            'countries': 'CN',
            'rateLimit': 1000,
            'has': {
                'CORS': false,
                'createMarketOrder': false,
                'fetchTickers': true,
                'withdraw': true,
                'createDepositAddress': true,
                'fetchDepositAddress': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/31784029-0313c702-b509-11e7-9ccc-bc0da6a0e435.jpg',
                'api': {
                    'public': 'https://data.gate.io/api',
                    'private': 'https://data.gate.io/api',
                },
                'www': 'https://gate.io/',
                'doc': 'https://gate.io/api2',
                'fees': 'https://gate.io/fee',
            },
        });
    }

    async createDepositAddress (currency, params = {}) {
        let response = await this.privatePostNewAddress (this.extend ({
            'currency': currency,
        }, params));
        let address = undefined;
        if ('addr' in response) {
            address = this.safeString (response['addr'], 0);
        }
        return {
            'currency': currency,
            'address': address,
            'status': address !== undefined ? 'ok' : 'none',
            'info': response,
        };
    }

    async fetchDepositAddress (currency, params = {}) {
        let response = await this.privatePostDepositAddress (this.extend ({
            'currency': currency,
        }, params));
        let address = undefined;
        if ('addr' in response) {
            address = this.safeString (response['addr'], 0);
        }
        return {
            'currency': currency,
            'address': address,
            'status': address !== undefined ? 'ok' : 'none',
            'info': response,
        };
    }

    parseTrade (trade, market) {
        // exchange reports local time (UTC+8)
        let timestamp = this.parse8601 (trade['date']) - 8 * 60 * 60 * 1000;
        return {
            'id': trade['tradeID'],
            'info': trade,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': market['symbol'],
            'type': undefined,
            'side': trade['type'],
            'price': trade['rate'],
            'amount': this.safeFloat (trade, 'amount'),
        };
    }
}
<commit_msg>minor edits and deduplication for gateio fetchDepositAddress/createDepositAddress #1709<commit_after>"use strict";

// ---------------------------------------------------------------------------

const bter = require ('./bter.js');

// ---------------------------------------------------------------------------

module.exports = class gateio extends bter {

    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'gateio',
            'name': 'Gate.io',
            'countries': 'CN',
            'rateLimit': 1000,
            'has': {
                'CORS': false,
                'createMarketOrder': false,
                'fetchTickers': true,
                'withdraw': true,
                'createDepositAddress': true,
                'fetchDepositAddress': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/31784029-0313c702-b509-11e7-9ccc-bc0da6a0e435.jpg',
                'api': {
                    'public': 'https://data.gate.io/api',
                    'private': 'https://data.gate.io/api',
                },
                'www': 'https://gate.io/',
                'doc': 'https://gate.io/api2',
                'fees': 'https://gate.io/fee',
            },
        });
    }

    async queryDepositAddress (method, currency, params = {}) {
        method = 'privatePost' + method + 'Address';
        let response = await this[method] (this.extend ({
            'currency': currency,
        }, params));
        let address = undefined;
        if ('addr' in response)
            address = this.safeString (response['addr'], 0);
        return {
            'currency': currency,
            'address': address,
            'status': (typeof address !== 'undefined') ? 'ok' : 'none',
            'info': response,
        };
    }

    async createDepositAddress (currency, params = {}) {
        return await this.queryDepositAddress ('New', currency, params);
    }

    async fetchDepositAddress (currency, params = {}) {
        return await this.queryDepositAddress ('Deposit', currency, params);
    }

    parseTrade (trade, market) {
        // exchange reports local time (UTC+8)
        let timestamp = this.parse8601 (trade['date']) - 8 * 60 * 60 * 1000;
        return {
            'id': trade['tradeID'],
            'info': trade,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': market['symbol'],
            'type': undefined,
            'side': trade['type'],
            'price': trade['rate'],
            'amount': this.safeFloat (trade, 'amount'),
        };
    }
}
<|endoftext|>


<commit_before>/*
 * MBP - Mobile boilerplate helper functions
 */

(function(document){

window.MBP = window.MBP || {};

/*
  * Fix for iPhone viewport scale bug
  * http://www.blog.highub.com/mobile-2/a-fix-for-iphone-viewport-scale-bug/
*/

MBP.viewportmeta = document.querySelector && document.querySelector('meta[name="viewport"]');
MBP.ua = navigator.userAgent;

MBP.scaleFix = function () {
  if (MBP.viewportmeta && /iPhone|iPad|iPod/.test(MBP.ua) && !/Opera Mini/.test(MBP.ua)) {
    MBP.viewportmeta.content = "width=device-width, minimum-scale=1.0, maximum-scale=1.0";
    document.addEventListener("gesturestart", MBP.gestureStart, false);
  }
};
MBP.gestureStart = function () {
  MBP.viewportmeta.content = "width=device-width, minimum-scale=0.25, maximum-scale=1.6";
};

/*
  * Normalized hide address bar for iOS & Android
  * (c) Scott Jehl, scottjehl.com
  * MIT License
*/

// If we split this up into two functions we can reuse
// this function if we aren't doing full page reloads.

// If we cache this we don't need to re-calibrate everytime we call
// the hide url bar
MBP.BODY_SCROLL_TOP = false;

// So we don't redefine this function everytime we
// we call hideUrlBar
MBP.getScrollTop = function(){
  var win = window,
      doc = document;

  return win.pageYOffset || doc.compatMode === "CSS1Compat" && doc.documentElement.scrollTop || doc.body.scrollTop || 0;
};

// It should be up to the mobile
MBP.hideUrlBar = function(){
    var win = window;

    // if there is a hash, or MBP.BODY_SCROLL_TOP hasn't been set yet, wait till that happens
    if( !location.hash && MBP.BODY_SCROLL_TOP !== false){
        win.scrollTo( 0, MBP.BODY_SCROLL_TOP === 1 ? 0 : 1 );
    }
};

MBP.hideUrlBarOnLoad = function () {
  var win = window,
      doc = win.document;

  // If there's a hash, or addEventListener is undefined, stop here
  if( !location.hash && win.addEventListener ) {

    //scroll to 1
    window.scrollTo( 0, 1 );
    MBP.BODY_SCROLL_TOP = 1;

    //reset to 0 on bodyready, if needed
    bodycheck = setInterval(function() {
      if( doc.body ) {
        clearInterval( bodycheck );
        MBP.BODY_SCROLL_TOP = MBP.getScrollTop();
        MBP.hideUrlBar();
      }
    }, 15 );

    win.addEventListener( "load", function() {
      setTimeout(function() {
        //at load, if user hasn't scrolled more than 20 or so...
        if( MBP.getScrollTop() < 20 ) {
          //reset to hide addr bar at onload
          MBP.hideUrlBar();
        }
      }, 0);
    } );
  }
};

/*
   * Fast Buttons - read wiki below before using
   * https://github.com/h5bp/mobile-boilerplate/wiki/JavaScript-Helper
*/

MBP.fastButton = function (element, handler) {
  this.handler = handler;

	if (element.length && element.length > 1) {
    for (var singleElIdx in element) {
      if (element[singleElIdx].addEventListener) {
        this.addClickEvent(element[singleElIdx]);
      }
    }
  } else if (element.addEventListener) {
    this.addClickEvent(element);
  }
};

MBP.fastButton.prototype.handleEvent = function(event) {
	event = event || window.event;
  switch (event.type) {
    case 'touchstart': this.onTouchStart(event); break;
    case 'touchmove': this.onTouchMove(event); break;
    case 'touchend': this.onClick(event); break;
    case 'click': this.onClick(event); break;
  }
};

MBP.fastButton.prototype.onTouchStart = function(event) {
  var element = event.srcElement;
  event.stopPropagation();
  element.addEventListener('touchend', this, false);
  document.body.addEventListener('touchmove', this, false);
  this.startX = event.touches[0].clientX;
  this.startY = event.touches[0].clientY;
  element.style.backgroundColor = "rgba(0,0,0,.7)";
};

MBP.fastButton.prototype.onTouchMove = function(event) {
  if(Math.abs(event.touches[0].clientX - this.startX) > 10 ||
    Math.abs(event.touches[0].clientY - this.startY) > 10    ) {
    this.reset(element);
  }
};

MBP.fastButton.prototype.onClick = function(event) {
	event = event || window.event;
  var element = event.srcElement;
  if (event.stopPropagation) { event.stopPropagation(); }
  this.reset(event);
  this.handler.apply(event.currentTarget, [event]);
  if(event.type == 'touchend') {
    MBP.preventGhostClick(this.startX, this.startY);
  }
  element.style.backgroundColor = "";
};

MBP.fastButton.prototype.reset = function() {
	rmEvt(element, "touchend", this, false);
	rmEvt(document.body, "touchmove", this, false);
  element.style.backgroundColor = "";
};

MBP.fastButton.prototype.addClickEvent = function(element) {
  addEvt(element, "touchstart", this, false);
  addEvt(element, "click", this, false);
};

MBP.preventGhostClick = function (x, y) {
  MBP.coords.push(x, y);
  window.setTimeout(function (){
    MBP.coords.splice(0, 2);
  }, 2500);
};

MBP.ghostClickHandler = function (event) {
  if (!MBP.hadTouchEvent && 'ontouchstart' in window) {
    // This is a bit of fun for Android 2.3...
    // If you change window.location via fastButton, a click event will fire
    // on the new page, as if the events are continuing from the previous page.
    // We pick that event up here, but MBP.coords is empty, because it's a new page,
    // so we don't prevent it. Here's we're assuming that click events on touch devices
    // that occur without a preceding touchStart are to be ignored.
    event.stopPropagation();
    event.preventDefault();
    return;
  }
  for(var i = 0, len = MBP.coords.length; i < len; i += 2) {
    var x = MBP.coords[i];
    var y = MBP.coords[i + 1];
    if(Math.abs(event.clientX - x) < 25 && Math.abs(event.clientY - y) < 25) {
      event.stopPropagation();
      event.preventDefault();
    }
  }
};

if (document.addEventListener) {
  document.addEventListener('click', MBP.ghostClickHandler, true);
}

addEvt( document.documentElement, 'touchstart', function() {
  MBP.hadTouchEvent = true;
}, false);

MBP.coords = [];

// fn arg can be an object or a function, thanks to handleEvent
// read more about the explanation at: http://www.thecssninja.com/javascript/handleevent
function addEvt(el, evt, fn, bubble) {
  if("addEventListener" in el) {
    // BBOS6 doesn't support handleEvent, catch and polyfill
    try {
      el.addEventListener(evt, fn, bubble);
    } catch(e) {
      if(typeof fn == "object" && fn.handleEvent) {
        el.addEventListener(evt, function(e){
        // Bind fn as this and set first arg as event object
        fn.handleEvent.call(fn,e);
        }, bubble);
      } else {
        throw e;
      }
    }
  } else if("attachEvent" in el) {
    // check if the callback is an object and contains handleEvent
    if(typeof fn == "object" && fn.handleEvent) {
      el.attachEvent("on" + evt, function(){
        // Bind fn as this
        fn.handleEvent.call(fn);
      });
    } else {
      el.attachEvent("on" + evt, fn);
    }
  }
}

function rmEvt(el, evt, fn, bubble) {
  if("removeEventListener" in el) {
    // BBOS6 doesn't support handleEvent, catch and polyfill
    try {
      el.removeEventListener(evt, fn, bubble);
    } catch(e) {
      if(typeof fn == "object" && fn.handleEvent) {
        el.removeEventListener(evt, function(e){
          // Bind fn as this and set first arg as event object
          fn.handleEvent.call(fn,e);
        }, bubble);
      } else {
        throw e;
      }
    }
  } else if("detachEvent" in el) {
    // check if the callback is an object and contains handleEvent
    if(typeof fn == "object" && fn.handleEvent) {
      el.detachEvent("on" + evt, function(){
        // Bind fn as this
        fn.handleEvent.call(fn);
      });
    } else {
      el.detachEvent("on" + evt, fn);
    }
  }
}

/*
  * iOS Startup Image
  * https://github.com/h5bp/mobile-boilerplate/issues#issue/2
*/

MBP.splash = function () {
  var filename = navigator.platform === 'iPad' ? 'h/' : 'l/';
  document.write('<link rel="apple-touch-startup-image" href="/img/' + filename + 'splash.png" />' );
};

/*
  * Autogrow
  * http://googlecode.blogspot.com/2009/07/gmail-for-mobile-html5-series.html
*/

MBP.autogrow = function (element, lh) {
  function handler(e){
    var newHeight = this.scrollHeight,
        currentHeight = this.clientHeight;
    if (newHeight > currentHeight) {
      this.style.height = newHeight + 3 * textLineHeight + "px";
    }
  }

  var setLineHeight = (lh) ? lh : 12,
      textLineHeight = element.currentStyle ? element.currentStyle.lineHeight :
                       getComputedStyle(element, null).lineHeight;

  textLineHeight = (textLineHeight.indexOf("px") == -1) ? setLineHeight :
                   parseInt(textLineHeight, 10);

  element.style.overflow = "hidden";
  element.addEventListener ? element.addEventListener('keyup', handler, false) :
                             element.attachEvent('onkeyup', handler);
};

/*
  * Enable active
  * Enable CSS active pseudo styles in Mobile Safari
  * http://miniapps.co.uk/blog/post/enable-css-active-pseudo-styles-in-mobile-safari/
*/

MBP.enableActive = function () {
  document.addEventListener("touchstart", function() {}, false);
};

/*
  * Prevent iOS from zooming onfocus
  * https://github.com/h5bp/mobile-boilerplate/pull/108
*/

MBP.preventZoom = function () {
  var formFields = document.querySelectorAll('input, select, textarea'),
  	  contentString = 'width=device-width,initial-scale=1,maximum-scale=',
  	  i = 0;
  for(i = 0; i < formFields.length; i++) {
    formFields[i].onfocus = function() {
      MBP.viewportmeta.content = contentString + '1';
    };
    formFields[i].onblur = function() {
      MBP.viewportmeta.content = contentString + '10';
    };
  }
};

/*
  * Original jQuery snippet for Prevent iOS from zooming onfocus
  *  http://nerd.vasilis.nl/prevent-ios-from-zooming-onfocus/
*/
// $('input, select, textarea').bind('focus blur', function(event) {
//	MBP.viewportmeta.content = 'width=device-width,initial-scale=1,maximum-scale=' + (event.type == 'blur' ? 10 : 1);
// });

})(document);
<commit_msg>fixed IE6 issues from previous commit in issue #86 #89, fixed #89<commit_after>/*
 * MBP - Mobile boilerplate helper functions
 */

(function(document){

window.MBP = window.MBP || {};

/*
  * Fix for iPhone viewport scale bug
  * http://www.blog.highub.com/mobile-2/a-fix-for-iphone-viewport-scale-bug/
*/

MBP.viewportmeta = document.querySelector && document.querySelector('meta[name="viewport"]');
MBP.ua = navigator.userAgent;

MBP.scaleFix = function () {
  if (MBP.viewportmeta && /iPhone|iPad|iPod/.test(MBP.ua) && !/Opera Mini/.test(MBP.ua)) {
    MBP.viewportmeta.content = "width=device-width, minimum-scale=1.0, maximum-scale=1.0";
    document.addEventListener("gesturestart", MBP.gestureStart, false);
  }
};
MBP.gestureStart = function () {
  MBP.viewportmeta.content = "width=device-width, minimum-scale=0.25, maximum-scale=1.6";
};

/*
  * Normalized hide address bar for iOS & Android
  * (c) Scott Jehl, scottjehl.com
  * MIT License
*/

// If we split this up into two functions we can reuse
// this function if we aren't doing full page reloads.

// If we cache this we don't need to re-calibrate everytime we call
// the hide url bar
MBP.BODY_SCROLL_TOP = false;

// So we don't redefine this function everytime we
// we call hideUrlBar
MBP.getScrollTop = function(){
  var win = window,
      doc = document;

  return win.pageYOffset || doc.compatMode === "CSS1Compat" && doc.documentElement.scrollTop || doc.body.scrollTop || 0;
};

// It should be up to the mobile
MBP.hideUrlBar = function(){
    var win = window;

    // if there is a hash, or MBP.BODY_SCROLL_TOP hasn't been set yet, wait till that happens
    if( !location.hash && MBP.BODY_SCROLL_TOP !== false){
        win.scrollTo( 0, MBP.BODY_SCROLL_TOP === 1 ? 0 : 1 );
    }
};

MBP.hideUrlBarOnLoad = function () {
  var win = window,
      doc = win.document;

  // If there's a hash, or addEventListener is undefined, stop here
  if( !location.hash && win.addEventListener ) {

    //scroll to 1
    window.scrollTo( 0, 1 );
    MBP.BODY_SCROLL_TOP = 1;

    //reset to 0 on bodyready, if needed
    bodycheck = setInterval(function() {
      if( doc.body ) {
        clearInterval( bodycheck );
        MBP.BODY_SCROLL_TOP = MBP.getScrollTop();
        MBP.hideUrlBar();
      }
    }, 15 );

    win.addEventListener( "load", function() {
      setTimeout(function() {
        //at load, if user hasn't scrolled more than 20 or so...
        if( MBP.getScrollTop() < 20 ) {
          //reset to hide addr bar at onload
          MBP.hideUrlBar();
        }
      }, 0);
    } );
  }
};

/*
   * Fast Buttons - read wiki below before using
   * https://github.com/h5bp/mobile-boilerplate/wiki/JavaScript-Helper
*/

MBP.fastButton = function (element, handler) {
  this.handler = handler;

	if (element.length && element.length > 1) {
    for (var singleElIdx in element) {
      this.addClickEvent(element[singleElIdx]);
    }
  } else {
    this.addClickEvent(element);
  }
};

MBP.fastButton.prototype.handleEvent = function(event) {
	event = event || window.event;
  switch (event.type) {
    case 'touchstart': this.onTouchStart(event); break;
    case 'touchmove': this.onTouchMove(event); break;
    case 'touchend': this.onClick(event); break;
    case 'click': this.onClick(event); break;
  }
};

MBP.fastButton.prototype.onTouchStart = function(event) {
  var element = event.srcElement;
  event.stopPropagation();
  element.addEventListener('touchend', this, false);
  document.body.addEventListener('touchmove', this, false);
  this.startX = event.touches[0].clientX;
  this.startY = event.touches[0].clientY;
  element.style.backgroundColor = "rgba(0,0,0,.7)";
};

MBP.fastButton.prototype.onTouchMove = function(event) {
  if(Math.abs(event.touches[0].clientX - this.startX) > 10 ||
    Math.abs(event.touches[0].clientY - this.startY) > 10    ) {
    this.reset(element);
  }
};

MBP.fastButton.prototype.onClick = function(event) {
	event = event || window.event;
  var element = event.srcElement;
  if (event.stopPropagation) { event.stopPropagation(); }
  this.reset(event);
  this.handler.apply(event.currentTarget, [event]);
  if(event.type == 'touchend') {
    MBP.preventGhostClick(this.startX, this.startY);
  }
  element.style.backgroundColor = "";
};

MBP.fastButton.prototype.reset = function(event) {
  var element = event.srcElement;
	rmEvt(element, "touchend", this, false);
	rmEvt(document.body, "touchmove", this, false);
  element.style.backgroundColor = "";
};

MBP.fastButton.prototype.addClickEvent = function(element) {
  addEvt(element, "touchstart", this, false);
  addEvt(element, "click", this, false);
};

MBP.preventGhostClick = function (x, y) {
  MBP.coords.push(x, y);
  window.setTimeout(function (){
    MBP.coords.splice(0, 2);
  }, 2500);
};

MBP.ghostClickHandler = function (event) {
  if (!MBP.hadTouchEvent && 'ontouchstart' in window) {
    // This is a bit of fun for Android 2.3...
    // If you change window.location via fastButton, a click event will fire
    // on the new page, as if the events are continuing from the previous page.
    // We pick that event up here, but MBP.coords is empty, because it's a new page,
    // so we don't prevent it. Here's we're assuming that click events on touch devices
    // that occur without a preceding touchStart are to be ignored.
    event.stopPropagation();
    event.preventDefault();
    return;
  }
  for(var i = 0, len = MBP.coords.length; i < len; i += 2) {
    var x = MBP.coords[i];
    var y = MBP.coords[i + 1];
    if(Math.abs(event.clientX - x) < 25 && Math.abs(event.clientY - y) < 25) {
      event.stopPropagation();
      event.preventDefault();
    }
  }
};

if (document.addEventListener) {
  document.addEventListener('click', MBP.ghostClickHandler, true);
}

addEvt( document.documentElement, 'touchstart', function() {
  MBP.hadTouchEvent = true;
}, false);

MBP.coords = [];

// fn arg can be an object or a function, thanks to handleEvent
// read more about the explanation at: http://www.thecssninja.com/javascript/handleevent
function addEvt(el, evt, fn, bubble) {
  if("addEventListener" in el) {
    // BBOS6 doesn't support handleEvent, catch and polyfill
    try {
      el.addEventListener(evt, fn, bubble);
    } catch(e) {
      if(typeof fn == "object" && fn.handleEvent) {
        el.addEventListener(evt, function(e){
        // Bind fn as this and set first arg as event object
        fn.handleEvent.call(fn,e);
        }, bubble);
      } else {
        throw e;
      }
    }
  } else if("attachEvent" in el) {
    // check if the callback is an object and contains handleEvent
    if(typeof fn == "object" && fn.handleEvent) {
      el.attachEvent("on" + evt, function(){
        // Bind fn as this
        fn.handleEvent.call(fn);
      });
    } else {
      el.attachEvent("on" + evt, fn);
    }
  }
}

function rmEvt(el, evt, fn, bubble) {
  if("removeEventListener" in el) {
    // BBOS6 doesn't support handleEvent, catch and polyfill
    try {
      el.removeEventListener(evt, fn, bubble);
    } catch(e) {
      if(typeof fn == "object" && fn.handleEvent) {
        el.removeEventListener(evt, function(e){
          // Bind fn as this and set first arg as event object
          fn.handleEvent.call(fn,e);
        }, bubble);
      } else {
        throw e;
      }
    }
  } else if("detachEvent" in el) {
    // check if the callback is an object and contains handleEvent
    if(typeof fn == "object" && fn.handleEvent) {
      el.detachEvent("on" + evt, function(){
        // Bind fn as this
        fn.handleEvent.call(fn);
      });
    } else {
      el.detachEvent("on" + evt, fn);
    }
  }
}

/*
  * iOS Startup Image
  * https://github.com/h5bp/mobile-boilerplate/issues#issue/2
*/

MBP.splash = function () {
  var filename = navigator.platform === 'iPad' ? 'h/' : 'l/';
  document.write('<link rel="apple-touch-startup-image" href="/img/' + filename + 'splash.png" />' );
};

/*
  * Autogrow
  * http://googlecode.blogspot.com/2009/07/gmail-for-mobile-html5-series.html
*/

MBP.autogrow = function (element, lh) {
  function handler(e){
    var newHeight = this.scrollHeight,
        currentHeight = this.clientHeight;
    if (newHeight > currentHeight) {
      this.style.height = newHeight + 3 * textLineHeight + "px";
    }
  }

  var setLineHeight = (lh) ? lh : 12,
      textLineHeight = element.currentStyle ? element.currentStyle.lineHeight :
                       getComputedStyle(element, null).lineHeight;

  textLineHeight = (textLineHeight.indexOf("px") == -1) ? setLineHeight :
                   parseInt(textLineHeight, 10);

  element.style.overflow = "hidden";
  element.addEventListener ? element.addEventListener('keyup', handler, false) :
                             element.attachEvent('onkeyup', handler);
};

/*
  * Enable active
  * Enable CSS active pseudo styles in Mobile Safari
  * http://miniapps.co.uk/blog/post/enable-css-active-pseudo-styles-in-mobile-safari/
*/

MBP.enableActive = function () {
  document.addEventListener("touchstart", function() {}, false);
};

/*
  * Prevent iOS from zooming onfocus
  * https://github.com/h5bp/mobile-boilerplate/pull/108
*/

MBP.preventZoom = function () {
  var formFields = document.querySelectorAll('input, select, textarea'),
  	  contentString = 'width=device-width,initial-scale=1,maximum-scale=',
  	  i = 0;
  for(i = 0; i < formFields.length; i++) {
    formFields[i].onfocus = function() {
      MBP.viewportmeta.content = contentString + '1';
    };
    formFields[i].onblur = function() {
      MBP.viewportmeta.content = contentString + '10';
    };
  }
};

/*
  * Original jQuery snippet for Prevent iOS from zooming onfocus
  *  http://nerd.vasilis.nl/prevent-ios-from-zooming-onfocus/
*/
// $('input, select, textarea').bind('focus blur', function(event) {
//	MBP.viewportmeta.content = 'width=device-width,initial-scale=1,maximum-scale=' + (event.type == 'blur' ? 10 : 1);
// });

})(document);
<|endoftext|>


<commit_before>/*
 * helper.js
 *
 * Helper file, you probably will not need this one.
 * Must be loaded as the very last js file, be careful.
 *
 */
$(document).ready(function(){
	$('#navigation a, #markup a').css({
		"cursor": 'pointer',
		"text-decoration": 'none'
	});
	if (settings.showInfo) {
        $('footer').append("

");
        $("footer p").eq(0).append("

");
		showInfo();
		setInterval("showInfo()",60000);
	}
    var do_replace_audio = function() {
        $('audio').mediaelementplayer({
                plugins:['flash','silverlight'],
                pluginPath:'/js/mediaelement/'
        });
        $('video').mediaelementplayer();
    }

    var do_preview_webm = function() {
        $('video').attr('preload', 'true')
    }

    var do_add_shorten = function() {
        $("div.post.reply div.body").shorten({
            moreText: 'Весь текст',
            lessText: 'Скрыть',
            showChars: (settings.hideLongTextNum),
        });
    }

    do_replace_audio(document);
    if (settings.previewWebm)
        do_preview_webm();
    if (settings.hideLongText)
        do_add_shorten(document);

	$(document).bind('new_post', function(e, post) {
        do_replace_audio(post);
        if (settings.hideLongText)
            do_add_shorten(post);
	});

    if (device_type == "mobile") {
        $("#navigation .fa").addClass("fa-2x");
        $("#navigation .fa").click(function() {
            $("#navigation .fa").addClass("fa-2x");
        });
    }
});

function showInfo() {
    $.ajax({
        type: 'GET',
        url: "/testcount.json",
        dataType: 'json',
        success: function(data){
            ajaxInfo = data;
            $('#showInfo').text("Скорость борды: " + JSON.parse(ajaxInfo.speed) + " п/час | Онлайн: " + JSON.parse(ajaxInfo.online));
        }
    });
    // well thank you Github
    $.ajax({
        type: 'GET',
        url: "https://api.github.com/repos/twiforce/fukuro/stats/contributors",
        dataType: 'json',
        success: function(data){
            githubContribInfo = data;
        }
    });
    $.ajax({
        type: 'GET',
        url: "https://api.github.com/repos/twiforce/fukuro/commits",
        dataType: 'json',
        success: function(data){
            githubInfo = data;
            $('#githubInfo').html("Последний коммит #" + githubContribInfo[0]["total"] + " \"" + githubInfo[0]["commit"]["message"]
                + "\" отправлен " + moment(githubInfo[0]["commit"]["author"]["date"]).fromNow() + ".")
        }
    });
}<commit_msg>helper.js: .webm preview now works with new posts<commit_after>/*
 * helper.js
 *
 * Helper file, you probably will not need this one.
 * Must be loaded as the very last js file, be careful.
 *
 */
$(document).ready(function(){
	$('#navigation a, #markup a').css({
		"cursor": 'pointer',
		"text-decoration": 'none'
	});
	if (settings.showInfo) {
        $('footer').append("

");
        $("footer p").eq(0).append("

");
		showInfo();
		setInterval("showInfo()",60000);
	}
    var do_replace_audio = function() {
        $('audio').mediaelementplayer({
                plugins:['flash','silverlight'],
                pluginPath:'/js/mediaelement/'
        });
        $('video').mediaelementplayer();
    }

    var do_preview_webm = function() {
        $('video').attr('preload', 'metadata')
    }

    var do_add_shorten = function() {
        $("div.post.reply div.body").shorten({
            moreText: 'Весь текст',
            lessText: 'Скрыть',
            showChars: (settings.hideLongTextNum),
        });
    }

    do_replace_audio(document);
    if (settings.previewWebm)
        do_preview_webm(document);
    if (settings.hideLongText)
        do_add_shorten(document);

	$(document).bind('new_post', function(e, post) {
        do_replace_audio(post);
        if (settings.hideLongText)
            do_add_shorten(post);
        if (settings.previewWebm)
            do_preview_webm(post);
	});

    if (device_type == "mobile") {
        $("#navigation .fa").addClass("fa-2x");
        $("#navigation .fa").click(function() {
            $("#navigation .fa").addClass("fa-2x");
        });
    }
});

function showInfo() {
    $.ajax({
        type: 'GET',
        url: "/testcount.json",
        dataType: 'json',
        success: function(data){
            ajaxInfo = data;
            $('#showInfo').text("Скорость борды: " + JSON.parse(ajaxInfo.speed) + " п/час | Онлайн: " + JSON.parse(ajaxInfo.online));
        }
    });
    // well thank you Github
    $.ajax({
        type: 'GET',
        url: "https://api.github.com/repos/twiforce/fukuro/stats/contributors",
        dataType: 'json',
        success: function(data){
            githubContribInfo = data;
        }
    });
    $.ajax({
        type: 'GET',
        url: "https://api.github.com/repos/twiforce/fukuro/commits",
        dataType: 'json',
        success: function(data){
            githubInfo = data;
            $('#githubInfo').html("Последний коммит #" + githubContribInfo[0]["total"] + " \"" + githubInfo[0]["commit"]["message"]
                + "\" отправлен " + moment(githubInfo[0]["commit"]["author"]["date"]).fromNow() + ".")
        }
    });
}<|endoftext|>


<commit_before>/*
Process Flow:
1. Pass the Google Search Query to Wolfram|Alpha and get the result as XML
2. Parse that XML to get a HTML-Object of the Result
3. Inject this object beautifully into the Google Site
*/
var searchQuery;

/* Get Search Query out of URL and think about we should really go for Wolfram instead of Google */
(function(undefined){
chrome.runtime.sendMessage("getURL", function(response) {
	searchQuery = response;
	// Determine whether Google provided their own "Quick Results"
	if (!document.getElementsByClassName("vk_c")[0]) {
		console.log("Google has NO 'Quick Results' --> Query WolframAlpha!");
		requestWolframResult(response);
	} else {
		console.log("Google has their 'Quick Results' --> no need for WolframAlpha");
	}
	injectWolframButton(response);

});

/*
Inject a Button "Search on Wolfram Alpha!" when not displaying them automatically
*/
function injectWolframButton(searchQuery) {
	// Result Container
	var wolframButton = document.createElement("button");
	wolframButton.id = "wolframButton";
	wolframButton.innerHTML = "Wolfram|Alpha";
	wolframButton.setAttribute("type", "button");
    wolframButton.setAttribute("value", "wolfram");
    wolframButton.setAttribute("name", "wolframButton");
	wolframUrl = "http://www.wolframalpha.com/input/?i="+searchQuery;
    wolframButton.setAttribute("onclick", "window.open(wolframUrl,'_blank');");
	document.getElementById("rcnt").parentNode.insertBefore(wolframButton, document.getElementById("rcnt"));
}

/*
Get and Parse the Wolfram|Alpha result XML
*/
function requestWolframResult(searchQuery) {
	console.log("Method called");
	var xmlhttp = new XMLHttpRequest();

	xmlhttp.onreadystatechange = function(){
	  if (xmlhttp.readyState == 4 && xmlhttp.status === 200){
			var xmlDoc = xmlhttp.responseXML;
			/* Plaintext Result */
			var pods = xmlDoc.getElementsByTagName("pod");
			var plaintexts = xmlDoc.getElementsByTagName("plaintext");
			var imgs = xmlDoc.getElementsByTagName("img");

			console.log(searchQuery);
			console.log(plaintexts[1].textContent);
			console.log(pods[1].getAttribute("title"));

			/* Inject the result */
			// As plaintext
			// displayResultAsPlaintext(plaintexts[1].textContent, pods[1].getAttribute("title"), searchQuery);
			// As image
			displayResultAsImage(imgs[1].getAttribute("src"), imgs[1].getAttribute("width"), imgs[1].getAttribute("height"), imgs[1].getAttribute("title"), imgs[1].getAttribute("alt"), pods[1].getAttribute("title"), searchQuery);
		}
	  }
	xmlhttp.open("GET","http://api.wolframalpha.com/v2/query?input="+searchQuery+"&appid=8X6XE5-Q5887TY7TE",true);
	// xmlhttp.open("GET","http://www.maxi-muth.de/wa.xml",true);
	xmlhttp.send();
}

/* Inject result as image */
function displayResultAsImage(imgSrc, width, height, title, alt, description, searchQuery) {
	// Result Container
	var resultDiv = document.createElement("div");
	resultDiv.id = "resultDiv";
	// Description
	var descriptionDiv = document.createElement("div");
	descriptionDiv.id = "description";
	// Image
	var resultImg = document.createElement("img");
	resultImg.id = "resultImg";
	// More link
	var moreLink = document.createElement("a");
	moreLink.id = "moreLink";

	// Set image
	resultImg.src = imgSrc;
	resultImg.title = title;
	resultImg.alt = alt;
	// resultImg.width = width;
	// resultImg.height = height;

	// Setdescription
	descriptionDiv.innerHTML = description;

	// More link
	moreLink.appendChild(document.createTextNode("More"));
	moreLink.title = "All details on the awesome site of Wolfram|Alpha";
	moreLink.href = "http://www.wolframalpha.com/input/?i="+searchQuery;
	moreLink.target = "_blank";

	// Insert result div into DOM
	document.getElementById("rcnt").parentNode.insertBefore(resultDiv, document.getElementById("rcnt"));

	// Add Description and more link into resultDiv
	document.getElementById("resultDiv").appendChild(resultImg);
	document.getElementById("resultDiv").appendChild(descriptionDiv);
	document.getElementById("resultDiv").appendChild(moreLink);

}

/* Inject result as plaintext */
function displayResultAsPlaintext(result, description, searchQuery) {
	// Result
	var resultDiv = document.createElement("div");
	resultDiv.id = "resultDiv";
	// Description
	var descriptionDiv = document.createElement("div");
	descriptionDiv.id = "description";
	// More link
	var moreLink = document.createElement("a");
	moreLink.id = "moreLink";

	// Set content of result div and description
	resultDiv.innerHTML = result;
	descriptionDiv.innerHTML = description;
	// More link
	moreLink.appendChild(document.createTextNode("More"));
	moreLink.title = "All details on the awesome site of Wolfram|Alpha";
	moreLink.href = "http://www.wolframalpha.com/input/?i="+searchQuery;
	moreLink.target = "_blank";

	// Insert result div into DOM
	document.getElementById("rcnt").parentNode.insertBefore(resultDiv, document.getElementById("rcnt"));
	// Add Description and more link into resultDiv
	document.getElementById("resultDiv").appendChild(descriptionDiv);
	document.getElementById("resultDiv").appendChild(moreLink);
}
})();
<commit_msg>Using relative protocol.<commit_after>/*
Process Flow:
1. Pass the Google Search Query to Wolfram|Alpha and get the result as XML
2. Parse that XML to get a HTML-Object of the Result
3. Inject this object beautifully into the Google Site
*/
var searchQuery;

/* Get Search Query out of URL and think about we should really go for Wolfram instead of Google */
(function(undefined){
chrome.runtime.sendMessage("getURL", function(response) {
	searchQuery = response;
	// Determine whether Google provided their own "Quick Results"
	if (!document.getElementsByClassName("vk_c")[0]) {
		console.log("Google has NO 'Quick Results' --> Query WolframAlpha!");
		requestWolframResult(response);
	} else {
		console.log("Google has their 'Quick Results' --> no need for WolframAlpha");
	}
	injectWolframButton(response);

});

/*
Inject a Button "Search on Wolfram Alpha!" when not displaying them automatically
*/
function injectWolframButton(searchQuery) {
	// Result Container
	var wolframButton = document.createElement("button");
	wolframButton.id = "wolframButton";
	wolframButton.innerHTML = "Wolfram|Alpha";
	wolframButton.setAttribute("type", "button");
    wolframButton.setAttribute("value", "wolfram");
    wolframButton.setAttribute("name", "wolframButton");
	wolframUrl = "//www.wolframalpha.com/input/?i=\"+searchQuery";
    wolframButton.setAttribute("onclick", "window.open(wolframUrl,'_blank');");
	document.getElementById("rcnt").parentNode.insertBefore(wolframButton, document.getElementById("rcnt"));
}

/*
Get and Parse the Wolfram|Alpha result XML
*/
function requestWolframResult(searchQuery) {
	console.log("Method called");
	var xmlhttp = new XMLHttpRequest();

	xmlhttp.onreadystatechange = function(){
	  if (xmlhttp.readyState == 4 && xmlhttp.status === 200){
			var xmlDoc = xmlhttp.responseXML;
			/* Plaintext Result */
			var pods = xmlDoc.getElementsByTagName("pod");
			var plaintexts = xmlDoc.getElementsByTagName("plaintext");
			var imgs = xmlDoc.getElementsByTagName("img");

			console.log(searchQuery);
			console.log(plaintexts[1].textContent);
			console.log(pods[1].getAttribute("title"));

			/* Inject the result */
			// As plaintext
			// displayResultAsPlaintext(plaintexts[1].textContent, pods[1].getAttribute("title"), searchQuery);
			// As image
			displayResultAsImage(imgs[1].getAttribute("src"), imgs[1].getAttribute("width"), imgs[1].getAttribute("height"), imgs[1].getAttribute("title"), imgs[1].getAttribute("alt"), pods[1].getAttribute("title"), searchQuery);
		}
	  }
	xmlhttp.open("GET","http://api.wolframalpha.com/v2/query?input="+searchQuery+"&appid=8X6XE5-Q5887TY7TE",true);
	// xmlhttp.open("GET","http://www.maxi-muth.de/wa.xml",true);
	xmlhttp.send();
}

/* Inject result as image */
function displayResultAsImage(imgSrc, width, height, title, alt, description, searchQuery) {
	// Result Container
	var resultDiv = document.createElement("div");
	resultDiv.id = "resultDiv";
	// Description
	var descriptionDiv = document.createElement("div");
	descriptionDiv.id = "description";
	// Image
	var resultImg = document.createElement("img");
	resultImg.id = "resultImg";
	// More link
	var moreLink = document.createElement("a");
	moreLink.id = "moreLink";

	// Set image
	resultImg.src = imgSrc;
	resultImg.title = title;
	resultImg.alt = alt;
	// resultImg.width = width;
	// resultImg.height = height;

	// Setdescription
	descriptionDiv.innerHTML = description;

	// More link
	moreLink.appendChild(document.createTextNode("More"));
	moreLink.title = "All details on the awesome site of Wolfram|Alpha";
	moreLink.href = "http://www.wolframalpha.com/input/?i="+searchQuery;
	moreLink.target = "_blank";

	// Insert result div into DOM
	document.getElementById("rcnt").parentNode.insertBefore(resultDiv, document.getElementById("rcnt"));

	// Add Description and more link into resultDiv
	document.getElementById("resultDiv").appendChild(resultImg);
	document.getElementById("resultDiv").appendChild(descriptionDiv);
	document.getElementById("resultDiv").appendChild(moreLink);

}

/* Inject result as plaintext */
function displayResultAsPlaintext(result, description, searchQuery) {
	// Result
	var resultDiv = document.createElement("div");
	resultDiv.id = "resultDiv";
	// Description
	var descriptionDiv = document.createElement("div");
	descriptionDiv.id = "description";
	// More link
	var moreLink = document.createElement("a");
	moreLink.id = "moreLink";

	// Set content of result div and description
	resultDiv.innerHTML = result;
	descriptionDiv.innerHTML = description;
	// More link
	moreLink.appendChild(document.createTextNode("More"));
	moreLink.title = "All details on the awesome site of Wolfram|Alpha";
	moreLink.href = "http://www.wolframalpha.com/input/?i="+searchQuery;
	moreLink.target = "_blank";

	// Insert result div into DOM
	document.getElementById("rcnt").parentNode.insertBefore(resultDiv, document.getElementById("rcnt"));
	// Add Description and more link into resultDiv
	document.getElementById("resultDiv").appendChild(descriptionDiv);
	document.getElementById("resultDiv").appendChild(moreLink);
}
})();
<|endoftext|>


<commit_before>/*global IOC:true*/
/*jshint evil:true*/
IOC.DI = function (ioc) {

  var registry = {};
  var factories = {};

  var _resolveArgs = function (args) {
    var failure = false;
    var resolved = [];
    args.forEach(function (arg) {
      if (typeof arg.value !== 'undefined') {
        resolved.push(arg.value);
      } else if (typeof arg.ref !== 'undefined') {
        var ref = _getInstance(arg.ref);
        if (ref) {
          resolved.push(ref);
        } else {
          failure = true;
        }
      } else if (typeof arg.func !== 'undefined') {
        resolved.push(arg.func);
      } else if (typeof arg.exec !== 'undefined') {
        resolved.push(arg.exec(ioc));
      }
    });
    return failure ? null : resolved;
  };

  var _execFunction = function (instance, func, args) {
    var resolvedFunc = (typeof func === 'function' ? func : ioc.object.get(_getInstance(instance), func));
    if (resolvedFunc) {
      var resolvedArgs = _resolveArgs(args || []);
      if (resolvedArgs) {
        resolvedFunc.apply(resolvedFunc, resolvedArgs);
      } else {
        throw 'Unable to resolve arguments for "' + func + '" of instance "' + instance + '"';
      }
    } else {
      throw 'Unknown function "' + func + '" for instance "' + instance + '"';
    }
  };

  var _addInstance = function (name, instance, factory, args) {
    registry[name] = instance;
    if (factory) {
      factories[name] = args || [];
    }
  };

  var _getInstance = function (name) {
    if (factories.hasOwnProperty(name)) {
      var args = _resolveArgs(factories[name] || []);
      if (args) {
        return registry[name].apply(registry[name], args);
      } else {
        throw 'Unable to resolve arguments for "' + name + '"';
      }
    } else {
      return registry[name];
    }
  };

  var _wire = function (instances) {
    if (!instances) {
      return;
    }

    var instanceKeys = ioc.object.keys(instances);
    var unresolved = {};

    instanceKeys.forEach(function (instance) {
      var func = ioc.object.get(window, instances[instance].namespace);
      if (func) {
        var args = _resolveArgs(instances[instance].args || []);
        if (args) {
          window.console.log(instance, 'wired');
          var actualInstance = instances[instance].factory ? func : func.apply(func, args);
          _addInstance(instance, actualInstance, instances[instance].factory, instances[instance].args || []);
          if (instances[instance].extension) {
            ioc = ioc.object.extend(ioc, actualInstance);
          }
        } else {
          unresolved[instance] = instances[instance];
        }
      } else {
        throw 'Unknown function "' + instances[instance].namespace + '"';
      }
    });

    var unresolvedKeys = ioc.object.keys(unresolved);
    if (unresolvedKeys.length !== ioc.object.keys(instances).length && unresolvedKeys.length > 0) {
      _wire(unresolved);
    } else {
      if (unresolvedKeys.length !== 0) {
        throw 'Make sure you don\'t have circular dependencies, Unable to resolve the following instances: ' + unresolvedKeys.join(", ");
      }
    }
  };

  var _init = function (instances) {
    ioc.object.keys(instances).forEach(function (instance) {
      if (instances[instance].init) {
        _execFunction(instance, instances[instance].init.func, instances[instance].init.args);
      }
    });
  };

  var _start = function (starts) {
    if (!starts) {
      return;
    }
    if (document.readyState !== 'complete') {
      window.setTimeout(function () {
        _start(starts);
      }, 100);
    } else {
      starts.forEach(function (start) {
          _execFunction(start.instance, start.func, start.args);
      });
    }
  };

  var _loadContext = function () {
    if (ioc.config.context) {
      window.console.log('wire instances');
      _wire(ioc.config.context.instances);
      window.console.log('init instances');
      _init(ioc.config.context.instances);
      window.console.log('start instances');
      _start(ioc.config.context.start);
    }
  };

  var _loadAsyncDependencies = function (dependencies) {
    var latch = ioc.async.latch(dependencies.async ? dependencies.async.length : 0, _loadContext, 'dependencies');
    dependencies.async.forEach(function (dep) {
      ioc.loader.loadScript(dep, latch.countDown);
    });
  };

  var _loadSyncDependencies = function () {
    if (!ioc.config.context || !ioc.config.context.dependencies) {
      return _loadContext();
    }

    var dependencies;
    if (!ioc.config.context.dependencies[ioc.config.mode]) {
      dependencies = {sync: [], async: []};
    } else {
      dependencies = ioc.config.context.dependencies[ioc.config.mode];
    }

    var seqLatch = ioc.async.seqLatch(dependencies.sync || [], function (url) {
      ioc.loader.loadScript(url, seqLatch.next);
    }, function () {
      _loadAsyncDependencies(dependencies);
    });
    seqLatch.next();
  };

  var _mergeImports = function (imports) {
    var imp = imports.pop();
    var unloadedImports = [];

    while (imp) {
      if (!ioc.object.get(window, imp.namespace)) {
        unloadedImports.push(imp);
      } else {
        ioc.config = ioc.object.extend(ioc.config, ioc.object.get(window, imp.namespace)());
      }
      imp = imports.pop();
    }

    if (unloadedImports.length !== 0) {
      var latch = ioc.async.latch(unloadedImports.length, function () {
        _mergeImports(unloadedImports);
      }, 'imports');
      unloadedImports.forEach(function (subImp) {
        ioc.loader.loadScript(subImp.url, latch.countDown);
      });
    } else {
      _loadSyncDependencies();
    }
  };

  var _loadConfig = function (config) {
    _addInstance('ioc', ioc);
    ioc.config = config;
    ioc.config.mode = ioc.url.query().env || 'default';
    window.console.log('IOC: Starting in mode', ioc.config.mode);
    if (config.exposeIoc) {
      window.ioc = ioc;
    }

    if (ioc.config.imports) {
      _mergeImports(JSON.parse(JSON.stringify(ioc.config.imports)));
    } else {
      _loadSyncDependencies();
    }
  };

  var _processAnnotations = function (text) {
    var regex = /@ioc-instance\s+["']([^"']+)["']\s*(.*);\s*(@ioc-init\s+["']([^"']+)["']\s*(.*);)*\s*(@ioc-start\s+["']([^"']+)["']\s*(.*);)*\s*\*\/\s*([\w.]+)/g;
    var match;
    while ((match = regex.exec(text))) {
      _processAnnotation(match);
    }
  };

  var _processArgAnnotation = function (match) {
    var args = [];
    var split = match.split(',');
    split.forEach(function (arg) {
      var argPair = arg.split(":");
      var argObj = {};
      argObj[argPair[0].trim()] = argPair[0].trim() === 'ref' ? argPair[1].trim() : eval(argPair[1].trim());
      args.push(argObj);
    });
    return args;
  };

  var _processAnnotation = function (match) {
    var instanceName = match[1];
    var namespace = match[9];

    if (!instanceName) {
      return;
    }
    if (!ioc.config.context) {
      ioc.config.context = {instances: {}};
    }

    //instance
    ioc.config.context.instances[instanceName] = {namespace: namespace};
    if (match[2]) {
      ioc.config.context.instances[instanceName].args = _processArgAnnotation(match[2]);
    }

    // init
    if (match[4]) {
      ioc.config.context.instances[instanceName].init = {func: match[4]};
      if (match[5]) {
        ioc.config.context.instances[instanceName].init.args = _processArgAnnotation(match[5]);
      }
    }

    // start
    if (match[7]) {
      var start = {instance: instanceName, func: match[7]};
      if (match[8]) {
        start.args = _processArgAnnotation(match[8]);
      }
      if (!ioc.config.context.start) {
        ioc.config.context.start = [];
      }
      ioc.config.context.start.push(start);
    }
  };

  return {
    di: {
      loadConfig: _loadConfig,
      getInstance: _getInstance,
      addInstance: _addInstance,
      processAnnotations: _processAnnotations
    }
  };
};<commit_msg>trying out separation of the extensions so they are available earlier<commit_after>/*global IOC:true*/
/*jshint evil:true*/
IOC.DI = function (ioc) {

  var registry = {};
  var factories = {};

  var _resolveArgs = function (args) {
    var failure = false;
    var resolved = [];
    args.forEach(function (arg) {
      if (typeof arg.value !== 'undefined') {
        resolved.push(arg.value);
      } else if (typeof arg.ref !== 'undefined') {
        var ref = _getInstance(arg.ref);
        if (ref) {
          resolved.push(ref);
        } else {
          failure = true;
        }
      } else if (typeof arg.func !== 'undefined') {
        resolved.push(arg.func);
      } else if (typeof arg.exec !== 'undefined') {
        resolved.push(arg.exec(ioc));
      }
    });
    return failure ? null : resolved;
  };

  var _execFunction = function (instance, func, args) {
    var resolvedFunc = (typeof func === 'function' ? func : ioc.object.get(_getInstance(instance), func));
    if (resolvedFunc) {
      var resolvedArgs = _resolveArgs(args || []);
      if (resolvedArgs) {
        resolvedFunc.apply(resolvedFunc, resolvedArgs);
      } else {
        throw 'Unable to resolve arguments for "' + func + '" of instance "' + instance + '"';
      }
    } else {
      throw 'Unknown function "' + func + '" for instance "' + instance + '"';
    }
  };

  var _addInstance = function (name, instance, factory, args) {
    registry[name] = instance;
    if (factory) {
      factories[name] = args || [];
    }
  };

  var _getInstance = function (name) {
    if (factories.hasOwnProperty(name)) {
      var args = _resolveArgs(factories[name] || []);
      if (args) {
        return registry[name].apply(registry[name], args);
      } else {
        throw 'Unable to resolve arguments for "' + name + '"';
      }
    } else {
      return registry[name];
    }
  };

  var _wire = function (instances) {
    if (!instances) {
      return;
    }

    var instanceKeys = ioc.object.keys(instances);
    var unresolved = {};

    instanceKeys.forEach(function (instance) {
      var func = ioc.object.get(window, instances[instance].namespace);
      if (func) {
        var args = _resolveArgs(instances[instance].args || []);
        if (args) {
          window.console.log(instance, 'wired');
          var actualInstance = instances[instance].factory ? func : func.apply(func, args);
          _addInstance(instance, actualInstance, instances[instance].factory, instances[instance].args || []);
          if (instances[instance].extension) {
            ioc = ioc.object.extend(ioc, actualInstance);
          }
        } else {
          unresolved[instance] = instances[instance];
        }
      } else {
        throw 'Unknown function "' + instances[instance].namespace + '"';
      }
    });

    var unresolvedKeys = ioc.object.keys(unresolved);
    if (unresolvedKeys.length !== ioc.object.keys(instances).length && unresolvedKeys.length > 0) {
      _wire(unresolved);
    } else {
      if (unresolvedKeys.length !== 0) {
        throw 'Make sure you don\'t have circular dependencies, Unable to resolve the following instances: ' + unresolvedKeys.join(", ");
      }
    }
  };

  var _init = function (instances) {
    ioc.object.keys(instances).forEach(function (instance) {
      if (instances[instance].init) {
        _execFunction(instance, instances[instance].init.func, instances[instance].init.args);
      }
    });
  };

  var _start = function (starts) {
    if (!starts) {
      return;
    }
    if (document.readyState !== 'complete') {
      window.setTimeout(function () {
        _start(starts);
      }, 100);
    } else {
      starts.forEach(function (start) {
          _execFunction(start.instance, start.func, start.args);
      });
    }
  };

  var _loadContext = function () {
    if (ioc.config.context) {
      window.console.log('wire extensions');
      _wire(ioc.config.context.extensions);
      window.console.log('init extensions');
      _init(ioc.config.context.extensions);
      window.console.log('wire instances');
      _wire(ioc.config.context.instances);
      window.console.log('init instances');
      _init(ioc.config.context.instances);
      window.console.log('start instances');
      _start(ioc.config.context.start);
    }
  };

  var _loadAsyncDependencies = function (dependencies) {
    var latch = ioc.async.latch(dependencies.async ? dependencies.async.length : 0, _loadContext, 'dependencies');
    dependencies.async.forEach(function (dep) {
      ioc.loader.loadScript(dep, latch.countDown);
    });
  };

  var _loadSyncDependencies = function () {
    if (!ioc.config.context || !ioc.config.context.dependencies) {
      return _loadContext();
    }

    var dependencies;
    if (!ioc.config.context.dependencies[ioc.config.mode]) {
      dependencies = {sync: [], async: []};
    } else {
      dependencies = ioc.config.context.dependencies[ioc.config.mode];
    }

    var seqLatch = ioc.async.seqLatch(dependencies.sync || [], function (url) {
      ioc.loader.loadScript(url, seqLatch.next);
    }, function () {
      _loadAsyncDependencies(dependencies);
    });
    seqLatch.next();
  };

  var _mergeImports = function (imports) {
    var imp = imports.pop();
    var unloadedImports = [];

    while (imp) {
      if (!ioc.object.get(window, imp.namespace)) {
        unloadedImports.push(imp);
      } else {
        ioc.config = ioc.object.extend(ioc.config, ioc.object.get(window, imp.namespace)());
      }
      imp = imports.pop();
    }

    if (unloadedImports.length !== 0) {
      var latch = ioc.async.latch(unloadedImports.length, function () {
        _mergeImports(unloadedImports);
      }, 'imports');
      unloadedImports.forEach(function (subImp) {
        ioc.loader.loadScript(subImp.url, latch.countDown);
      });
    } else {
      _loadSyncDependencies();
    }
  };

  var _loadConfig = function (config) {
    _addInstance('ioc', ioc);
    ioc.config = config;
    ioc.config.mode = ioc.url.query().env || 'default';
    window.console.log('IOC: Starting in mode', ioc.config.mode);
    if (config.exposeIoc) {
      window.ioc = ioc;
    }

    if (ioc.config.imports) {
      _mergeImports(JSON.parse(JSON.stringify(ioc.config.imports)));
    } else {
      _loadSyncDependencies();
    }
  };

  var _processAnnotations = function (text) {
    var regex = /@ioc-instance\s+["']([^"']+)["']\s*(.*);\s*(@ioc-init\s+["']([^"']+)["']\s*(.*);)*\s*(@ioc-start\s+["']([^"']+)["']\s*(.*);)*\s*\*\/\s*([\w.]+)/g;
    var match;
    while ((match = regex.exec(text))) {
      _processAnnotation(match);
    }
  };

  var _processArgAnnotation = function (match) {
    var args = [];
    var split = match.split(',');
    split.forEach(function (arg) {
      var argPair = arg.split(":");
      var argObj = {};
      argObj[argPair[0].trim()] = argPair[0].trim() === 'ref' ? argPair[1].trim() : eval(argPair[1].trim());
      args.push(argObj);
    });
    return args;
  };

  var _processAnnotation = function (match) {
    var instanceName = match[1];
    var namespace = match[9];

    if (!instanceName) {
      return;
    }
    if (!ioc.config.context) {
      ioc.config.context = {instances: {}};
    }

    //instance
    ioc.config.context.instances[instanceName] = {namespace: namespace};
    if (match[2]) {
      ioc.config.context.instances[instanceName].args = _processArgAnnotation(match[2]);
    }

    // init
    if (match[4]) {
      ioc.config.context.instances[instanceName].init = {func: match[4]};
      if (match[5]) {
        ioc.config.context.instances[instanceName].init.args = _processArgAnnotation(match[5]);
      }
    }

    // start
    if (match[7]) {
      var start = {instance: instanceName, func: match[7]};
      if (match[8]) {
        start.args = _processArgAnnotation(match[8]);
      }
      if (!ioc.config.context.start) {
        ioc.config.context.start = [];
      }
      ioc.config.context.start.push(start);
    }
  };

  return {
    di: {
      loadConfig: _loadConfig,
      getInstance: _getInstance,
      addInstance: _addInstance,
      processAnnotations: _processAnnotations
    }
  };
};<|endoftext|>


<commit_before>/**
 * Created by Obscurity on 2017/1/21.
 */

(function ($) {

    'use strict';

    var platforms = {
        qzone: {
            name: "qzone",
            default: true,
            icon: "https://ohtikzqed.bkt.clouddn.com/qzone.png",
            text: "QQ空间"
        },
        qq: {
            name: "qq",
            default: true,
            icon: "https://ohtikzqed.bkt.clouddn.com/qq.png",
            text: "QQ好友"
        },
        wechat: {
            name: "wechat",
            default: true,
            icon: "https://ohtikzqed.bkt.clouddn.com/wechat.png",
            text: "微信"
        },
        sinaweibo: {
            name: "sinaweibo",
            default: true,
            icon: "https://ohtikzqed.bkt.clouddn.com/sinaweibo.png",
            text: "新浪微博"
        },
        douban: {
            name: "douban",
            default: true,
            icon: "https://ohtikzqed.bkt.clouddn.com/douban.png",
            text: "豆瓣"
        },
        renren: {
            name: "renren",
            default: false,
            icon: "https://ohtikzqed.bkt.clouddn.com/renren.png",
            text: "人人网"
        },
        kaixin: {
            name: "kaixin",
            default: false,
            icon: "https://ohtikzqed.bkt.clouddn.com/kaixin.png",
            text: "开心网"
        },
        pengyou: {
            name: "pengyou",
            default: false,
            icon: "https://ohtikzqed.bkt.clouddn.com/pengyou.png",
            text: "朋友网"
        },
        tieba: {
            name: "tieba",
            default: false,
            icon: "https://ohtikzqed.bkt.clouddn.com/tieba.png",
            text: "百度贴吧"
        }
    };

    var defaults = {
        size: "small",
        platforms: []
    };

    var sizes = ["small", "medium", "large"];

    var hShare = function (options) {

        var _render = function (name, icon, customize, html) {
            if (customize) {
                return html;
            }
            else {
                switch(name) {
                    case "qzone":
                        return _renderQzone(icon);
                    case "qq":
                        return __renderQQ(icon);
                    case "wechat":
                        return _renderWechat(icon);
                    case "sinaweibo":
                        return _renderSinaWeibo(icon);
                    case "renren":
                        return _renderRenren(icon);
                    case "douban":
                        return _renderDouban(icon);
                    case "kaixin":
                        return _renderKaixin(icon);
                    case "pengyou":
                        return _renderPengyou(icon);
                    case "tieba":
                        return _renderTieba(icon);
                    default:
                        throw Error("invalid name");
                        break;
                }
            }
        };

        var __renderQQ = function (icon) {
            return ""
        };

        var _renderWechat = function (icon) {
            return "<\/a>";
        };

        var _renderQzone = function (icon) {
            return "<\/a>";
        };

        var _renderDouban = function (icon) {
            return "";
        };

        var _renderRenren = function (icon) {
            return "";
        };

        var _renderSinaWeibo = function (icon) {
            return "";
        };

        var _renderKaixin = function (icon) {
            return "";
        };

        var _renderPengyou = function (icon) {
            return "<\/a>";
        };

        var _renderTieba = function (icon) {
            return "";
        };

        var url = encodeURIComponent(location.href);
        var title = encodeURIComponent(document.title);

        var opts = options ? $.extend(true, {}, options) : $.extend(true, {}, defaults);
        var size = sizes.includes(opts.size) ? opts.size : "medium";

        opts.platforms = [];
        if (options && (options.platforms instanceof Array)) {
            options.platforms.forEach(function (platform) {
                opts.platforms.push($.extend({}, (platform.name && platforms[platform.name]) ? platforms[platform.name] : {}, platform));
            });
        }
        else {
            for(var key in platforms) {
                if (platforms[key].default) {
                    opts.platforms.push(platforms[key]);
                }
            }
        }

        return this.each(function () {
            var $this = $(this);

            var _platforms = opts.platforms;

            _platforms.forEach(function (plt) {
                var name = plt.name || "";
                var icon = plt.icon || "";
                var isCustomized = !!plt.customize;
                var customize = plt.customize || "";
                $this.append($(_render(name, icon, isCustomized, customize)));
            });

        });
    };

    $.fn.extend({
        hshare: hShare
    });

})(jQuery);<commit_msg>增加了一个demo<commit_after>/**
 * Created by Obscurity on 2017/1/21.
 */

(function ($) {

    'use strict';

    var platforms = {
        qzone: {
            name: "qzone",
            default: true,
            icon: "https://ohtikzqed.bkt.clouddn.com/qzone.png",
            text: "QQ空间"
        },
        qq: {
            name: "qq",
            default: true,
            icon: "https://ohtikzqed.bkt.clouddn.com/qq.png",
            text: "QQ好友"
        },
        wechat: {
            name: "wechat",
            default: true,
            icon: "https://ohtikzqed.bkt.clouddn.com/wechat.png",
            text: "微信"
        },
        sinaweibo: {
            name: "sinaweibo",
            default: true,
            icon: "https://ohtikzqed.bkt.clouddn.com/sinaweibo.png",
            text: "新浪微博"
        },
        douban: {
            name: "douban",
            default: true,
            icon: "https://ohtikzqed.bkt.clouddn.com/douban.png",
            text: "豆瓣"
        },
        renren: {
            name: "renren",
            default: false,
            icon: "https://ohtikzqed.bkt.clouddn.com/renren.png",
            text: "人人网"
        },
        kaixin: {
            name: "kaixin",
            default: false,
            icon: "https://ohtikzqed.bkt.clouddn.com/kaixin.png",
            text: "开心网"
        },
        pengyou: {
            name: "pengyou",
            default: false,
            icon: "https://ohtikzqed.bkt.clouddn.com/pengyou.png",
            text: "朋友网"
        },
        tieba: {
            name: "tieba",
            default: false,
            icon: "https://ohtikzqed.bkt.clouddn.com/tieba.png",
            text: "百度贴吧"
        }
    };

    var defaults = {
        size: "small",
        platforms: []
    };

    var sizes = ["small", "medium", "large"];

    var hShare = function (options) {

        var _render = function (name, icon, customize, html) {
            if (customize) {
                return html;
            }
            else {
                switch(name) {
                    case "qzone":
                        return _renderQzone(icon);
                    case "qq":
                        return __renderQQ(icon);
                    case "wechat":
                        return _renderWechat(icon);
                    case "sinaweibo":
                        return _renderSinaWeibo(icon);
                    case "renren":
                        return _renderRenren(icon);
                    case "douban":
                        return _renderDouban(icon);
                    case "kaixin":
                        return _renderKaixin(icon);
                    case "pengyou":
                        return _renderPengyou(icon);
                    case "tieba":
                        return _renderTieba(icon);
                    default:
                        throw Error("invalid name");
                        break;
                }
            }
        };

        var __renderQQ = function (icon) {
            return ""
        };

        var _renderWechat = function (icon) {
            return "<\/a>";
        };

        var _renderQzone = function (icon) {
            return "<\/a>";
        };

        var _renderDouban = function (icon) {
            return "";
        };

        var _renderRenren = function (icon) {
            return "";
        };

        var _renderSinaWeibo = function (icon) {
            return "";
        };

        var _renderKaixin = function (icon) {
            return "";
        };

        var _renderPengyou = function (icon) {
            return "<\/a>";
        };

        var _renderTieba = function (icon) {
            return "";
        };

        var url = encodeURIComponent(location.href);
        var title = encodeURIComponent(document.title);

        var opts = options ? $.extend(true, {}, options) : $.extend(true, {}, defaults);
        var size = sizes.includes(opts.size) ? opts.size : "medium";

        opts.platforms = [];
        if (options && (options.platforms instanceof Array)) {
            options.platforms.forEach(function (platform) {
                opts.platforms.push($.extend({}, (platform.name && platforms[platform.name]) ? platforms[platform.name] : {}, platform));
            });
        }
        else {
            for(var key in platforms) {
                if (platforms[key].default) {
                    opts.platforms.push(platforms[key]);
                }
            }
        }

        return this.each(function () {
            var $this = $(this);

            var _platforms = opts.platforms;

            _platforms.forEach(function (plt) {
                var name = plt.name || "";
                var icon = plt.icon || "";
                var isCustomized = !!plt.customize;
                var customize = plt.customize || "";
                $this.append($(_render(name, icon, isCustomized, customize)));
            });

        });
    };

    $.fn.extend({
        hshare: hShare
    });

})(jQuery);<|endoftext|>


<commit_before>#!/usr/bin/env node

const path = require('path');
const shell = require('shelljs');
const argv = require('yargs').argv;
const clc = require('cli-color');

function packageJsonLocations(dirname) {
  return shell.find(dirname)
    .filter(fname => !(fname.indexOf('node_modules') > -1 || fname[0] === '.') && path.basename(fname) === 'package.json')
    .map(fname => path.dirname(fname));
}

function yarn(directoryName) {
  let command = 'yarn';

  if (argv.cmd)
    command += ' ' + argv.cmd;
  let command = 'yarn';

  if (argv.opt)
    command += ' ' + argv.opt;

  let result = shell.exec(command);
  shell.cd(directoryName);

  console.log(clc.blueBright('Current yarn path: ' + directoryName + '/package.json...'));

  return {
    directoryName: directoryName,
    exitCode: result.code
  };
}

function filterRoot(directoryName) {
  console.log('Root filtering');

  return path.normalize(directoryName) === path.normalize(process.cwd());
}

if (require.main === module) {
  let exitCode = packageJsonLocations(process.cwd())
    .filter(argv.skipRoot ? filterRoot : filtered => filtered)
    .map(yarn)
    .reduce((code, result) =>result.exitCode > code ? result.exitCode : code, 0);

  console.log(clc.green.bold('End of yarns'));
  process.exit(exitCode);
}

module.exports = {
  yarn: yarn
};
<commit_msg>Minor<commit_after>#!/usr/bin/env node

const path = require('path');
const shell = require('shelljs');
const argv = require('yargs').argv;
const clc = require('cli-color');

function packageJsonLocations(dirname) {
  return shell.find(dirname)
    .filter(fname => !(fname.indexOf('node_modules') > -1 || fname[0] === '.') && path.basename(fname) === 'package.json')
    .map(fname => path.dirname(fname));
}

function yarn(directoryName) {
  let command = 'yarn';

  if (argv.cmd)
    command += ' ' + argv.cmd;

  if (argv.opt)
    command += ' ' + argv.opt;

  let result = shell.exec(command);
  shell.cd(directoryName);

  console.log(clc.blueBright('Current yarn path: ' + directoryName + '/package.json...'));

  return {
    directoryName: directoryName,
    exitCode: result.code
  };
}

function filterRoot(directoryName) {
  console.log('Root filtering');

  return path.normalize(directoryName) === path.normalize(process.cwd());
}

if (require.main === module) {
  let exitCode = packageJsonLocations(process.cwd())
    .filter(argv.skipRoot ? filterRoot : filtered => filtered)
    .map(yarn)
    .reduce((code, result) =>result.exitCode > code ? result.exitCode : code, 0);

  console.log(clc.green.bold('End of yarns'));
  process.exit(exitCode);
}

module.exports = {
  yarn: yarn
};
<|endoftext|>