<commit_before>// Simple Set Clipboard System
// Author: Joseph Huckaby

var ZeroClipboard = {

	version: "1.0.7",
	clients: {}, // registered upload clients on page, indexed by id
	moviePath: 'ZeroClipboard.swf', // URL to movie
	nextId: 1, // ID of next movie

	$: function(thingy) {
		// simple DOM lookup utility function
		if (typeof(thingy) == 'string') thingy = document.getElementById(thingy);
		if (!thingy.addClass) {
			// extend element with a few useful methods
			thingy.hide = function() { this.style.display = 'none'; };
			thingy.show = function() { this.style.display = ''; };
			thingy.addClass = function(name) { this.removeClass(name); this.className += ' ' + name; };
			thingy.removeClass = function(name) {
				var classes = this.className.split(/\s+/);
				var idx = -1;
				for (var k = 0; k < classes.length; k++) {
					if (classes[k] == name) { idx = k; k = classes.length; }
				}
				if (idx > -1) {
					classes.splice( idx, 1 );
					this.className = classes.join(' ');
				}
				return this;
			};
			thingy.hasClass = function(name) {
				return !!this.className.match( new RegExp("\\s*" + name + "\\s*") );
			};
		}
		return thingy;
	},

	setMoviePath: function(path) {
		// set path to ZeroClipboard.swf
		this.moviePath = path;
	},

	dispatch: function(id, eventName, args) {
		// receive event from flash movie, send to client
		var client = this.clients[id];
		if (client) {
			client.receiveEvent(eventName, args);
		}
	},

	register: function(id, client) {
		// register new client to receive events
		this.clients[id] = client;
	},

	getDOMObjectPosition: function(obj, stopObj) {
		// get absolute coordinates for dom element
		var info = {
			left: 0,
			top: 0,
			width: obj.width ? obj.width : obj.offsetWidth,
			height: obj.height ? obj.height : obj.offsetHeight
		};

		while (obj && (obj != stopObj)) {
			info.left += obj.offsetLeft;
			info.top += obj.offsetTop;
			obj = obj.offsetParent;
		}

		return info;
	},

	Client: function(elem) {
		// constructor for new simple upload client
		this.handlers = {};

		// unique ID
		this.id = ZeroClipboard.nextId++;
		this.movieId = 'ZeroClipboardMovie_' + this.id;

		// register client with singleton to receive flash events
		ZeroClipboard.register(this.id, this);

		// create movie
		if (elem) this.glue(elem);
	}
};

ZeroClipboard.Client.prototype = {

	id: 0, // unique ID for us
	ready: false, // whether movie is ready to receive events or not
	movie: null, // reference to movie object
	clipText: '', // text to copy to clipboard
	handCursorEnabled: true, // whether to show hand cursor, or default pointer cursor
	cssEffects: true, // enable CSS mouse effects on dom container
	handlers: null, // user event handlers

	glue: function(elem, appendElem, stylesToAdd) {
		// glue to DOM element
		// elem can be ID or actual DOM element object
		this.domElement = ZeroClipboard.$(elem);

		// float just above object, or zIndex 99 if dom element isn't set
		var zIndex = 99;
		if (this.domElement.style.zIndex) {
			zIndex = parseInt(this.domElement.style.zIndex, 10) + 1;
		}

		if (typeof(appendElem) == 'string') {
			appendElem = ZeroClipboard.$(appendElem);
		}
		else if (typeof(appendElem) == 'undefined') {
			appendElem = document.getElementsByTagName('body')[0];
		}

		// find X/Y position of domElement
		var box = ZeroClipboard.getDOMObjectPosition(this.domElement, appendElem);

		// create floating DIV above element
		this.div = document.createElement('div');
		var style = this.div.style;
		style.position = 'absolute';
		style.left = '' + box.left + 'px';
		style.top = '' + box.top + 'px';
		style.width = '' + box.width + 'px';
		style.height = '' + box.height + 'px';
		style.zIndex = zIndex;

		if (typeof(stylesToAdd) == 'object') {
			for (addedStyle in stylesToAdd) {
				style[addedStyle] = stylesToAdd[addedStyle];
			}
		}

		// style.backgroundColor = '#f00'; // debug

		appendElem.appendChild(this.div);

		this.div.innerHTML = this.getHTML( box.width, box.height );
	},

	getHTML: function(width, height) {
		// return HTML for movie
		var html = '';
		var flashvars = 'id=' + this.id +
			'&width=' + width +
			'&height=' + height;

		if (navigator.userAgent.match(/MSIE/)) {
			// IE gets an OBJECT tag
			var protocol = location.href.match(/^https/i) ? 'https://' : 'http://';
			html += '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="'+protocol+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="'+width+'" height="'+height+'" id="'+this.movieId+'" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+ZeroClipboard.moviePath+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+flashvars+'"/><param name="wmode" value="transparent"/></object>';
		}
		else {
			// all other browsers get an EMBED tag
			html += '<embed id="'+this.movieId+'" src="'+ZeroClipboard.moviePath+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+width+'" height="'+height+'" name="'+this.movieId+'" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+flashvars+'" wmode="transparent" />';
		}
		return html;
	},

	hide: function() {
		// temporarily hide floater offscreen
		if (this.div) {
			this.div.style.left = '-2000px';
		}
	},

	show: function() {
		// show ourselves after a call to hide()
		this.reposition();
	},

	destroy: function() {
		// destroy control and floater
		if (this.domElement && this.div) {
			this.hide();
			this.div.innerHTML = '';

			var body = document.getElementsByTagName('body')[0];
			try { body.removeChild( this.div ); } catch(e) {;}

			this.domElement = null;
			this.div = null;
		}
	},

	reposition: function(elem) {
		// reposition our floating div, optionally to new container
		// warning: container CANNOT change size, only position
		if (elem) {
			this.domElement = ZeroClipboard.$(elem);
			if (!this.domElement) this.hide();
		}

		if (this.domElement && this.div) {
			var box = ZeroClipboard.getDOMObjectPosition(this.domElement);
			var style = this.div.style;
			style.left = '' + box.left + 'px';
			style.top = '' + box.top + 'px';
		}
	},

	setText: function(newText) {
		// set text to be copied to clipboard
		this.clipText = newText;
		if (this.ready) this.movie.setText(newText);
	},

	addEventListener: function(eventName, func) {
		// add user event listener for event
		// event types: load, queueStart, fileStart, fileComplete, queueComplete, progress, error, cancel
		eventName = eventName.toString().toLowerCase().replace(/^on/, '');
		if (!this.handlers[eventName]) this.handlers[eventName] = [];
		this.handlers[eventName].push(func);
	},

	setHandCursor: function(enabled) {
		// enable hand cursor (true), or default arrow cursor (false)
		this.handCursorEnabled = enabled;
		if (this.ready) this.movie.setHandCursor(enabled);
	},

	setCSSEffects: function(enabled) {
		// enable or disable CSS effects on DOM container
		this.cssEffects = !!enabled;
	},

	receiveEvent: function(eventName, args) {
		// receive event from flash
		eventName = eventName.toString().toLowerCase().replace(/^on/, '');

		// special behavior for certain events
		switch (eventName) {
			case 'load':
				// movie claims it is ready, but in IE this isn't always the case...
				// bug fix: Cannot extend EMBED DOM elements in Firefox, must use traditional function
				this.movie = document.getElementById(this.movieId);
				if (!this.movie) {
					var self = this;
					setTimeout( function() { self.receiveEvent('load', null); }, 1 );
					return;
				}

				// firefox on pc needs a "kick" in order to set these in certain cases
				if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) {
					var self = this;
					setTimeout( function() { self.receiveEvent('load', null); }, 100 );
					this.ready = true;
					return;
				}

				this.ready = true;
				this.movie.setText( this.clipText );
				this.movie.setHandCursor( this.handCursorEnabled );
				break;

			case 'mouseover':
				if (this.domElement && this.cssEffects) {
					this.domElement.addClass('hover');
					if (this.recoverActive) this.domElement.addClass('active');
				}
				break;

			case 'mouseout':
				if (this.domElement && this.cssEffects) {
					this.recoverActive = false;
					if (this.domElement.hasClass('active')) {
						this.domElement.removeClass('active');
						this.recoverActive = true;
					}
					this.domElement.removeClass('hover');
				}
				break;

			case 'mousedown':
				if (this.domElement && this.cssEffects) {
					this.domElement.addClass('active');
				}
				break;

			case 'mouseup':
				if (this.domElement && this.cssEffects) {
					this.domElement.removeClass('active');
					this.recoverActive = false;
				}
				break;
		} // switch eventName

		if (this.handlers[eventName]) {
			for (var idx = 0, len = this.handlers[eventName].length; idx < len; idx++) {
				var func = this.handlers[eventName][idx];

				if (typeof(func) == 'function') {
					// actual function reference
					func(this, args);
				}
				else if ((typeof(func) == 'object') && (func.length == 2)) {
					// PHP style object + method, i.e. [myObject, 'myMethod']
					func[0][ func[1] ](this, args);
				}
				else if (typeof(func) == 'string') {
					// name of function
					window[func](this, args);
				}
			} // foreach event handler defined
		} // user defined handler for event
	}

};
<commit_msg>ZeroClipboard: movie might be undefined in IE, if checked too early.<commit_after>// Simple Set Clipboard System
// Author: Joseph Huckaby

var ZeroClipboard = {

	version: "1.0.7",
	clients: {}, // registered upload clients on page, indexed by id
	moviePath: 'ZeroClipboard.swf', // URL to movie
	nextId: 1, // ID of next movie

	$: function(thingy) {
		// simple DOM lookup utility function
		if (typeof(thingy) == 'string') thingy = document.getElementById(thingy);
		if (!thingy.addClass) {
			// extend element with a few useful methods
			thingy.hide = function() { this.style.display = 'none'; };
			thingy.show = function() { this.style.display = ''; };
			thingy.addClass = function(name) { this.removeClass(name); this.className += ' ' + name; };
			thingy.removeClass = function(name) {
				var classes = this.className.split(/\s+/);
				var idx = -1;
				for (var k = 0; k < classes.length; k++) {
					if (classes[k] == name) { idx = k; k = classes.length; }
				}
				if (idx > -1) {
					classes.splice( idx, 1 );
					this.className = classes.join(' ');
				}
				return this;
			};
			thingy.hasClass = function(name) {
				return !!this.className.match( new RegExp("\\s*" + name + "\\s*") );
			};
		}
		return thingy;
	},

	setMoviePath: function(path) {
		// set path to ZeroClipboard.swf
		this.moviePath = path;
	},

	dispatch: function(id, eventName, args) {
		// receive event from flash movie, send to client
		var client = this.clients[id];
		if (client) {
			client.receiveEvent(eventName, args);
		}
	},

	register: function(id, client) {
		// register new client to receive events
		this.clients[id] = client;
	},

	getDOMObjectPosition: function(obj, stopObj) {
		// get absolute coordinates for dom element
		var info = {
			left: 0,
			top: 0,
			width: obj.width ? obj.width : obj.offsetWidth,
			height: obj.height ? obj.height : obj.offsetHeight
		};

		while (obj && (obj != stopObj)) {
			info.left += obj.offsetLeft;
			info.top += obj.offsetTop;
			obj = obj.offsetParent;
		}

		return info;
	},

	Client: function(elem) {
		// constructor for new simple upload client
		this.handlers = {};

		// unique ID
		this.id = ZeroClipboard.nextId++;
		this.movieId = 'ZeroClipboardMovie_' + this.id;

		// register client with singleton to receive flash events
		ZeroClipboard.register(this.id, this);

		// create movie
		if (elem) this.glue(elem);
	}
};

ZeroClipboard.Client.prototype = {

	id: 0, // unique ID for us
	ready: false, // whether movie is ready to receive events or not
	movie: null, // reference to movie object
	clipText: '', // text to copy to clipboard
	handCursorEnabled: true, // whether to show hand cursor, or default pointer cursor
	cssEffects: true, // enable CSS mouse effects on dom container
	handlers: null, // user event handlers

	glue: function(elem, appendElem, stylesToAdd) {
		// glue to DOM element
		// elem can be ID or actual DOM element object
		this.domElement = ZeroClipboard.$(elem);

		// float just above object, or zIndex 99 if dom element isn't set
		var zIndex = 99;
		if (this.domElement.style.zIndex) {
			zIndex = parseInt(this.domElement.style.zIndex, 10) + 1;
		}

		if (typeof(appendElem) == 'string') {
			appendElem = ZeroClipboard.$(appendElem);
		}
		else if (typeof(appendElem) == 'undefined') {
			appendElem = document.getElementsByTagName('body')[0];
		}

		// find X/Y position of domElement
		var box = ZeroClipboard.getDOMObjectPosition(this.domElement, appendElem);

		// create floating DIV above element
		this.div = document.createElement('div');
		var style = this.div.style;
		style.position = 'absolute';
		style.left = '' + box.left + 'px';
		style.top = '' + box.top + 'px';
		style.width = '' + box.width + 'px';
		style.height = '' + box.height + 'px';
		style.zIndex = zIndex;

		if (typeof(stylesToAdd) == 'object') {
			for (addedStyle in stylesToAdd) {
				style[addedStyle] = stylesToAdd[addedStyle];
			}
		}

		// style.backgroundColor = '#f00'; // debug

		appendElem.appendChild(this.div);

		this.div.innerHTML = this.getHTML( box.width, box.height );
	},

	getHTML: function(width, height) {
		// return HTML for movie
		var html = '';
		var flashvars = 'id=' + this.id +
			'&width=' + width +
			'&height=' + height;

		if (navigator.userAgent.match(/MSIE/)) {
			// IE gets an OBJECT tag
			var protocol = location.href.match(/^https/i) ? 'https://' : 'http://';
			html += '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="'+protocol+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="'+width+'" height="'+height+'" id="'+this.movieId+'" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+ZeroClipboard.moviePath+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+flashvars+'"/><param name="wmode" value="transparent"/></object>';
		}
		else {
			// all other browsers get an EMBED tag
			html += '<embed id="'+this.movieId+'" src="'+ZeroClipboard.moviePath+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+width+'" height="'+height+'" name="'+this.movieId+'" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+flashvars+'" wmode="transparent" />';
		}
		return html;
	},

	hide: function() {
		// temporarily hide floater offscreen
		if (this.div) {
			this.div.style.left = '-2000px';
		}
	},

	show: function() {
		// show ourselves after a call to hide()
		this.reposition();
	},

	destroy: function() {
		// destroy control and floater
		if (this.domElement && this.div) {
			this.hide();
			this.div.innerHTML = '';

			var body = document.getElementsByTagName('body')[0];
			try { body.removeChild( this.div ); } catch(e) {;}

			this.domElement = null;
			this.div = null;
		}
	},

	reposition: function(elem) {
		// reposition our floating div, optionally to new container
		// warning: container CANNOT change size, only position
		if (elem) {
			this.domElement = ZeroClipboard.$(elem);
			if (!this.domElement) this.hide();
		}

		if (this.domElement && this.div) {
			var box = ZeroClipboard.getDOMObjectPosition(this.domElement);
			var style = this.div.style;
			style.left = '' + box.left + 'px';
			style.top = '' + box.top + 'px';
		}
	},

	setText: function(newText) {
		// set text to be copied to clipboard
		this.clipText = newText;
		if (this.ready) this.movie.setText(newText);
	},

	addEventListener: function(eventName, func) {
		// add user event listener for event
		// event types: load, queueStart, fileStart, fileComplete, queueComplete, progress, error, cancel
		eventName = eventName.toString().toLowerCase().replace(/^on/, '');
		if (!this.handlers[eventName]) this.handlers[eventName] = [];
		this.handlers[eventName].push(func);
	},

	setHandCursor: function(enabled) {
		// enable hand cursor (true), or default arrow cursor (false)
		this.handCursorEnabled = enabled;
		if (this.ready) this.movie.setHandCursor(enabled);
	},

	setCSSEffects: function(enabled) {
		// enable or disable CSS effects on DOM container
		this.cssEffects = !!enabled;
	},

	receiveEvent: function(eventName, args) {
		// receive event from flash
		eventName = eventName.toString().toLowerCase().replace(/^on/, '');

		// special behavior for certain events
		switch (eventName) {
			case 'load':
				// movie claims it is ready, but in IE this isn't always the case...
				// bug fix: Cannot extend EMBED DOM elements in Firefox, must use traditional function
				this.movie = document.getElementById(this.movieId);
				if (!this.movie || this.movie === undefined) {
					var self = this;
					setTimeout( function() { self.receiveEvent('load', null); }, 1 );
					return;
				}

				// firefox on pc needs a "kick" in order to set these in certain cases
				if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) {
					var self = this;
					setTimeout( function() { self.receiveEvent('load', null); }, 100 );
					this.ready = true;
					return;
				}

				this.ready = true;
				this.movie.setText( this.clipText );
				this.movie.setHandCursor( this.handCursorEnabled );
				break;

			case 'mouseover':
				if (this.domElement && this.cssEffects) {
					this.domElement.addClass('hover');
					if (this.recoverActive) this.domElement.addClass('active');
				}
				break;

			case 'mouseout':
				if (this.domElement && this.cssEffects) {
					this.recoverActive = false;
					if (this.domElement.hasClass('active')) {
						this.domElement.removeClass('active');
						this.recoverActive = true;
					}
					this.domElement.removeClass('hover');
				}
				break;

			case 'mousedown':
				if (this.domElement && this.cssEffects) {
					this.domElement.addClass('active');
				}
				break;

			case 'mouseup':
				if (this.domElement && this.cssEffects) {
					this.domElement.removeClass('active');
					this.recoverActive = false;
				}
				break;
		} // switch eventName

		if (this.handlers[eventName]) {
			for (var idx = 0, len = this.handlers[eventName].length; idx < len; idx++) {
				var func = this.handlers[eventName][idx];

				if (typeof(func) == 'function') {
					// actual function reference
					func(this, args);
				}
				else if ((typeof(func) == 'object') && (func.length == 2)) {
					// PHP style object + method, i.e. [myObject, 'myMethod']
					func[0][ func[1] ](this, args);
				}
				else if (typeof(func) == 'string') {
					// name of function
					window[func](this, args);
				}
			} // foreach event handler defined
		} // user defined handler for event
	}

};
<|endoftext|>


<commit_before>function SessionSetupPage() {
    BasePage.call(this);
    var self = this;

    self.games = ko.observableArray();
    self.selectedGame = ko.observable();
    self.selectedGame.subscribe(gameSelected);
    self.errandList = new ErrandListModel();

    self.startGame = function () {
        function redirectToLobby(result)
        {
            console.log(result);
        }

        var settings = {
            gameId: self.selectedGame().id()
        };
        $.post(window.BACKENDURL + 'gamesession/start', settings).then(redirectToLobby);
    };

    self.gameSetupReady = ko.computed(function () {
        return self.selectedGame() && self.errandList.errands().length > 0;
    });

    function gameSelected(game) {
        if (game) {
            self.errandList.startLoading();
            getErrands(game.id()).then(self.errandList.setErrands);
        } else {
            self.errandList.isInitialized(false);
        }
    }

    function setGames(data) {
        self.games(_.map(data, createGameModel));
    }

    function createGameModel(item) {
        var model = new GameModel();
        model.setValues(item);
        return model;
    }

    function getGames() {
        return $.getJSON(window.BACKENDURL + 'game');
    }

    function getErrands(gameId) {
        return $.getJSON(window.BACKENDURL + 'errand/game/' + gameId);
    }

    getGames().then(setGames).always(self.dataLoaded);
}<commit_msg>Added redirect to lobby after session creattion<commit_after>function SessionSetupPage() {
    BasePage.call(this);
    var self = this;

    self.games = ko.observableArray();
    self.selectedGame = ko.observable();
    self.selectedGame.subscribe(gameSelected);
    self.errandList = new ErrandListModel();

    self.startGame = function () {
        function redirectToLobby(result)
        {
            window.location = 'Lobby/?id=' + result
        }

        var settings = {
            gameId: self.selectedGame().id()
        };
        $.post(window.BACKENDURL + 'gamesession/start', settings).then(redirectToLobby);
    };

    self.gameSetupReady = ko.computed(function () {
        return self.selectedGame() && self.errandList.errands().length > 0;
    });

    function gameSelected(game) {
        if (game) {
            self.errandList.startLoading();
            getErrands(game.id()).then(self.errandList.setErrands);
        } else {
            self.errandList.isInitialized(false);
        }
    }

    function setGames(data) {
        self.games(_.map(data, createGameModel));
    }

    function createGameModel(item) {
        var model = new GameModel();
        model.setValues(item);
        return model;
    }

    function getGames() {
        return $.getJSON(window.BACKENDURL + 'game');
    }

    function getErrands(gameId) {
        return $.getJSON(window.BACKENDURL + 'errand/game/' + gameId);
    }

    getGames().then(setGames).always(self.dataLoaded);
}<|endoftext|>


<commit_before>"use strict";

// For conditions of distribution and use, see copyright notice in LICENSE

var cExecTypeLocal = 1;
var cExecTypeServer = 2;
var cExecTypePeers = 4;

function Entity() {
    this.components = {};
    this.parentScene = null;
    this.id = 0;
    this.temporary = false;
    this.componentIdGenerator = new UniqueIdGenerator();
    this.componentAdded = new signals.Signal();
    this.componentRemoved = new signals.Signal();
    this.actionTriggered = new signals.Signal();
    this.componentIdChanged = new signals.Signal();
}

Entity.prototype = {
    createComponent: function(id, typeId, name, changeType) {
        // If zero ID, assign ID now
        if (id == 0)
        {
            // If entity itself is local, create only local components
            if (this.local == true || changeType == AttributeChange.LocalOnly)
                id = this.componentIdGenerator.allocateLocal();
            else
                id = this.componentIdGenerator.allocateUnacked();
        }

        if (this.componentById(id))
        {
            console.log("Component id " + id + " in entity " + this.id + " already exists, can not create");
            return null;
        }
        var newComp = createComponent(typeId);
        if (newComp)
        {
            newComp.id = id;
            newComp.parentEntity = this;
            if (name != null)
                newComp.name = name;
            this.components[id] = newComp;
            // Register direct access by type
            var propName = sanitatePropertyName(newComp.typeName);
            if (this[propName] === undefined)
                this[propName] = newComp;
        }

        if (changeType == null || changeType == AttributeChange.Default)
            changeType = newComp.local ? AttributeChange.LocalOnly : AttributeChange.Replicate;
        if (changeType != AttributeChange.Disconnected)
        {
            // Trigger scene level signal
            if (this.parentScene)
                this.parentScene.emitComponentAdded(this, newComp, changeType);
            // Trigger entity level signal
            this.componentAdded.dispatch(newComp, changeType);
        }

        return newComp;
    },

    removeComponent: function(id, changeType) {
        if (this.components.hasOwnProperty(id))
        {
            var comp = this.components[id];
            delete this.components[id];
            // Remove direct access by type
            var propName = sanitatePropertyName(comp.typeName);
            if (this[propName] === comp)
                delete this[propName];

            if (changeType == null || changeType == AttributeChange.Default)
                changeType = comp.local ? AttributeChange.LocalOnly : AttributeChange.Replicate;
            if (changeType != AttributeChange.Disconnected)
            {
                // Trigger scene level signal
                if (this.parentScene)
                    this.parentScene.emitComponentRemoved(this, comp, changeType);
                // Trigger entity level signal
                this.componentRemoved.dispatch(comp, changeType);
            }
        }
        else
            console.log("Component id " + id + " in entity " + this.id + " does not exist, can not remove");
    },

    removeAllComponents: function(changeType) {
        for (var compId in this.components) {
            this.removeComponent(compId, changeType);
        }
    },

    triggerAction: function(name, params, execType) {
        if (execType == null)
            execType = cExecTypeLocal;
        this.actionTriggered.dispatch(name, params, execType);
        // Trigger scene level signal
        if (this.parentScene)
            this.parentScene.emitActionTriggered(this, name, params, execType);
    },

    // Change a component's id. Done in response to server sending back an authoritative id corresponding to an unacked id
    changeComponentId: function(oldId, newId) {
        if (oldId != newId)
        {
            var comp = this.components[oldId];
            if (comp == null)
            {
                console.log("Component id " + oldId + " not found, can not assign new id");
                return;
            }
            delete this.components[oldId];
            comp.id = newId;
            this.components[newId] = comp;

            this.componentIdChanged.dispatch(oldId, newId);
            // Trigger scene level signal
            if (this.parentScene)
                this.parentScene.emitComponentIdChanged(this, oldId, newId);
        }
    },

    componentById: function(id) {
        if (this.components.hasOwnProperty(id))
            return this.components[id];
        else
            return null;
    },

    componentByType: function(typeId, name) {
        // Convert typename to numeric ID if necessary
        if (typeof typeId == 'string' || typeId instanceof String)
            typeId = componentTypeIds[typeId];
        for (var compId in this.components) {
            if (this.components.hasOwnProperty(compId) && this.components[compId].typeId == typeId) {
                if (name == null || this.components[compId].name == name)
                    return this.components[compId];
            }
        }
        return null;
    },

    get local(){
        return this.id >= cFirstLocalId;
    },

    get unacked(){
        return this.id >= cFirstUnackedId && this.id < cFirstLocalId;
    },

    get name()
    {
        var nameComp = this.componentByType(cComponentTypeName);
        if (nameComp) {
            var nameAttr = nameComp.attributeById("name");
            return nameAttr.value;
        }
        else
            return "";
    },

    set name(value)
    {
        // Name exists in its own component, create if doesn't exist
        var nameComp = this.componentByType(cComponentTypeName);
        if (nameComp == null)
            nameComp = this.createComponent(0, cComponentTypeName, "");
        var nameAttr = nameComp.attributeById("name");
        nameAttr.value = value;
    }
};<commit_msg>Only send componentAdded signal on successful component creation<commit_after>"use strict";

// For conditions of distribution and use, see copyright notice in LICENSE

var cExecTypeLocal = 1;
var cExecTypeServer = 2;
var cExecTypePeers = 4;

function Entity() {
    this.components = {};
    this.parentScene = null;
    this.id = 0;
    this.temporary = false;
    this.componentIdGenerator = new UniqueIdGenerator();
    this.componentAdded = new signals.Signal();
    this.componentRemoved = new signals.Signal();
    this.actionTriggered = new signals.Signal();
    this.componentIdChanged = new signals.Signal();
}

Entity.prototype = {
    createComponent: function(id, typeId, name, changeType) {
        // If zero ID, assign ID now
        if (id == 0)
        {
            // If entity itself is local, create only local components
            if (this.local == true || changeType == AttributeChange.LocalOnly)
                id = this.componentIdGenerator.allocateLocal();
            else
                id = this.componentIdGenerator.allocateUnacked();
        }

        if (this.componentById(id))
        {
            console.log("Component id " + id + " in entity " + this.id + " already exists, can not create");
            return null;
        }
        var newComp = createComponent(typeId);
        if (newComp)
        {
            newComp.id = id;
            newComp.parentEntity = this;
            if (name != null)
                newComp.name = name;
            this.components[id] = newComp;
            // Register direct access by type
            var propName = sanitatePropertyName(newComp.typeName);
            if (this[propName] === undefined)
                this[propName] = newComp;
        }
        else
        {
            return null;
        }

        if (changeType == null || changeType == AttributeChange.Default)
            changeType = newComp.local ? AttributeChange.LocalOnly : AttributeChange.Replicate;
        if (changeType != AttributeChange.Disconnected)
        {
            // Trigger scene level signal
            if (this.parentScene)
                this.parentScene.emitComponentAdded(this, newComp, changeType);
            // Trigger entity level signal
            this.componentAdded.dispatch(newComp, changeType);
        }

        return newComp;
    },

    removeComponent: function(id, changeType) {
        if (this.components.hasOwnProperty(id))
        {
            var comp = this.components[id];
            delete this.components[id];
            // Remove direct access by type
            var propName = sanitatePropertyName(comp.typeName);
            if (this[propName] === comp)
                delete this[propName];

            if (changeType == null || changeType == AttributeChange.Default)
                changeType = comp.local ? AttributeChange.LocalOnly : AttributeChange.Replicate;
            if (changeType != AttributeChange.Disconnected)
            {
                // Trigger scene level signal
                if (this.parentScene)
                    this.parentScene.emitComponentRemoved(this, comp, changeType);
                // Trigger entity level signal
                this.componentRemoved.dispatch(comp, changeType);
            }
        }
        else
            console.log("Component id " + id + " in entity " + this.id + " does not exist, can not remove");
    },

    removeAllComponents: function(changeType) {
        for (var compId in this.components) {
            this.removeComponent(compId, changeType);
        }
    },

    triggerAction: function(name, params, execType) {
        if (execType == null)
            execType = cExecTypeLocal;
        this.actionTriggered.dispatch(name, params, execType);
        // Trigger scene level signal
        if (this.parentScene)
            this.parentScene.emitActionTriggered(this, name, params, execType);
    },

    // Change a component's id. Done in response to server sending back an authoritative id corresponding to an unacked id
    changeComponentId: function(oldId, newId) {
        if (oldId != newId)
        {
            var comp = this.components[oldId];
            if (comp == null)
            {
                console.log("Component id " + oldId + " not found, can not assign new id");
                return;
            }
            delete this.components[oldId];
            comp.id = newId;
            this.components[newId] = comp;

            this.componentIdChanged.dispatch(oldId, newId);
            // Trigger scene level signal
            if (this.parentScene)
                this.parentScene.emitComponentIdChanged(this, oldId, newId);
        }
    },

    componentById: function(id) {
        if (this.components.hasOwnProperty(id))
            return this.components[id];
        else
            return null;
    },

    componentByType: function(typeId, name) {
        // Convert typename to numeric ID if necessary
        if (typeof typeId == 'string' || typeId instanceof String)
            typeId = componentTypeIds[typeId];
        for (var compId in this.components) {
            if (this.components.hasOwnProperty(compId) && this.components[compId].typeId == typeId) {
                if (name == null || this.components[compId].name == name)
                    return this.components[compId];
            }
        }
        return null;
    },

    get local(){
        return this.id >= cFirstLocalId;
    },

    get unacked(){
        return this.id >= cFirstUnackedId && this.id < cFirstLocalId;
    },

    get name()
    {
        var nameComp = this.componentByType(cComponentTypeName);
        if (nameComp) {
            var nameAttr = nameComp.attributeById("name");
            return nameAttr.value;
        }
        else
            return "";
    },

    set name(value)
    {
        // Name exists in its own component, create if doesn't exist
        var nameComp = this.componentByType(cComponentTypeName);
        if (nameComp == null)
            nameComp = this.createComponent(0, cComponentTypeName, "");
        var nameAttr = nameComp.attributeById("name");
        nameAttr.value = value;
    }
};
<|endoftext|>


<commit_before>(function (global, document) {
  "use strict";

  (document);

  global.numberify = function(x) {
    if (x === 0) {
      return {"zeros": "000", "num": "", "units": ""}
    }

    if (x < 10) {
      return {"zeros": "00", "num": x, "units": ""}
    }

    if (x < 100) {
      return {"zeros": "0", "num": x, "units": ""}
    }

    if (x < 1000) {
      return {"zeros": "", "num": x, "units": ""}
    }

    var res;

    if (x < 1000000) {
      res = global.numberify((x/1000).toFixed(0))
      res.units = "K"
    } else if (x < 1000000000) {
      res = global.numberify((x/1000000).toFixed(0))
      res.units = "M"
    } else if (x < 1000000000000) {
      res = global.numberify((x/1000000000).toFixed(0))
      res.units = "B"
    }

    if (res.num*10 % 10 === 0) {
      res.num = Math.ceil(res.num);
    }

    return res;
  }

  global.statisticsOpen = function() {
    var data = global.dashboard.$data;

    var json = {
      "ownerToken": global.cookieGet("commentoOwnerToken"),
      "domain": data.domains[data.cd].domain,
    }

    $(".view").hide();
    global.post(global.origin + "/api/domain/statistics", json, function(resp) {
      $("#statistics-view").show();

      if (!resp.success) {
        global.globalErrorShow(resp.message);
        return;
      }

      var options = {
        showPoint: false,
        axisY: {
          onlyInteger: true,
          showGrid: false,
        },
        axisX: {
          showGrid: false,
        },
        showArea: true,
      };

      var views;
      var comments;

      views = resp.viewsLast30Days;
      // views = [0, 1, 4, 16, 14, 12, 10, 25, 13, 5, 20, 25, 12, 57, 46, 64, 4, 36, 7, 80, 43, 86, 121, 6, 74, 94, 83, 73, 140, 89, 25];

      comments = resp.commentsLast30Days;
      // comments = [0, 0, 1, 2, 3, 3, 4, 5, 7, 8, 5, 9, 9, 5, 6, 7, 8, 3, 1, 16, 3, 10, 8, 5, 12, 5, 4, 8, 4, 23, 19];

      var labels = new Array();
      for (var i = 0; i < views.length; i++) {
        if ((views.length-i) % 7 === 0) {
          var x = (views.length-i)/7;
          labels.push(x + " week" + (x > 1 ? "s" : "") + " ago");
        } else {
          labels.push("");
        }
      }

      new Chartist.Line("#views-graph", {
        labels: labels,
        series: [views],
      }, options);

      new Chartist.Line("#comments-graph", {
        labels: labels,
        series: [comments],
      }, options);

      data.domains[data.cd].viewsLast30Days = numberify(views.reduce(function(a, b) {
        return a + b;
      }, 0));
      data.domains[data.cd].commentsLast30Days = numberify(comments.reduce(function(a, b) {
        return a + b;
      }, 0));
    });
  }

} (window.commento, document));
<commit_msg>dashboard-statistics.js: namespace numberify with global<commit_after>(function (global, document) {
  "use strict";

  (document);

  global.numberify = function(x) {
    if (x === 0) {
      return {"zeros": "000", "num": "", "units": ""}
    }

    if (x < 10) {
      return {"zeros": "00", "num": x, "units": ""}
    }

    if (x < 100) {
      return {"zeros": "0", "num": x, "units": ""}
    }

    if (x < 1000) {
      return {"zeros": "", "num": x, "units": ""}
    }

    var res;

    if (x < 1000000) {
      res = global.numberify((x/1000).toFixed(0))
      res.units = "K"
    } else if (x < 1000000000) {
      res = global.numberify((x/1000000).toFixed(0))
      res.units = "M"
    } else if (x < 1000000000000) {
      res = global.numberify((x/1000000000).toFixed(0))
      res.units = "B"
    }

    if (res.num*10 % 10 === 0) {
      res.num = Math.ceil(res.num);
    }

    return res;
  }

  global.statisticsOpen = function() {
    var data = global.dashboard.$data;

    var json = {
      "ownerToken": global.cookieGet("commentoOwnerToken"),
      "domain": data.domains[data.cd].domain,
    }

    $(".view").hide();
    global.post(global.origin + "/api/domain/statistics", json, function(resp) {
      $("#statistics-view").show();

      if (!resp.success) {
        global.globalErrorShow(resp.message);
        return;
      }

      var options = {
        showPoint: false,
        axisY: {
          onlyInteger: true,
          showGrid: false,
        },
        axisX: {
          showGrid: false,
        },
        showArea: true,
      };

      var views;
      var comments;

      views = resp.viewsLast30Days;
      // views = [0, 1, 4, 16, 14, 12, 10, 25, 13, 5, 20, 25, 12, 57, 46, 64, 4, 36, 7, 80, 43, 86, 121, 6, 74, 94, 83, 73, 140, 89, 25];

      comments = resp.commentsLast30Days;
      // comments = [0, 0, 1, 2, 3, 3, 4, 5, 7, 8, 5, 9, 9, 5, 6, 7, 8, 3, 1, 16, 3, 10, 8, 5, 12, 5, 4, 8, 4, 23, 19];

      var labels = new Array();
      for (var i = 0; i < views.length; i++) {
        if ((views.length-i) % 7 === 0) {
          var x = (views.length-i)/7;
          labels.push(x + " week" + (x > 1 ? "s" : "") + " ago");
        } else {
          labels.push("");
        }
      }

      new Chartist.Line("#views-graph", {
        labels: labels,
        series: [views],
      }, options);

      new Chartist.Line("#comments-graph", {
        labels: labels,
        series: [comments],
      }, options);

      data.domains[data.cd].viewsLast30Days = global.numberify(views.reduce(function(a, b) {
        return a + b;
      }, 0));
      data.domains[data.cd].commentsLast30Days = global.numberify(comments.reduce(function(a, b) {
        return a + b;
      }, 0));
    });
  }

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


<commit_before>module.exports = function (config) {
  config.set({

    template: {
      // By default templates use tab for indentation
      // You can pass any string and each tab will be replaced with that string.
      // You can pass integer and it will be a number of spaces for indentation.
      indent: '\t',

      // Include "use strict" statement to the top of the generated test file
      useStrict: true,

      // Add commented examples of basic specs to the generated test file
      includeSamples: true,
    },

    units: {

      // List the unit types which should be processed. Only the types mentioned
      // here will be parsed and asked about.
      // The order they appear can be changed by reordering these keys.
      process: [
        'controller', 'directive', 'factory', 'service',
        'filter', 'provider', 'value', 'constant'
      ]

    },

    dependencies: {

      // List the dependencies which should be processed. Only the
      // types mentioned here will be included in generated test code.
      // The order they appear can be changed by reordering these keys.
      process: ['provider', 'service', 'factory', 'value', 'constant'],

      // Exclude particular dependencies, there won't be any test code generated
      // for them.
      filter: ['$scope'],

      // Map dependency type to a respective template. Can be helpful in case
      // when one wants to stub services and factories with values.
      templateMap: {
        'provider': 'provider',
        'service': 'service',
        'factory': 'factory',
        'value': 'value',
        'constant': 'constant'
      }

    }

  });
};<commit_msg>fix(config): Reorder processed dependencies appearance.<commit_after>module.exports = function (config) {
  config.set({

    template: {
      // By default templates use tab for indentation
      // You can pass any string and each tab will be replaced with that string.
      // You can pass integer and it will be a number of spaces for indentation.
      indent: '\t',

      // Include "use strict" statement to the top of the generated test file
      useStrict: true,

      // Add commented examples of basic specs to the generated test file
      includeSamples: true,
    },

    units: {

      // List the unit types which should be processed. Only the types mentioned
      // here will be parsed and asked about.
      // The order they appear can be changed by reordering these keys.
      process: [
        'controller', 'directive', 'factory', 'service',
        'filter', 'provider', 'value', 'constant'
      ]

    },

    dependencies: {

      // List the dependencies which should be processed. Only the
      // types mentioned here will be included in generated test code.
      // The order they appear can be changed by reordering these keys.
      process: ['factory', 'service', 'provider', 'value', 'constant'],

      // Exclude particular dependencies, there won't be any test code generated
      // for them.
      filter: ['$scope'],

      // Map dependency type to a respective template. Can be helpful in case
      // when one wants to stub services and factories with values.
      templateMap: {
        'factory': 'factory',
        'service': 'service',
        'provider': 'provider',
        'value': 'value',
        'constant': 'constant'
      }

    }

  });
};<|endoftext|>


<commit_before>angular.module('courseReg', [])
    .controller('CoureRegController', ['$scope', '$http', function($scope, $http){
        $scope.courseRegList;

        $scope.clickListener = function(e)
        {
            if(e.target.id == "sendEmail")
                emailjs.send("gmail","gmail").then(
                    function(response) {
                        alert("success");
                    },
                    function(error) {
                        alert("failed");
                    }
                )
            //{name:$("#username").html(), email:$("#email").html(), tel:$("#tel").html()}
        }

        $scope.loadCourseReg = function()
        {
            $http.get('/course')
                .success(function(res){
                    $scope.courseRegList = res;
                    $("#sendEmail").click(clickListener);
                })
                .catch(function(err) {
                    console.log('Get courses error.');
                });
        };
        $scope.loadCourseReg();
    }]);

<commit_msg>minor changes<commit_after>angular.module('courseReg', [])
    .controller('CoureRegController', ['$scope', '$http', function($scope, $http){
        $scope.courseRegList;

        var clickListener = function(e)
        {

            if(e.target.id == "sendEmail")
            {
                emailjs.send("gmail","gmail",{name:$("#username").val(), email:$("#email").val(), tel:$("#tel").val()}).then(
                    function(response) {
                        alert("המייל נשלח בהצלחה");
                    },
                    function(error) {
                        alert("נכשל");
                    }
                );
            }
        }

        $scope.loadCourseReg = function()
        {
            $http.get('/course')
                .success(function(res){
                    $scope.courseRegList = res;
                    $("#sendEmail").click(clickListener);
                })
                .catch(function(err) {
                    console.log('Get courses error.');
                });
        };
        $scope.loadCourseReg();
    }]);<|endoftext|>


<commit_before><<<<<<< HEAD
var octonode    = require('octonode');
var path        = require('path');
var child       = require('child_process');
var pkg_config  = require('config-tree');
var chalk			  = require('chalk');
var io 					= require('indian-ocean');
=======
var fs          = require('fs')
var octonode    = require('octonode')
var path        = require('path')
var child       = require('child_process')
var pkg_config  = require('config-tree')
var chalk			  = require('chalk')
var io          = require('indian-ocean')
>>>>>>> 87f6e6aa3182983580d4b655693a6c4384f77f69

// Github authentication
var config;
var gh_client;
var gh_entity;

var sh_commands = require('./sh-commands.js');

/*    I N I T  C O M M A N D S   */
function configClient(){
	var dir = path.dirname(__dirname);
	pkg_config.sprout(dir, 'kestrel');
}

/*    C R E A T I O N  C O M M A N D S   */
function setGitHubOrgType(gh_c){
	if (config.github.type == 'org'){
		return gh_c.org(config.github.account_name);
	} else if (config.github.type == 'individual'){
		return gh_c.me();
	}
}

function kestrelInit(cb){
	child.exec( sh_commands.kestrelInit(), cb );
}

function gitInit(current_dir, cb){
	child.exec( sh_commands.gitInit(config.github.login_method, config.github.account_name, current_dir), cb );
}

function createGitHubRepo(repo_name, cb){
	gh_entity.repo({
	  "name": repo_name,
	  "private": config.github.private_repos
	}, function(err, response){
		cb(err, response);
	});
}

function createGitHubHook(repo_name, cb){
	var gh_repo = gh_client.repo(config.github.account_name + '/' + repo_name);

	gh_repo.hook({
	  "name": "web",
	  "active": true,
	  "events": ["push", "status"],
	  "config": {
	    "url": config.server.url
	  }
	}, function(err, response){
		cb(err, response);
	});
}

function setConfig(set_gh){
<<<<<<< HEAD
  var home_dir = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
  var conf_dir_path = path.join(home_dir, '.conf');
  var config_path = path.join(home_dir,  '.conf', 'kestrel-config.json');
  var conf_dir_exists = io.existsSync( conf_dir_path );
  var config_exists = io.existsSync( config_path );

  if (!conf_dir_exists) {
  	throw '~/.conf folder not found. Please run `swoop config`.';
  }
  if (!config_exists) {
  	throw '~/.conf/kestrel-config.json not found. Please run `swoop config`.';
  }
=======
  var home_dir = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE,
  		conf_dir_path = home_dir + '/.conf',
  		config_path = home_dir + '/.conf/kestrel-config.json',
  		conf_dir_exists = io.existsSync( conf_dir_path ),
  		config_exists = io.existsSync( config_path );

  if (!conf_dir_exists) throw '~/.conf folder not found. Please run `swoop config`.'
  if (!config_exists) throw '~/.conf/kestrel-config.json not found. Please run `swoop config`.'
>>>>>>> 87f6e6aa3182983580d4b655693a6c4384f77f69

  config = config || require(config_path);
	if (set_gh){
		gh_client = gh_client || octonode.client(config.github.access_token);
		gh_entity = gh_entity || setGitHubOrgType(gh_client);
	}
	return config;
}

function getProjectName(cb){
	var current_dir = path.basename(path.resolve('./'))
	if (!io.existsSync('./.git')) {
		cb(current_dir)
	} else {
		child.exec(sh_commands.getGitRemoteProjectName(), function(err, stdout, stderr ) {
			if (err || stdout.trim() == 'Fetch URL: origin') {
				console.log(chalk.yellow('Warning: Could not get remote project name from .git folder.'))
				console.log('> This could simply mean you have initialized git but haven\'t connected it to a GitHub repository.')
				cb(current_dir)
			} else {
				// Grab the repo name from the url, if that doesn't work, default to current directory name
				var url_parts = stdout.split('/')
				var project_name = url_parts[url_parts.length - 1].replace(/\.git/, '')
				cb(project_name)
			}
		})
	}
}

function initAll(){
	setConfig(true);
<<<<<<< HEAD
	var current_dir = path.basename(path.resolve('.'));
	kestrelInit(function(err0, stdout0, stderr1){
		if (err0){
			console.log( chalk.yellow('Step 1/4: Skipping. .kestrel folder already exists.') );
		} else {
			console.log(chalk.green('Step 1/4: `.kestrel` folder created!'));
		}
=======
>>>>>>> 87f6e6aa3182983580d4b655693a6c4384f77f69

	getProjectName(function(project_name){
		console.log('Setting repo name as:', chalk.bold(project_name))
		kestrelInit(function(err0, stdout0, stderr1){
			if (err0){
				console.log( chalk.yellow('Step 1/4: Skipping. .kestrel folder already exists.') );
			} else {
				console.log(chalk.green('Step 1/4: `.kestrel` folder created!'));
			}

			gitInit(project_name, function(err1, stdout, stderr){
				if (err1) {
					console.log(chalk.yellow('Step 2/4: Warning:') + ' Git remote origin already set. You should manually run ' + chalk.bold('git remote set-url origin ' + sh_commands.gitInit(config.github.login_method, config.github.account_name, project_name).split('origin ')[1]) );
				} else {
					console.log(chalk.green('Step 2/4: Git init\'ed and origin set!'));
				}

				createGitHubRepo(project_name, function(err2, response){
					if (err2) {
						console.log(chalk.yellow('Step 3/4: GitHub repo creation failed!') + ' `Validation Failed` could mean it already exists.' + '\nCheck here: ' + chalk.cyan('https://github.com/' + config.github.account_name + '/' + project_name) + '\nStated reason:', err2.message);
					} else {
						console.log(chalk.green('Step 3/4: GitHub repo created!'));
					}

					createGitHubHook(project_name, function(err3){
						if (err3) {
							console.log(chalk.yellow('Step 4/4: GitHub hook creation failed!') + ' `Validation Failed` could mean it already exists.' + '\nCheck here: ' + chalk.cyan('https://github.com/' + config.github.account_name + '/' + project_name + '/settings/hooks') + '\nStated reason:', err3.message);
						} else {
							console.log(chalk.green('Step 4/4: GitHub hook created.') + ' Once you push you can preview it at:\n  ' + chalk.bold(config.server.url.split(':').slice(0,2).join(':') + ':3000/' + project_name) );
						}
					});
				});
			});
		});
	});
}

/*    D E P L O Y   C O M M A N D S   */
function checkGitStatus(gitStatus){
	gitStatus = gitStatus.trim();
	// These could also be `.indexOf` and avoid escaping
	var ahead_regex = new RegExp('ahead');
	var behind_regex = new RegExp('behind');
	var kestrel_init_regex = new RegExp('\.kestrel\/');
	var deploy_settings_regex = new RegExp('\.kestrel\/deploy-settings\.json');
	var git_status_lines = gitStatus.split('\n');

	// If it's just two lines and the second line describes a change to `.kestrel/deploy-settings.json` then we're okay.
	// It should also ignore the creation of the `.kestrel` folder
	if (git_status_lines.length == 2 && ( deploy_settings_regex.exec(git_status_lines[1]) || kestrel_init_regex.exec(git_status_lines[1])) ) return 'clean_with_deploy_change';
	// If the status has more than one line, we have uncommitted changes
	if (git_status_lines.length > 1) return 'uncommitted';
	// If the status has the word ahead and behind then we have to pull and push
	if (ahead_regex.exec(gitStatus) && behind_regex.exec(gitStatus)) return 'ahead_and_behind';
	// Allow for deployment if we are ahead
	if (ahead_regex.exec(gitStatus)) return 'clean';
	// if (ahead_regex.exec(gitStatus)) return 'ahead';
	// Don't allow for deployment if we are behind. This condition will rarely be triggered and will also be caught by git itself when your push fails
	if (behind_regex.exec(gitStatus)) return 'behind';
	return 'clean';
}

function deployLastCommit(bucket_environment, trigger_type, trigger, local_path, remote_path, when){
  setConfig(true);
	var current_dir = path.resolve('.');

	var trigger_commit_msg  = bucket_environment + '::' + trigger + '::' + local_path + '::' + remote_path + '::' + when;

	// Make sure the working branch has no outstanding commits and is neither ahead or behind
	// Normally outstanding commits wouldn't be a problem, but the push flag allows for an empty commit
	// So if we had untracked or uncommitted files, it would just push the last commit.
	child.exec( sh_commands.status(), function(err0, stdout0, stderr0){
		if (err0 !== null) throw stderr1;
		var branch_status = checkGitStatus(stdout0),
				push,
				erred_out = false,
				spawnPush = sh_commands.spawnPush();

		// If stdout is blank, we have nothing to commit
		if (branch_status == 'clean' || branch_status == 'clean_with_deploy_change') {
			// Add the trigger as a commit message and push
			console.log(chalk.bgBlue.black('Pushing to GitHub...'));
			child.exec( sh_commands.makeEmptyCommitMsg(trigger_commit_msg), function(err1, stdout1, stderr1){
				if (!err1){
					push = child.spawn( spawnPush[0], spawnPush[1], {stdio: 'inherit'} );
				} else {
					console.log(chalk.red.bold('Error commiting!'));
				}

				// When done
				push.on('close', function(code){
					if (code != 0){
						// On error, erase the commit that has the trigger because the trigger push didn't go through
						child.exec( sh_commands.revertToPreviousCommit(), function(err2, stdout2, stderr2){
							if (err2) {
								console.log(chalk.red.bold('Error pushing AND error scrubbing the push commit. You might want to grab the SHA of the last commit you made and run `git rest --soft INSERT-SHA-HERE` in order to manually remove Kestrel\'s deploy commit.'));
								console.log(chalk.yellow('Once you do that, please check our internet connection and try again'));
								throw stderr2 + '\nAND\n' + err2;
							} else {
								if (code == 128){
									console.log(chalk.red.bold('Failed!'))
									console.log(chalk.yellow('Reason: Your internet connection appears down'));
								} else if (code == 1){
									console.log(chalk.red.bold('Failed!'))
									console.log(chalk.yellow('Reason: Please pull before pushing.'));
								} else {
									console.log(chalk.red.bold('Failed! Error code: ' + code.toString()), 'Try Googling this reason code to find out more.');
								}
							}
						});
					} else {
						// Otherwise, things went great!
						// Print the commands that got us to this auspicious moment.
						// Add a `_` for the `when` value because that needs to be one single string for the cli arg reader
						console.log(chalk.cyan('Settings: ') + 'swoop deploy -e ' + bucket_environment + ' -m ' + trigger_type + ' -l ' + local_path + ' -r ' + remote_path + ' -w ' + when.replace(' ', '_'));
						console.log(chalk.green('Push successful!'));
					}
				});
			});

		} else {
			if (branch_status == 'uncommitted') throw chalk.red.bold('Error!') + chalk.yellow(' You have uncommitted changes on this branch.' + ' Please commit your changes before attempting to deploy.')
			if (branch_status == 'ahead_and_behind') throw chalk.red.bold('Error!') + chalk.yellow(' You have unpushed commits on this branch and your local branch is behind your remote.' + ' Please pull and then push your changes before attempting to deploy.')
			// EDIT: It's okay if they haven't push their commits. Like the edit above to the scrub push, removing this step will result in fewer pushes for the server to respond to. This alert is currently not being triggered because the branch status no longer as a condition where it is set to ahead.
			// if (branch_status == 'ahead') throw chalk.red.bold('Error!') + ' You have unpushed commits on this branch.' + ' Please push your changes before attempting to deploy.'.yellow;
			if (branch_status == 'behind') throw chalk.red.bold('Error!') + chalk.yellow(' Your local branch is behind your remote.' + ' Please pull, merge and push before attempting to deploy.')
		}
	});
}

/*    C R E A T E  A R C H I V E  B R A N C H   */
function addToArchive(deploySettings){
	var local_branch = deploySettings.local_branch;
	var remote_branch = deploySettings.remote_branch;

  setConfig(true);
  var repo_name = path.basename(path.resolve('.'));
  var archive_push = sh_commands.archive(config.github.login_method, config.github.account_name, config.archive.repo_name, local_branch, remote_branch);

	console.log(chalk.bgBlue.black('Pushing to GitHub...'));
	child.spawn( archive_push[0], archive_push[1], {stdio: 'inherit'} )
	  .on('close', function(code){
	  	if (code != 0){
				console.log(chalk.red.bold('Archive failed.', 'Error code: ' + chalk.bold( code.toString()) ));
				if (code == 128){
					console.log(chalk.yellow('Reason:') + chalk.bold('Your internet connection appears down'));
				}
	  	} else {
	  		console.log(chalk.green('Success!') + ' `' + local_branch + '` branch of `' + repo_name + '` archived as `' + remote_branch + '` on the `' + config.archive.repo_name + '` repo.\n  https://github.com/' + config.github.account_name + '/' + config.archive.repo_name + '/tree/' + remote_branch + '\n' + chalk.cyan('Note:') + ' Your existing repo has not been deleted. Please do that manually through GitHub:\n  https://github.com/' + config.github.account_name + '/' + repo_name + '/settings')
	  	}
	  })
}

function reportError(err, msg){
	console.log(msg, '\nReason:');
	throw err;
}

module.exports = {
	setConfig: setConfig,
	config: configClient,
	init: initAll,
	deploy: deployLastCommit,
	archive: addToArchive,
	unschedule: deployLastCommit
}
<commit_msg>fix merge<commit_after>var octonode    = require('octonode');
var path        = require('path');
var child       = require('child_process');
var pkg_config  = require('config-tree');
var chalk			  = require('chalk');
var io 					= require('indian-ocean');

// Github authentication
var config;
var gh_client;
var gh_entity;

var sh_commands = require('./sh-commands.js');

/*    I N I T  C O M M A N D S   */
function configClient(){
	var dir = path.dirname(__dirname);
	pkg_config.sprout(dir, 'kestrel');
}

/*    C R E A T I O N  C O M M A N D S   */
function setGitHubOrgType(gh_c){
	if (config.github.type == 'org'){
		return gh_c.org(config.github.account_name);
	} else if (config.github.type == 'individual'){
		return gh_c.me();
	}
}

function kestrelInit(cb){
	child.exec( sh_commands.kestrelInit(), cb );
}

function gitInit(current_dir, cb){
	child.exec( sh_commands.gitInit(config.github.login_method, config.github.account_name, current_dir), cb );
}

function createGitHubRepo(repo_name, cb){
	gh_entity.repo({
	  "name": repo_name,
	  "private": config.github.private_repos
	}, function(err, response){
		cb(err, response);
	});
}

function createGitHubHook(repo_name, cb){
	var gh_repo = gh_client.repo(config.github.account_name + '/' + repo_name);

	gh_repo.hook({
	  "name": "web",
	  "active": true,
	  "events": ["push", "status"],
	  "config": {
	    "url": config.server.url
	  }
	}, function(err, response){
		cb(err, response);
	});
}

function setConfig(set_gh){
  var home_dir = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
  var conf_dir_path = path.join(home_dir, '.conf');
  var config_path = path.join(home_dir,  '.conf', 'kestrel-config.json');
  var conf_dir_exists = io.existsSync( conf_dir_path );
  var config_exists = io.existsSync( config_path );

  if (!conf_dir_exists) {
  	throw '~/.conf folder not found. Please run `swoop config`.';
  }
  if (!config_exists) {
  	throw '~/.conf/kestrel-config.json not found. Please run `swoop config`.';
  }

  config = config || require(config_path);
	if (set_gh){
		gh_client = gh_client || octonode.client(config.github.access_token);
		gh_entity = gh_entity || setGitHubOrgType(gh_client);
	}
	return config;
}

function getProjectName(cb){
	var current_dir = path.basename(path.resolve('./'))
	if (!io.existsSync('./.git')) {
		cb(current_dir)
	} else {
		child.exec(sh_commands.getGitRemoteProjectName(), function(err, stdout, stderr ) {
			if (err || stdout.trim() == 'Fetch URL: origin') {
				console.log(chalk.yellow('Warning: Could not get remote project name from .git folder.'))
				console.log('> This could simply mean you have initialized git but haven\'t connected it to a GitHub repository.')
				cb(current_dir)
			} else {
				// Grab the repo name from the url, if that doesn't work, default to current directory name
				var url_parts = stdout.split('/')
				var project_name = url_parts[url_parts.length - 1].replace(/\.git/, '')
				cb(project_name)
			}
		})
	}
}

function initAll(){
	setConfig(true);
	getProjectName(function(project_name){
		console.log('Using project name:', chalk.bold(project_name))
		kestrelInit(function(err0, stdout0, stderr1){
			if (err0){
				console.log( chalk.yellow('Step 1/4: Skipping. .kestrel folder already exists.') );
			} else {
				console.log(chalk.green('Step 1/4: `.kestrel` folder created!'));
			}

			gitInit(project_name, function(err1, stdout, stderr){
				if (err1) {
					console.log(chalk.yellow('Step 2/4: Warning:') + ' Git remote origin already set. You should manually run ' + chalk.bold('git remote set-url origin ' + sh_commands.gitInit(config.github.login_method, config.github.account_name, project_name).split('origin ')[1]) );
				} else {
					console.log(chalk.green('Step 2/4: Git init\'ed and origin set!'));
				}

				createGitHubRepo(project_name, function(err2, response){
					if (err2) {
						console.log(chalk.yellow('Step 3/4: GitHub repo creation failed!') + ' `Validation Failed` could mean it already exists.' + '\nCheck here: ' + chalk.cyan('https://github.com/' + config.github.account_name + '/' + project_name) + '\nStated reason:', err2.message);
					} else {
						console.log(chalk.green('Step 3/4: GitHub repo created!'));
					}

					createGitHubHook(project_name, function(err3){
						if (err3) {
							console.log(chalk.yellow('Step 4/4: GitHub hook creation failed!') + ' `Validation Failed` could mean it already exists.' + '\nCheck here: ' + chalk.cyan('https://github.com/' + config.github.account_name + '/' + project_name + '/settings/hooks') + '\nStated reason:', err3.message);
						} else {
							console.log(chalk.green('Step 4/4: GitHub hook created.') + ' Once you push you can preview it at:\n  ' + chalk.bold(config.server.url.split(':').slice(0,2).join(':') + ':3000/' + project_name) );
						}
					});
				});
			});
		});
	});
}

/*    D E P L O Y   C O M M A N D S   */
function checkGitStatus(gitStatus){
	gitStatus = gitStatus.trim();
	// These could also be `.indexOf` and avoid escaping
	var ahead_regex = new RegExp('ahead');
	var behind_regex = new RegExp('behind');
	var kestrel_init_regex = new RegExp('\.kestrel\/');
	var deploy_settings_regex = new RegExp('\.kestrel\/deploy-settings\.json');
	var git_status_lines = gitStatus.split('\n');

	// If it's just two lines and the second line describes a change to `.kestrel/deploy-settings.json` then we're okay.
	// It should also ignore the creation of the `.kestrel` folder
	if (git_status_lines.length == 2 && ( deploy_settings_regex.exec(git_status_lines[1]) || kestrel_init_regex.exec(git_status_lines[1])) ) return 'clean_with_deploy_change';
	// If the status has more than one line, we have uncommitted changes
	if (git_status_lines.length > 1) return 'uncommitted';
	// If the status has the word ahead and behind then we have to pull and push
	if (ahead_regex.exec(gitStatus) && behind_regex.exec(gitStatus)) return 'ahead_and_behind';
	// Allow for deployment if we are ahead
	if (ahead_regex.exec(gitStatus)) return 'clean';
	// if (ahead_regex.exec(gitStatus)) return 'ahead';
	// Don't allow for deployment if we are behind. This condition will rarely be triggered and will also be caught by git itself when your push fails
	if (behind_regex.exec(gitStatus)) return 'behind';
	return 'clean';
}

function deployLastCommit(bucket_environment, trigger_type, trigger, local_path, remote_path, when){
  setConfig(true);
	var current_dir = path.resolve('.');

	var trigger_commit_msg  = bucket_environment + '::' + trigger + '::' + local_path + '::' + remote_path + '::' + when;

	// Make sure the working branch has no outstanding commits and is neither ahead or behind
	// Normally outstanding commits wouldn't be a problem, but the push flag allows for an empty commit
	// So if we had untracked or uncommitted files, it would just push the last commit.
	child.exec( sh_commands.status(), function(err0, stdout0, stderr0){
		if (err0 !== null) throw stderr1;
		var branch_status = checkGitStatus(stdout0),
				push,
				erred_out = false,
				spawnPush = sh_commands.spawnPush();

		// If stdout is blank, we have nothing to commit
		if (branch_status == 'clean' || branch_status == 'clean_with_deploy_change') {
			// Add the trigger as a commit message and push
			console.log(chalk.bgBlue.black('Pushing to GitHub...'));
			child.exec( sh_commands.makeEmptyCommitMsg(trigger_commit_msg), function(err1, stdout1, stderr1){
				if (!err1){
					push = child.spawn( spawnPush[0], spawnPush[1], {stdio: 'inherit'} );
				} else {
					console.log(chalk.red.bold('Error commiting!'));
				}

				// When done
				push.on('close', function(code){
					if (code != 0){
						// On error, erase the commit that has the trigger because the trigger push didn't go through
						child.exec( sh_commands.revertToPreviousCommit(), function(err2, stdout2, stderr2){
							if (err2) {
								console.log(chalk.red.bold('Error pushing AND error scrubbing the push commit. You might want to grab the SHA of the last commit you made and run `git rest --soft INSERT-SHA-HERE` in order to manually remove Kestrel\'s deploy commit.'));
								console.log(chalk.yellow('Once you do that, please check our internet connection and try again'));
								throw stderr2 + '\nAND\n' + err2;
							} else {
								if (code == 128){
									console.log(chalk.red.bold('Failed!'))
									console.log(chalk.yellow('Reason: Your internet connection appears down'));
								} else if (code == 1){
									console.log(chalk.red.bold('Failed!'))
									console.log(chalk.yellow('Reason: Please pull before pushing.'));
								} else {
									console.log(chalk.red.bold('Failed! Error code: ' + code.toString()), 'Try Googling this reason code to find out more.');
								}
							}
						});
					} else {
						// Otherwise, things went great!
						// Print the commands that got us to this auspicious moment.
						// Add a `_` for the `when` value because that needs to be one single string for the cli arg reader
						console.log(chalk.cyan('Settings: ') + 'swoop deploy -e ' + bucket_environment + ' -m ' + trigger_type + ' -l ' + local_path + ' -r ' + remote_path + ' -w ' + when.replace(' ', '_'));
						console.log(chalk.green('Push successful!'));
					}
				});
			});

		} else {
			if (branch_status == 'uncommitted') throw chalk.red.bold('Error!') + chalk.yellow(' You have uncommitted changes on this branch.' + ' Please commit your changes before attempting to deploy.')
			if (branch_status == 'ahead_and_behind') throw chalk.red.bold('Error!') + chalk.yellow(' You have unpushed commits on this branch and your local branch is behind your remote.' + ' Please pull and then push your changes before attempting to deploy.')
			// EDIT: It's okay if they haven't push their commits. Like the edit above to the scrub push, removing this step will result in fewer pushes for the server to respond to. This alert is currently not being triggered because the branch status no longer as a condition where it is set to ahead.
			// if (branch_status == 'ahead') throw chalk.red.bold('Error!') + ' You have unpushed commits on this branch.' + ' Please push your changes before attempting to deploy.'.yellow;
			if (branch_status == 'behind') throw chalk.red.bold('Error!') + chalk.yellow(' Your local branch is behind your remote.' + ' Please pull, merge and push before attempting to deploy.')
		}
	});
}

/*    C R E A T E  A R C H I V E  B R A N C H   */
function addToArchive(deploySettings){
	var local_branch = deploySettings.local_branch;
	var remote_branch = deploySettings.remote_branch;

  setConfig(true);
  var repo_name = path.basename(path.resolve('.'));
  var archive_push = sh_commands.archive(config.github.login_method, config.github.account_name, config.archive.repo_name, local_branch, remote_branch);

	console.log(chalk.bgBlue.black('Pushing to GitHub...'));
	child.spawn( archive_push[0], archive_push[1], {stdio: 'inherit'} )
	  .on('close', function(code){
	  	if (code != 0){
				console.log(chalk.red.bold('Archive failed.', 'Error code: ' + chalk.bold( code.toString()) ));
				if (code == 128){
					console.log(chalk.yellow('Reason:') + chalk.bold('Your internet connection appears down'));
				}
	  	} else {
	  		console.log(chalk.green('Success!') + ' `' + local_branch + '` branch of `' + repo_name + '` archived as `' + remote_branch + '` on the `' + config.archive.repo_name + '` repo.\n  https://github.com/' + config.github.account_name + '/' + config.archive.repo_name + '/tree/' + remote_branch + '\n' + chalk.cyan('Note:') + ' Your existing repo has not been deleted. Please do that manually through GitHub:\n  https://github.com/' + config.github.account_name + '/' + repo_name + '/settings')
	  	}
	  })
}

function reportError(err, msg){
	console.log(msg, '\nReason:');
	throw err;
}

module.exports = {
	setConfig: setConfig,
	config: configClient,
	init: initAll,
	deploy: deployLastCommit,
	archive: addToArchive,
	unschedule: deployLastCommit
}
<|endoftext|>


<commit_before>var jsPixelateCanvas = require('./pixelate.js');
var headroom = require('./headroom.min.js');

//PIXELATE ON SCROLL CODE

$(document).ready(function() {
	var imgPixelate = $('#js-pixelate-scroll');

	if (imgPixelate.length > 0) {

		var ctx = jsPixelateCanvas.getContext('2d'),
		    img = new Image;
		    //value = factor.value;

		img.onload = function() {
			pixelate(0);
		};

		var imgPixelateId = imgPixelate.attr('src');
		img.src = imgPixelateId;

		function pixelate(value) {

			if (value === 0) {
				value = 1;
			}
		    /// calculate the factor
		    var fw = (img.width / value)|0,
		        fh = (img.height / value)|0;

		    /// turn off image smoothing (prefixed in some browsers)
		    ctx.imageSmoothingEnabled =
		    ctx.mozImageSmoothingEnabled =
		    ctx.msImageSmoothingEnabled =
		    ctx.webkitImageSmoothingEnabled = false;

		    /// draw mini-version of image
		    ctx.drawImage(img, 0, 0, fw, fh);

		    /// draw the mini-version back up, voila, pixelated
		    ctx.drawImage(jsPixelateCanvas, 0, 0, fw, fh, 0, 0, img.width, img.height);
		}

	(function () {
	    var previousScroll = 0;

	    $(window).scroll(function(){
	       var currentScroll = $(this).scrollTop();
	       if (currentScroll > previousScroll){
				$('#js-panel-fullwidth .panel-fullwidth-content').addClass('panel-fullwidth-img-text');
	       } else {
					$('#js-panel-fullwidth .panel-fullwidth-content').removeClass('panel-fullwidth-img-text');
	       }
	       previousScroll = currentScroll;
	    });
	}());

	$(document).scroll(function() {
		var scrollTop = $(window).scrollTop();
		if (scrollTop > 450) {
			return;
		}
		var pixelateValue = parseInt(scrollTop / 12);
		pixelate(pixelateValue);

	});
	}
});

$(document).ready(function(){
    //menu: off canvas
    $('.nav-menu-trigger').click(function(event){
        event.stopPropagation();
        $(this).toggleClass('nav-menu-triggered');
        $('.nav-menu').toggleClass('nav-menu-open');
        $('main').toggleClass('main-offcanvas');
    });

    $(window).click(function(){
    	$('.nav-menu-trigger').removeClass('nav-menu-triggered');
        $('.nav-menu').removeClass('nav-menu-open');
        $('main').removeClass('main-offcanvas');
    });

    //menu: current link styling
	  function stripTrailingSlash(str) {
	    if(str.substr(-1) == '/') {
	      return str.substr(0, str.length - 1);
	    }
	    return str;
	  }

	  var url = window.location.pathname;
	  var activePage = stripTrailingSlash(url);

	  $('.nav-menu a').each(function(){
	    var currentPage = stripTrailingSlash($(this).attr('href'));

	    if (activePage == currentPage) {
	      $(this).addClass('nav-active');
	    }
	  });

    //red pixel cube at end of blog post
    $(".blog-post-info").children().last().addClass('icon-decorative-pixel');

    //header: sticky
    $(".nav").headroom({
	  	"offset": 100,
	  	"tolerance": 5,
	  	"classes": {
	    	"initial": "animated",
	    	"pinned": "slideDown",
	    	"unpinned": "slideUp"
	  	}
	});

    //thumbnails which pixelate on hover
	$('.img-pixelate-hover').load(function(){
		$(this).pixelate({
			value : 0.7
		});
	});

	//customize twitter feed
	hideTwitterBoxElements();

});

/*!
 * headroom.js v0.7.0 - Give your page some headroom. Hide your header until you need it
 * Copyright (c) 2014 Nick Williams - http://wicky.nillia.ms/headroom.js
 * License: MIT
 */

!function(a){a&&(a.fn.headroom=function(b){return this.each(function(){var c=a(this),d=c.data("headroom"),e="object"==typeof b&&b;e=a.extend(!0,{},Headroom.options,e),d||(d=new Headroom(this,e),d.init(),c.data("headroom",d)),"string"==typeof b&&d[b]()})},a("[data-headroom]").each(function(){var b=a(this);b.headroom(b.data())}))}(window.Zepto||window.jQuery);

//customize twitter feed
var hideTwitterAttempts = 0;
function hideTwitterBoxElements() {
		setTimeout( function() {
				if ( $('[id*=twitter]').length ) {
				$('[id*=twitter]').each( function(){
						var ibody = $(this).contents().find( 'body' );

						if ( ibody.find( '.timeline .stream .h-feed li.tweet' ).length ) {

						ibody.find( '.timeline .stream .h-feed li.tweet' ).css( 'padding-left', '68px' );

						ibody.find( '.header .avatar' ).css( 'left', '-67px' );

						ibody.find( '.timeline .stream .h-feed li.tweet .p-name' ).css( 'color', '#fff' );
						ibody.find( '.timeline .stream .h-feed li.tweet .p-name' ).css( 'font-family', 'Muli, Helvetica, sans-serif' );
						ibody.find( '.timeline .stream .h-feed li.tweet .p-name' ).css( 'font-size', '16px' );

						ibody.find( '.timeline .stream .h-feed li.tweet .e-entry-title' ).css( 'color', '#fff' );
						ibody.find( '.timeline .stream .h-feed li.tweet .e-entry-title' ).css( 'font-family', 'Muli, Helvetica, sans-serif' );
						ibody.find( '.timeline .stream .h-feed li.tweet .e-entry-title' ).css( 'font-size', '16px' );
						ibody.find( '.timeline .stream .h-feed li.tweet .e-entry-title' ).css( 'line-height', '1.6' );
						ibody.find( '.timeline .stream .h-feed li.tweet .e-entry-title' ).css( 'margin-top', '10px' );

						ibody.find( '.timeline .stream .h-feed li.tweet .p-nickname' ).css( 'display', 'none' );
						}
						else {
								$(this).hide();
						}
				});
				}
				hideTwitterAttempts++;
				if ( hideTwitterAttempts < 3 ) {
						hideTwitterBoxElements();
				}
		}, 1500);
}
<commit_msg>fixed wrong var name inside main.js<commit_after>var jsPixelateHover = require('./pixelate.js');
var headroom = require('./headroom.min.js');

//PIXELATE ON SCROLL CODE

$(document).ready(function() {
	var imgPixelate = $('#js-pixelate-scroll');

	if (imgPixelate.length > 0) {

		var ctx = jsPixelateCanvas.getContext('2d'),
		    img = new Image;
		    //value = factor.value;

		img.onload = function() {
			pixelate(0);
		};

		var imgPixelateId = imgPixelate.attr('src');
		img.src = imgPixelateId;

		function pixelate(value) {

			if (value === 0) {
				value = 1;
			}
		    /// calculate the factor
		    var fw = (img.width / value)|0,
		        fh = (img.height / value)|0;

		    /// turn off image smoothing (prefixed in some browsers)
		    ctx.imageSmoothingEnabled =
		    ctx.mozImageSmoothingEnabled =
		    ctx.msImageSmoothingEnabled =
		    ctx.webkitImageSmoothingEnabled = false;

		    /// draw mini-version of image
		    ctx.drawImage(img, 0, 0, fw, fh);

		    /// draw the mini-version back up, voila, pixelated
		    ctx.drawImage(jsPixelateCanvas, 0, 0, fw, fh, 0, 0, img.width, img.height);
		}

	(function () {
	    var previousScroll = 0;

	    $(window).scroll(function(){
	       var currentScroll = $(this).scrollTop();
	       if (currentScroll > previousScroll){
				$('#js-panel-fullwidth .panel-fullwidth-content').addClass('panel-fullwidth-img-text');
	       } else {
					$('#js-panel-fullwidth .panel-fullwidth-content').removeClass('panel-fullwidth-img-text');
	       }
	       previousScroll = currentScroll;
	    });
	}());

	$(document).scroll(function() {
		var scrollTop = $(window).scrollTop();
		if (scrollTop > 450) {
			return;
		}
		var pixelateValue = parseInt(scrollTop / 12);
		pixelate(pixelateValue);

	});
	}
});

$(document).ready(function(){
    //menu: off canvas
    $('.nav-menu-trigger').click(function(event){
        event.stopPropagation();
        $(this).toggleClass('nav-menu-triggered');
        $('.nav-menu').toggleClass('nav-menu-open');
        $('main').toggleClass('main-offcanvas');
    });

    $(window).click(function(){
    	$('.nav-menu-trigger').removeClass('nav-menu-triggered');
        $('.nav-menu').removeClass('nav-menu-open');
        $('main').removeClass('main-offcanvas');
    });

    //menu: current link styling
	  function stripTrailingSlash(str) {
	    if(str.substr(-1) == '/') {
	      return str.substr(0, str.length - 1);
	    }
	    return str;
	  }

	  var url = window.location.pathname;
	  var activePage = stripTrailingSlash(url);

	  $('.nav-menu a').each(function(){
	    var currentPage = stripTrailingSlash($(this).attr('href'));

	    if (activePage == currentPage) {
	      $(this).addClass('nav-active');
	    }
	  });

    //red pixel cube at end of blog post
    $(".blog-post-info").children().last().addClass('icon-decorative-pixel');

    //header: sticky
    $(".nav").headroom({
	  	"offset": 100,
	  	"tolerance": 5,
	  	"classes": {
	    	"initial": "animated",
	    	"pinned": "slideDown",
	    	"unpinned": "slideUp"
	  	}
	});

    //thumbnails which pixelate on hover
	$('.img-pixelate-hover').load(function(){
		$(this).pixelate({
			value : 0.7
		});
	});

	//customize twitter feed
	hideTwitterBoxElements();

});

/*!
 * headroom.js v0.7.0 - Give your page some headroom. Hide your header until you need it
 * Copyright (c) 2014 Nick Williams - http://wicky.nillia.ms/headroom.js
 * License: MIT
 */

!function(a){a&&(a.fn.headroom=function(b){return this.each(function(){var c=a(this),d=c.data("headroom"),e="object"==typeof b&&b;e=a.extend(!0,{},Headroom.options,e),d||(d=new Headroom(this,e),d.init(),c.data("headroom",d)),"string"==typeof b&&d[b]()})},a("[data-headroom]").each(function(){var b=a(this);b.headroom(b.data())}))}(window.Zepto||window.jQuery);

//customize twitter feed
var hideTwitterAttempts = 0;
function hideTwitterBoxElements() {
		setTimeout( function() {
				if ( $('[id*=twitter]').length ) {
				$('[id*=twitter]').each( function(){
						var ibody = $(this).contents().find( 'body' );

						if ( ibody.find( '.timeline .stream .h-feed li.tweet' ).length ) {

						ibody.find( '.timeline .stream .h-feed li.tweet' ).css( 'padding-left', '68px' );

						ibody.find( '.header .avatar' ).css( 'left', '-67px' );

						ibody.find( '.timeline .stream .h-feed li.tweet .p-name' ).css( 'color', '#fff' );
						ibody.find( '.timeline .stream .h-feed li.tweet .p-name' ).css( 'font-family', 'Muli, Helvetica, sans-serif' );
						ibody.find( '.timeline .stream .h-feed li.tweet .p-name' ).css( 'font-size', '16px' );

						ibody.find( '.timeline .stream .h-feed li.tweet .e-entry-title' ).css( 'color', '#fff' );
						ibody.find( '.timeline .stream .h-feed li.tweet .e-entry-title' ).css( 'font-family', 'Muli, Helvetica, sans-serif' );
						ibody.find( '.timeline .stream .h-feed li.tweet .e-entry-title' ).css( 'font-size', '16px' );
						ibody.find( '.timeline .stream .h-feed li.tweet .e-entry-title' ).css( 'line-height', '1.6' );
						ibody.find( '.timeline .stream .h-feed li.tweet .e-entry-title' ).css( 'margin-top', '10px' );

						ibody.find( '.timeline .stream .h-feed li.tweet .p-nickname' ).css( 'display', 'none' );
						}
						else {
								$(this).hide();
						}
				});
				}
				hideTwitterAttempts++;
				if ( hideTwitterAttempts < 3 ) {
						hideTwitterBoxElements();
				}
		}, 1500);
}
<|endoftext|>


<commit_before>"use strict";

var mapbox = L.tileLayer('https://{s}.tiles.mapbox.com/v3/dennisl.4e2aab76/{z}/{x}/{y}.png');
var osm = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors'
    });

var map = L.map('map', {layers: [osm, mapbox]}).setView([51.505, -0.09], 8);

var baseMaps = {
  'OSM' : osm,
  'Mapbox': mapbox,
};

L.control.layers(baseMaps).addTo(map);

L.Routing.control({
    geocoder: L.Control.Geocoder.nominatim()
}).addTo(map);

<commit_msg>Enable routing while dragging<commit_after>"use strict";

var mapbox = L.tileLayer('https://{s}.tiles.mapbox.com/v3/dennisl.4e2aab76/{z}/{x}/{y}.png');
var osm = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors'
    });

var map = L.map('map', {layers: [osm, mapbox]}).setView([51.505, -0.09], 8);

var baseMaps = {
  'OSM' : osm,
  'Mapbox': mapbox,
};

L.control.layers(baseMaps).addTo(map);

L.Routing.control({
    geocoder: L.Control.Geocoder.nominatim(),
    routeWhileDragging: true
}).addTo(map);

<|endoftext|>