<commit_before>
<commit_msg>Update grayscale.js<commit_after>/*!
 * Start Bootstrap - Grayscale Bootstrap Theme (http://startbootstrap.com)
 * Code licensed under the Apache License v2.0.
 * For details, see http://www.apache.org/licenses/LICENSE-2.0.
 */

// jQuery to collapse the navbar on scroll
function collapseNavbar() {
    if ($(".navbar").offset().top > 50) {
        $(".navbar-fixed-top").addClass("top-nav-collapse");
    } else {
        $(".navbar-fixed-top").removeClass("top-nav-collapse");
    }
}

$(window).scroll(collapseNavbar);
$(document).ready(collapseNavbar);

// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
    $('a.page-scroll').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 1500, 'easeInOutExpo');
        event.preventDefault();
    });
});

// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
    $(this).closest('.collapse').collapse('toggle');
});

// Google Maps Scripts
var map = null;
// When the window has finished loading create our google map below
google.maps.event.addDomListener(window, 'load', init);
google.maps.event.addDomListener(window, 'resize', function() {
    map.setCenter(new google.maps.LatLng(40.6700, -73.9400));
});

function init() {
    // Basic options for a simple Google Map
    // For more options see: https://developers.google.com/maps/documentation/javascript/reference#MapOptions
    var mapOptions = {
        // How zoomed in you want the map to start at (always required)
        zoom: 15,

        // The latitude and longitude to center the map (always required)
        center: new google.maps.LatLng(40.6700, -73.9400), // New York

        // Disables the default Google Maps UI components
        disableDefaultUI: true,
        scrollwheel: false,
        draggable: false,

        // How you would like to style the map.
        // This is where you would paste any style found on Snazzy Maps.
        styles: [{
            "featureType": "water",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 17
            }]
        }, {
            "featureType": "landscape",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 20
            }]
        }, {
            "featureType": "road.highway",
            "elementType": "geometry.fill",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 17
            }]
        }, {
            "featureType": "road.highway",
            "elementType": "geometry.stroke",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 29
            }, {
                "weight": 0.2
            }]
        }, {
            "featureType": "road.arterial",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 18
            }]
        }, {
            "featureType": "road.local",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 16
            }]
        }, {
            "featureType": "poi",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 21
            }]
        }, {
            "elementType": "labels.text.stroke",
            "stylers": [{
                "visibility": "on"
            }, {
                "color": "#000000"
            }, {
                "lightness": 16
            }]
        }, {
            "elementType": "labels.text.fill",
            "stylers": [{
                "saturation": 36
            }, {
                "color": "#000000"
            }, {
                "lightness": 40
            }]
        }, {
            "elementType": "labels.icon",
            "stylers": [{
                "visibility": "off"
            }]
        }, {
            "featureType": "transit",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 19
            }]
        }, {
            "featureType": "administrative",
            "elementType": "geometry.fill",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 20
            }]
        }, {
            "featureType": "administrative",
            "elementType": "geometry.stroke",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 17
            }, {
                "weight": 1.2
            }]
        }]
    };

    // Get the HTML DOM element that will contain your map
    // We are using a div with id="map" seen below in the <body>
    var mapElement = document.getElementById('map');

    // Create the Google Map using out element and options defined above
    map = new google.maps.Map(mapElement, mapOptions);

    // Custom Map Marker Icon - Customize the map-marker.png file to customize your icon
    var image = 'img/map-marker.png';
    var myLatLng = new google.maps.LatLng(40.6700, -73.9400);
    var beachMarker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        icon: image
    });
}

<|endoftext|>


<commit_before>/**
 * JSaw - JavaScript Audio Workstation
 * Copyright (c) 2011 Nicholas Kircher
 * JSaw may be freely distributed under the MIT license.

 Everything in JSaw is split up into its component parts, and then connected together.
 Each pattern has a collection of tracks, each track is basically a synth which is attached
 to a piano roll.  Piano rolls are collections of step grids which are collections of notes.

 */

// Hackery!  Witchery!  Nonsense and bullshit!
function construct(constructor, args) {
	function F(constructor) {
		return constructor.apply(this, args);
	}
	F.prototype = constructor.prototype;
	return new F(constructor);
}

/**
 * JSAW core
 */

// Static Class
var JSAW = {
	audiolet: false
};

/**
 * Note object: represents a note in a pattern.
 *
 * @constructor
 * @param {Object} options Configuration options for the constructor.
 */
JSAW.Note = function(options) {
	this.instance = true; // This is the instance of Note!

	this.options = {
		id: false,
		key: "C",
		octave: 3,
		velocity: 1.0,
		duration: 1, // Number of steps
		position: 0 // Step position
	}
	_(this.options).extend(options);

	this.id = this.options.id;
};
/**** METHODS ****/

JSAW.Note.prototype.getKey = function(){return this.options.key;};
JSAW.Note.prototype.getOctave = function(){return this.options.octave;};
JSAW.Note.prototype.getVelocity = function(){return this.options.velocity;};
JSAW.Note.prototype.getDuration = function(){return this.options.duration;};
JSAW.Note.prototype.getPosition = function(){return this.options.position;};
JSAW.Note.prototype.getFullName = function(){return this.options.key+this.options.octave;};
JSAW.Note.prototype.getFrequency = function(){return Note.fromLatin(this.getFullName()).frequency();};
JSAW.Note.prototype.hashify = function(){
	var outhash = {}
	_(outhash).extend(this.options);
	outhash.frequency = this.getFrequency();
	outhash.fullName = this.getFullName();
	outhash.velocity = this.getVelocity();
	outhash.instance = false;
	return outhash;
};

JSAW.Note.prototype.set = function(params){
	params.id = this.id;	// Prevent changes to ID parameter
	_(this.options).extend(params);
};

/**
 * Pattern object: represents a sequence of notes to be played.
 *
 * @constructor
 * @param {Object} options Configuration options for the constructor.
 */
JSAW.Pattern = function(options) {
	this._notes = {}; // Associative array of all note objects in this pattern.
	this._steps = []; // Step array.
	this._noteIncrement = 1; // Counter.

	this.options = {
		id: false,
		name: "New Pattern",
		beats: 4,
		stepsPerBeat: 4,
		pattern: [],
		track: false
	}
	_(this.options).extend(options);

	this.id = this.options.id = (this.options.id) ? this.options.id : this.generateID();
	this.track = this.options.track;

	if (!this.track) {
		console.warn("Uh oh, pattern is not assigned to a track object!");
	}

	if (this.options.pattern.length > 0) {
		this.renderPattern(this.options.pattern);
	}
	else {
		for (var x = 0; x < this.options.beats; x++) {
			for (var i = 0; i < this.options.stepsPerBeat; i++) {
				this._steps.push([]);
			}
		}
	}

};

/**** METHODS ****/

/**
 * Generate a unique numeric ID and increment the internal counter + 1.
 *
 * @return {Number} The generated numeric ID.
 */
JSAW.Pattern.prototype.generateID = function() {
	//this.self._increment.pattern += 1;
	//return ++this.self._increment.pattern;
};

/**
 * Get a note object by ID.
 */
JSAW.Pattern.prototype.getNote = function(id) {
	return _(_.keys(this._notes)).contains(id) ? this._notes[id] : false;
};

/**
 * Create a new note and add it to the collection.
 */
JSAW.Pattern.prototype.addNote = function(options) {
	options.id = options.id || ++this._noteIncrement;
	this._notes[options.id] = new JSAW.Note(options);
	this._steps[options.position].push(this._notes[options.id]);

	return this._notes[options.id];
};

JSAW.Pattern.prototype.renderPattern = function(newPattern) {
	var outPattern = [];
	_(newPattern).forEach(function(step){
		var newStep = [];
		if (step.length > 0) {
			_(step).forEach(function(noteData){
				newStep.push(this.addNote(noteData));
			}, this)
		}
		outPattern.push(newStep);
	}, this);
	return outPattern;
};

JSAW.Pattern.prototype.startPlayback = function() {
	var self = this;
	var sequence = new PSequence([this._steps], 1);
	this.track.instrument.al.scheduler.play(
		[sequence],
		1,
		function(step) {
			if (step.length > 0) {
				_(step).forEach(function(note){
					self.track.instrument.voices.create(note);
				});
			}
		}
	);
}

/**
 * Track objects
 */
JSAW.Track = function(options) {
	//this.self = self;
	this._patterns = [];

	// What instrument am I?
	this.instrument = {};
};

JSAW.Track.prototype.generateID = function() {
	//this.self._increment.track += 1;
	//return ++this.self._increment.track;
};

/**
 * Instrument object
 *
 * @constructor
 * @param {Object} options Configuration parameters for the instrument instance
 */
JSAW.Instrument = function(options) {
	// Derp
	this.options = {
		id: false,
		name: "New Instrument",
		type: "synth",
		generator: Synth,
		muted: false,
		volume: 0.8,
		pan: 0.5,
		effects: []
	}
	_(this.options).extend(options);

	console.group("Instrument  ("+this.options.type+"): '"+this.options.name+"'");

	this.al = this.options.al;
	this.generatorClass = this.options.generator;
	this.effects = this.options.effects;

	if (this.options.type === "sampler") {
		this.samplerParams = options.samplerParams;
		this.samplerParams.audiolet = this.al;
		this.generator = construct(this.generatorClass, [this.samplerParams]);
		this.generator.connect(this.al.output);
	}

	var _self = this;

	console.debug("this.options:");
	console.dir(this.options);

	this.voices = {
		self: _self,
		list: [],

		// Create method
		create: function(data) {
			console.group("Voice create");
			console.info("Type: "+this.self.options.type);

			if (_.isUndefined(data) || _.isNull(data)) {
				console.error("Cannot create voice: data argument is null or undefined.");
				console.groupEnd();
				return false;
			}

			if (_.isArray(data)) {
				_(data).forEach(function(value){
					this.voices.create(value);
				}, this.self);

				console.groupEnd();
				return;
			}

			var noteData = (data.instance) ? data.hashify() : data;

			// Synth type
			if (this.self.options.type == "synth") {
				noteData.audiolet = this.self.al;
				noteData.velocity = noteData.velocity * this.self.options.volume;

				console.debug(noteData);

				var voiceObj = construct(this.self.generatorClass, [noteData]);
				var voiceFX = [];

				voiceObj.vel.gain.setValue(noteData.velocity);

				if (this.self.effects.length > 0) {
					for (var i = 0; i < this.self.effects.length; i++) {
						voiceFX.push(construct(this.self.effects[i], [{audiolet: this.self.al}]));
					}
					for (var i = 0; i < voiceFX.length; i++) {
						if (i < 1) {
							voiceObj.connect(voiceFX[i]);
							if (voiceFX.length === 1) voiceFX[i].connect(this.self.al.output);
						}
						else if (i < voiceFX.length-1) {
							voiceFX[i].connect(voiceFX[i+1]);
						}
						else {
							voiceFX[i].connect(this.self.al.output);
						}
					}
				}
				else {
					voiceObj.connect(this.self.al.output);
				}

				this.list.push(voiceObj);

				console.debug("Voice created");
			}

			// Sampler type
			else if (this.self.options.type == "sampler") {
				this.self.generator.gain.gain.setValue(noteData.velocity);
				this.self.generator.triggerSample.trigger.setValue(1);

				console.debug("Sample triggered");
			}

			console.groupEnd();
		} // end Create method

	}; // end Voices

	console.groupEnd();
}; // end Instrument

JSAW.Global = function() {
	this._sequenceCount = 1;
	this._instrumentCount = 1;
};

JSAW.Global.prototype.getNewSequenceID = function(){
	this._sequenceCount += 1;
	return this._sequenceCount;
};
JSAW.Global.prototype.getNewTrackID = function(){
	this._instrumentCount += 1;
	return this._instrumentCount;
};

// Static stuff and class definitions
JSAW.Project = function(config) {
	this.title = config.title || "Ode To JSaw";
	this.artist = config.artist || "Someone";
	this.bpm = config.bpm || 120.0;

}

JSAW.Sequence = function(config) {
	this.id = config.id || JSAW.Global.sequenceCount+1
	this.name = config.name || "Sequence #"+this.id;
}

/**
 * Begin initialising application logic here!
 */
window.onload = function() {
	//jsaw.status = new JSAW.Model.Status();

	JSAW.audiolet = new Audiolet();

};
<commit_msg>Adding myself to the copyright notice :D<commit_after>/**
 * JSaw - JavaScript Audio Workstation
 * Copyright (c) 2011 Nicholas Kircher, Aaron 'Spanky Tanks' Danks
 * JSaw may be freely distributed under the MIT license.

 Everything in JSaw is split up into its component parts, and then connected together.
 Each pattern has a collection of tracks, each track is basically a synth which is attached
 to a piano roll.  Piano rolls are collections of step grids which are collections of notes.

 */

// Hackery!  Witchery!  Nonsense and bullshit!
function construct(constructor, args) {
	function F(constructor) {
		return constructor.apply(this, args);
	}
	F.prototype = constructor.prototype;
	return new F(constructor);
}

/**
 * JSAW core
 */

// Static Class
var JSAW = {
	audiolet: false
};

/**
 * Note object: represents a note in a pattern.
 *
 * @constructor
 * @param {Object} options Configuration options for the constructor.
 */
JSAW.Note = function(options) {
	this.instance = true; // This is the instance of Note!

	this.options = {
		id: false,
		key: "C",
		octave: 3,
		velocity: 1.0,
		duration: 1, // Number of steps
		position: 0 // Step position
	}
	_(this.options).extend(options);

	this.id = this.options.id;
};
/**** METHODS ****/

JSAW.Note.prototype.getKey = function(){return this.options.key;};
JSAW.Note.prototype.getOctave = function(){return this.options.octave;};
JSAW.Note.prototype.getVelocity = function(){return this.options.velocity;};
JSAW.Note.prototype.getDuration = function(){return this.options.duration;};
JSAW.Note.prototype.getPosition = function(){return this.options.position;};
JSAW.Note.prototype.getFullName = function(){return this.options.key+this.options.octave;};
JSAW.Note.prototype.getFrequency = function(){return Note.fromLatin(this.getFullName()).frequency();};
JSAW.Note.prototype.hashify = function(){
	var outhash = {}
	_(outhash).extend(this.options);
	outhash.frequency = this.getFrequency();
	outhash.fullName = this.getFullName();
	outhash.velocity = this.getVelocity();
	outhash.instance = false;
	return outhash;
};

JSAW.Note.prototype.set = function(params){
	params.id = this.id;	// Prevent changes to ID parameter
	_(this.options).extend(params);
};

/**
 * Pattern object: represents a sequence of notes to be played.
 *
 * @constructor
 * @param {Object} options Configuration options for the constructor.
 */
JSAW.Pattern = function(options) {
	this._notes = {}; // Associative array of all note objects in this pattern.
	this._steps = []; // Step array.
	this._noteIncrement = 1; // Counter.

	this.options = {
		id: false,
		name: "New Pattern",
		beats: 4,
		stepsPerBeat: 4,
		pattern: [],
		track: false
	}
	_(this.options).extend(options);

	this.id = this.options.id = (this.options.id) ? this.options.id : this.generateID();
	this.track = this.options.track;

	if (!this.track) {
		console.warn("Uh oh, pattern is not assigned to a track object!");
	}

	if (this.options.pattern.length > 0) {
		this.renderPattern(this.options.pattern);
	}
	else {
		for (var x = 0; x < this.options.beats; x++) {
			for (var i = 0; i < this.options.stepsPerBeat; i++) {
				this._steps.push([]);
			}
		}
	}

};

/**** METHODS ****/

/**
 * Generate a unique numeric ID and increment the internal counter + 1.
 *
 * @return {Number} The generated numeric ID.
 */
JSAW.Pattern.prototype.generateID = function() {
	//this.self._increment.pattern += 1;
	//return ++this.self._increment.pattern;
};

/**
 * Get a note object by ID.
 */
JSAW.Pattern.prototype.getNote = function(id) {
	return _(_.keys(this._notes)).contains(id) ? this._notes[id] : false;
};

/**
 * Create a new note and add it to the collection.
 */
JSAW.Pattern.prototype.addNote = function(options) {
	options.id = options.id || ++this._noteIncrement;
	this._notes[options.id] = new JSAW.Note(options);
	this._steps[options.position].push(this._notes[options.id]);

	return this._notes[options.id];
};

JSAW.Pattern.prototype.renderPattern = function(newPattern) {
	var outPattern = [];
	_(newPattern).forEach(function(step){
		var newStep = [];
		if (step.length > 0) {
			_(step).forEach(function(noteData){
				newStep.push(this.addNote(noteData));
			}, this)
		}
		outPattern.push(newStep);
	}, this);
	return outPattern;
};

JSAW.Pattern.prototype.startPlayback = function() {
	var self = this;
	var sequence = new PSequence([this._steps], 1);
	this.track.instrument.al.scheduler.play(
		[sequence],
		1,
		function(step) {
			if (step.length > 0) {
				_(step).forEach(function(note){
					self.track.instrument.voices.create(note);
				});
			}
		}
	);
}

/**
 * Track objects
 */
JSAW.Track = function(options) {
	//this.self = self;
	this._patterns = [];

	// What instrument am I?
	this.instrument = {};
};

JSAW.Track.prototype.generateID = function() {
	//this.self._increment.track += 1;
	//return ++this.self._increment.track;
};

/**
 * Instrument object
 *
 * @constructor
 * @param {Object} options Configuration parameters for the instrument instance
 */
JSAW.Instrument = function(options) {
	// Derp
	this.options = {
		id: false,
		name: "New Instrument",
		type: "synth",
		generator: Synth,
		muted: false,
		volume: 0.8,
		pan: 0.5,
		effects: []
	}
	_(this.options).extend(options);

	console.group("Instrument  ("+this.options.type+"): '"+this.options.name+"'");

	this.al = this.options.al;
	this.generatorClass = this.options.generator;
	this.effects = this.options.effects;

	if (this.options.type === "sampler") {
		this.samplerParams = options.samplerParams;
		this.samplerParams.audiolet = this.al;
		this.generator = construct(this.generatorClass, [this.samplerParams]);
		this.generator.connect(this.al.output);
	}

	var _self = this;

	console.debug("this.options:");
	console.dir(this.options);

	this.voices = {
		self: _self,
		list: [],

		// Create method
		create: function(data) {
			console.group("Voice create");
			console.info("Type: "+this.self.options.type);

			if (_.isUndefined(data) || _.isNull(data)) {
				console.error("Cannot create voice: data argument is null or undefined.");
				console.groupEnd();
				return false;
			}

			if (_.isArray(data)) {
				_(data).forEach(function(value){
					this.voices.create(value);
				}, this.self);

				console.groupEnd();
				return;
			}

			var noteData = (data.instance) ? data.hashify() : data;

			// Synth type
			if (this.self.options.type == "synth") {
				noteData.audiolet = this.self.al;
				noteData.velocity = noteData.velocity * this.self.options.volume;

				console.debug(noteData);

				var voiceObj = construct(this.self.generatorClass, [noteData]);
				var voiceFX = [];

				voiceObj.vel.gain.setValue(noteData.velocity);

				if (this.self.effects.length > 0) {
					for (var i = 0; i < this.self.effects.length; i++) {
						voiceFX.push(construct(this.self.effects[i], [{audiolet: this.self.al}]));
					}
					for (var i = 0; i < voiceFX.length; i++) {
						if (i < 1) {
							voiceObj.connect(voiceFX[i]);
							if (voiceFX.length === 1) voiceFX[i].connect(this.self.al.output);
						}
						else if (i < voiceFX.length-1) {
							voiceFX[i].connect(voiceFX[i+1]);
						}
						else {
							voiceFX[i].connect(this.self.al.output);
						}
					}
				}
				else {
					voiceObj.connect(this.self.al.output);
				}

				this.list.push(voiceObj);

				console.debug("Voice created");
			}

			// Sampler type
			else if (this.self.options.type == "sampler") {
				this.self.generator.gain.gain.setValue(noteData.velocity);
				this.self.generator.triggerSample.trigger.setValue(1);

				console.debug("Sample triggered");
			}

			console.groupEnd();
		} // end Create method

	}; // end Voices

	console.groupEnd();
}; // end Instrument

JSAW.Global = function() {
	this._sequenceCount = 1;
	this._instrumentCount = 1;
};

JSAW.Global.prototype.getNewSequenceID = function(){
	this._sequenceCount += 1;
	return this._sequenceCount;
};
JSAW.Global.prototype.getNewTrackID = function(){
	this._instrumentCount += 1;
	return this._instrumentCount;
};

// Static stuff and class definitions
JSAW.Project = function(config) {
	this.title = config.title || "Ode To JSaw";
	this.artist = config.artist || "Someone";
	this.bpm = config.bpm || 120.0;

}

JSAW.Sequence = function(config) {
	this.id = config.id || JSAW.Global.sequenceCount+1
	this.name = config.name || "Sequence #"+this.id;
}

/**
 * Begin initialising application logic here!
 */
window.onload = function() {
	//jsaw.status = new JSAW.Model.Status();

	JSAW.audiolet = new Audiolet();

};
<|endoftext|>


<commit_before>describe('Binding: radio', function () {
    this.prepareTestElement('
'
        + '<input type="radio" name="options" value="A" />A'
        + '<input type="radio" name="options" value="B" />B'
        + '<input type="radio" name="options" value="X"" />X"'
        + '
');

    it('Should throw exception for non-observable value', function() {
        var el = this.testElement[0];

        expect(function () {
            ko.applyBindings({ value: "A" }, el);
        }).toThrow();
    });

    it('Should not check any button, if init value is not specified', function() {
        var vm = { value: ko.observable() };

        ko.applyBindings(vm, this.testElement[0]);

        expect(this.testElement.children()).not.toHaveClass('active');
        expect(this.testElement.find('input')).not.toBeChecked();
    });

    it('Should check button corresponding to the init value', function () {
        var vm = { value: ko.observable('A') };

        ko.applyBindings(vm, this.testElement[0]);

        expect(this.testElement.find('.active input:checked')).toHaveValue('A');
    });

    it('Should check button according to value changes', function () {
        var vm = { value: ko.observable('A') };

        ko.applyBindings(vm, this.testElement[0]);

        expect(this.testElement.find('.active input:checked')).toHaveValue('A');
        vm.value('B');
        expect(this.testElement.find('.active input:checked')).toHaveValue('B');
        vm.value('A');
        expect(this.testElement.find('.active input:checked')).toHaveValue('A');
        vm.value('X"');
        expect(this.testElement.find('.active input:checked')).toHaveValue('X"');
    });

    it('Should change value according to clicked button', function () {
        var vm = { value: ko.observable() };
        //need because of realization of binding
        jasmine.clock().install();

        ko.applyBindings(vm, this.testElement[0]);

        this.testElement.children().eq(0).click();
        jasmine.clock().tick(1);
        expect(vm.value()).toEqual('A');

        this.testElement.children().eq(1).click();
        jasmine.clock().tick(1);
        expect(vm.value()).toEqual('B');

        jasmine.clock().uninstall();
    });

    it('Should uncheck all buttons, if no button has set value', function () {
        var vm = { value: ko.observable('A') };

        ko.applyBindings(vm, this.testElement[0]);

        vm.value('Z');

        expect(this.testElement.children()).not.toHaveClass('active');
        expect(this.testElement.find('input')).not.toBeChecked();
    });

    it('Should change value according to clicked button for dynamically added radiobuttons', function () {
        var vm = { value: ko.observable() };

        this.testElement.append('<input type="radio" name="options" value="C" />C');

        //need because of realization of binding
        jasmine.clock().install();

        ko.applyBindings(vm, this.testElement[0]);

        this.testElement.children().eq(3).click();
        jasmine.clock().tick(1);
        expect(vm.value()).toEqual('C');

        jasmine.clock().uninstall();
    });

    it('Should check dynamically added button according to value changes', function () {
        var vm = { value: ko.observable() };

        this.testElement.append('<input type="radio" name="options" value="C" />C');

        ko.applyBindings(vm, this.testElement[0]);
        vm.value('C');
        expect(this.testElement.find('.active input:checked')).toHaveValue('C');
    });
});<commit_msg>Updated tests for radio binding to include case with number value<commit_after>describe('Binding: radio', function () {
    this.prepareTestElement('
'
        + '<input type="radio" name="options" value="A" />A'
        + '<input type="radio" name="options" value="B" />B'
        + '<input type="radio" name="options" value="X"" />X"'
        + '<input type="radio" name="options" value="1" />1'
        + '
');

    it('Should throw exception for non-observable value', function() {
        var el = this.testElement[0];

        expect(function () {
            ko.applyBindings({ value: "A" }, el);
        }).toThrow();
    });

    it('Should not check any button, if init value is not specified', function() {
        var vm = { value: ko.observable() };

        ko.applyBindings(vm, this.testElement[0]);

        expect(this.testElement.children()).not.toHaveClass('active');
        expect(this.testElement.find('input')).not.toBeChecked();
    });

    it('Should check button corresponding to the init value', function () {
        var vm = { value: ko.observable('A') };

        ko.applyBindings(vm, this.testElement[0]);

        expect(this.testElement.find('.active input:checked')).toHaveValue('A');
    });

    it('Should check button according to value changes', function () {
        var vm = { value: ko.observable('A') };

        ko.applyBindings(vm, this.testElement[0]);

        expect(this.testElement.find('.active input:checked')).toHaveValue('A');
        vm.value('B');
        expect(this.testElement.find('.active input:checked')).toHaveValue('B');
        vm.value('A');
        expect(this.testElement.find('.active input:checked')).toHaveValue('A');
        vm.value('X"');
        expect(this.testElement.find('.active input:checked')).toHaveValue('X"');
        vm.value(1);
        expect(this.testElement.find('.active input:checked')).toHaveValue('1');
    });

    it('Should change value according to clicked button', function () {
        var vm = { value: ko.observable() };
        //need because of realization of binding
        jasmine.clock().install();

        ko.applyBindings(vm, this.testElement[0]);

        this.testElement.children().eq(0).click();
        jasmine.clock().tick(1);
        expect(vm.value()).toEqual('A');

        this.testElement.children().eq(1).click();
        jasmine.clock().tick(1);
        expect(vm.value()).toEqual('B');

        jasmine.clock().uninstall();
    });

    it('Should uncheck all buttons, if no button has set value', function () {
        var vm = { value: ko.observable('A') };

        ko.applyBindings(vm, this.testElement[0]);

        vm.value('Z');

        expect(this.testElement.children()).not.toHaveClass('active');
        expect(this.testElement.find('input')).not.toBeChecked();
    });

    it('Should change value according to clicked button for dynamically added radiobuttons', function () {
        var vm = { value: ko.observable() };

        this.testElement.append('<input type="radio" name="options" value="C" />C');

        //need because of realization of binding
        jasmine.clock().install();

        ko.applyBindings(vm, this.testElement[0]);

        this.testElement.children().last().click();
        jasmine.clock().tick(1);
        expect(vm.value()).toEqual('C');

        jasmine.clock().uninstall();
    });

    it('Should check dynamically added button according to value changes', function () {
        var vm = { value: ko.observable() };

        this.testElement.append('<input type="radio" name="options" value="C" />C');

        ko.applyBindings(vm, this.testElement[0]);
        vm.value('C');
        expect(this.testElement.find('.active input:checked')).toHaveValue('C');
    });
});<|endoftext|>


<commit_before>//Draw the karyotype
jviz.modules.ideogram.prototype.karyotypeDraw = function()
{
  //Show loading
  this.loading(true);

  //Clear the karyotype zone
  this.karyotypeClear();

  //Get the canvas draw zone
  var draw = this._karyotype.draw;

  //Calculate the margin
  this._karyotype.margin = (draw.width - this._genome.length * this._karyotype.chromosome.width) / (this._genome.length - 1);

  //Get the middle layer
  var canvas = this._canvas.el.layer(this._karyotype.draw.layer);

  //Clear the canvas
  canvas.Clear();

  //Reset the karyotypes positions
  this._karyotype.positions = [];

  //Draw all the karyotypes
  for(var i = 0; i < this._genome.chromosomes.length; i++)
  {
    //Get the chromosome
    var chr = this._genome.chromosomes[i];

    //Get the mark for this chromosome
    //var marks = this.GetMarks(ch.id).length;
    var marks = 0;

    //Get the chromosome width
    var chr_width = this._karyotype.chromosome.width;

    //Get the chromosome height
    var chr_height = draw.height * (chr.length / this._karyotype.max);

    //Get the chromosome position x
    var chr_x = draw.margin.left + (i + 0) * this._karyotype.margin + i * this._karyotype.chromosome.width;

    //Get the chromosome position y
    var chr_y = draw.margin.top + draw.height - chr_height;

    //Get the chromosome radius
    var chr_radius = this._karyotype.chromosome.radius;

    //Draw the chromosome
    canvas.Rect({ x: chr_x, y: chr_y, width: chr_width, height: chr_height, radius: chr_radius });

    //Set the chromsome fill color
    canvas.Fill({ color: this._fill.chromosome.color, opacity: this._fill.chromosome.opacity });

    //Save the position
    this._karyotype.positions.push({ x: chr_x, y: chr_y, width: chr_width, height: chr_height });

    //Check for draw the centromere
    if(typeof chr.centromere !== 'undefined')
    {
      //Centromere width
      var cent_width = this._karyotype.chromosome.width;

      //Centromere start
      var cent_start = draw.height * (chr.centromere[0] / this._karyotype.max);

      //Centromere end
      var cent_end = draw.height * (chr.centromere[1] / this._karyotype.max);

      //Centromere height
      var cent_height = Math.abs(cent_end - cent_start);

      //Centromere position x
      var cent_x = chr_x;

      //Centromere position y
      var cent_y = draw.margin.top + draw.height - chr_height + cent_start;

      //Clear the centromere region
      canvas.Clear({ x: cent_x, y: cent_y, width: cent_width, height: cent_height });

      //Centromere points
      var cent = [];

      //Add the top point
      cent.push([cent_x, cent_y]);

      //Add the middle point
      cent.push([cent_x + cent_width / 2, cent_y + cent_height / 2]);

      //Add the end point
      cent.push([cent_x, cent_y + cent_height]);

      //Add the end right
      cent.push([cent_x + cent_width, cent_y + cent_height]);

      //Add the middle right
      cent.push([cent_x + cent_width / 2, cent_y + cent_height / 2]);

      //Add the top right
      cent.push([cent_x + cent_width, cent_y]);

      //Draw the lines
      canvas.Line(cent);

      //Add the fill color
      canvas.Fill({ color: this._fill.centromere.color, opacity: this._fill.centromere.opacity });
    }

    //Get the chromosome name
    var text_txt = chr.name;

    //Get the text position x
    var text_x = chr_x + this._karyotype.chromosome.width / 2;

    //Get the text position y
    var text_y = draw.margin.top + draw.height + this._karyotype.text.margin;

    //Get the text color
    var text_color = this._karyotype.text.color;

    //Get the text size
    var text_size = this._karyotype.text.size;

    //Get the text font
    var text_font = this._karyotype.text.font;

    //Get the text align
    var text_align = this._karyotype.text.align;

    //Draw the chromosome title
    canvas.Text({ x: text_x, y: text_y, text: text_txt, color: text_color, size: text_size, font: text_font, align: text_align });

    //Get the regions for this chromosome
    var regions = (typeof this._regions.list[chr.name] === 'undefined') ? [] : this._regions.list[chr.name];

    //Read all the regions
    for(var j = 0; j < regions.length; j++)
    {
      //Get the region
      var re = regions[j];

      //Region start
      var re_start = draw.height * (re.start / this._karyotype.max);

      //Region end
      var re_end = draw.height * (re.end / this._karyotype.max);

      //Region width
      var re_width = this._karyotype.chromosome.width;

      //Region height
      var re_height = Math.max(Math.abs(re_end - re_start), 1);

      //Region position x
      var re_x = chr_x;

      //Region position y
      var re_y = draw.margin.top + draw.height - chr_height + re_start;

      //Draw the region
      canvas.Rect({ x: re_x, y: re_y, width: re_width, height: re_height });

      //Region fill
      canvas.Fill({ color: this._chromosome.regions.fill, opacity: this._chromosome.regions.opacity });
    }

    //Check the number of marks
    if(marks === 0){ continue; }

    //Get the mark rectangle position x
    var mark_x = chr_x + this._karyotype.width / 2 - this._marks.karyotypes.width / 2;

    //Get the mark rectange position y
    var mark_y = chr_y - this._marks.karyotypes.margin;

    //Get the mark rectange radius
    var mark_radius = this._marks.karyotypes.radius;

    //Get the mark width
    var mark_width = this._marks.karyotypes.width;

    //Get the mark rectangle height
    var mark_height = this._marks.karyotypes.height;

    //Draw the rectangle
    canvas.Rect({ x: mark_x, y: mark_y, width: mark_width, height: mark_height, radius: mark_radius });

    //Set the rectangle color
    canvas.Fill({ color: this._marks.fill });

    //Update the text position x
    this._marks.text.x = posx + this._karyotype.chromosome.width / 2;

    //Update the text position y
    this._marks.text.y = mark_y + this._marks.karyotypes.text;

    //Update the text
    this._marks.text.text = marks.toString();

    //Draw the text
    canvas.Text(this._marks.text);

    //Update the mark position x
    mark_x = posx + this._karyotype.width / 2;

    //Update the mark position y
    mark_y = mark_y + this._marks.karyotypes.height - this._marks.karyotypes.triangle;

    //Initialize the triangle array
    var tri = [];

    //Add the first point
    tri.push([ mark_x - this._marks.triangle, mark_y ]);

    //Add the middle point
    tri.push([ mark_x, mark_y + this._marks.triangle ]);

    //Add the first point
    tri.push([ mark_x + this._marks.triangle, mark_y ]);

    //Add the line
    canvas.Line(tri);

    //Add the fill color
    canvas.Fill(this._marks.fill);
  }

  //Reset the karyotypes hover
  this._karyotype.hover.index = -1;

  //Set loading as false
  this.loading(false);

  //Add the foot info
  this.foot(this._foot.default);
};

//Get the chromosome
jviz.modules.ideogram.prototype.karyotypeFindChromosome = function(x, y)
{
  //Get the actual draw
  var draw = this._karyotype.draw;

  //Check for click on the margin left
  if(x < draw.margin.left + 0 * this._karyotype.margin){ return -1; }

  //Check for click on the margin right
  if(draw.margin.left + draw.width - 0 * this._karyotype.margin < x){return -1; }

  //Check for click on the margin top
  if(y < draw.margin.top){ return -1; }

  //Check for click on the margin bottom
  if(draw.margin.top + draw.height < y){ return -1; }

  //Read all the chromosomes positions
  for(var i = 0; i < this._karyotype.positions.length; i++)
  {
    //Get the position
    var pos = this._karyotype.positions[i];

    //Check the left position x
    if(x < pos.x){ return -1; }

    //Check the right position x
    if(pos.x + pos.width < x){ continue; }

    //Return the chromosome index
    return i;
  }

  //Default, return -1
  return -1;
};

//Clicked on a chromosome
jviz.modules.ideogram.prototype.karyotypeClick = function(x, y)
{
  //Get the chromosome index
  var index = this.karyotypeFindChromosome(x, y);

  //Check for undefined chromosome
  if(index === -1){ return; }

  //Get the chromosome info
  var chr = this._genome.chromosomes[index];

  //Emit the event
  var result = this._events.emit('click:chromosome', chr.name, index);

  //Check for undefined result
  if(result === false){ return; }

  //Open this chromosome
  this.chromosome(index);
};

//Draw the karyotypes hover
jviz.modules.ideogram.prototype.karyotypeMove = function(x, y)
{
  //Get the hover chromosome
  var index = this.karyotypeFindChromosome(x, y);

  //Check the index
  if(index === this._karyotype.hover.index){ return; }

  //Update the index
  this._karyotype.hover.index = index;

  //Get the canvas
  var canvas = this._canvas.el.layer(1);

  //Clear the canvas
  canvas.Clear();

  //Check for no chromosome
  if(index === -1)
  {
    //Reset the foot content
    this.foot(this._foot.default);

    //Remove the pointer cursor
    jviz.cursor.remove('pointer');

    //Exit
    return;
  }

  //Get the chromosome position
  var chr = this._karyotype.positions[index];

  //Calculate the hover position x
  var rect_x = chr.x - this._karyotype.hover.margin.left;

  //Calculate the hover position y
  var rect_y = chr.y - this._karyotype.hover.margin.top;

  //Calculate the hover width
  var rect_width = chr.width + this._karyotype.hover.margin.left + this._karyotype.hover.margin.right;

  //Calculate the hover height
  var rect_height = chr.height + this._karyotype.hover.margin.top + this._karyotype.hover.margin.bottom;

  //Get the hover radius
  var rect_radius = this._karyotype.hover.radius;

  //Draw
  canvas.Rect({ x: rect_x, y: rect_y, width: rect_width, height: rect_height, radius: rect_radius });

  //Set the fill color
  canvas.Fill({ color: this._karyotype.hover.color, opacity: this._karyotype.hover.opacity });

  //Get the chromosome name
  var chr_name = this._genome.chromosomes[index].name;

  //Get the regions on chromosome
  var chr_regions = (typeof this._regions.list[chr_name] !== 'undefined') ? this._regions.list[chr_name].length : 0;

  //Update the foot content
  this.foot(this._foot.chromosome.replace('{chromosome}', chr_name).replace('{regions}', chr_regions));

  //Add the pointer cursor
  jviz.cursor.set('pointer');
};

//Preview mouse leave
jviz.modules.ideogram.prototype.karyotypeLeave = function()
{
  //Update the index
  this._karyotype.hover.index = -1;

  //Clear the canvas layer
  this._canvas.el.layer(1).Clear();
};

//Clear the karyotype
jviz.modules.ideogram.prototype.karyotypeClear = function()
{
  //Get the draw zone
  var draw = this._karyotype.draw;

  //Read all layers
  for(var i = 0; i < this._canvas.layers; i++)
  {
    //Get the layer
    var canvas = this._canvas.el.layer(i);

    //Clear a rectangle
    canvas.Clear({ x: 0, y: draw.top, width: draw.real_width, height: draw.real_height });
  }

  //Continue
  return this;
};
<commit_msg>js/karyotype.js: remove foot functions<commit_after>//Draw the karyotype
jviz.modules.ideogram.prototype.karyotypeDraw = function()
{
  //Show loading
  this.loading(true);

  //Clear the karyotype zone
  this.karyotypeClear();

  //Get the canvas draw zone
  var draw = this._karyotype.draw;

  //Calculate the margin
  this._karyotype.margin = (draw.width - this._genome.length * this._karyotype.chromosome.width) / (this._genome.length - 1);

  //Get the middle layer
  var canvas = this._canvas.el.layer(this._karyotype.draw.layer);

  //Clear the canvas
  canvas.Clear();

  //Reset the karyotypes positions
  this._karyotype.positions = [];

  //Draw all the karyotypes
  for(var i = 0; i < this._genome.chromosomes.length; i++)
  {
    //Get the chromosome
    var chr = this._genome.chromosomes[i];

    //Get the mark for this chromosome
    //var marks = this.GetMarks(ch.id).length;
    var marks = 0;

    //Get the chromosome width
    var chr_width = this._karyotype.chromosome.width;

    //Get the chromosome height
    var chr_height = draw.height * (chr.length / this._karyotype.max);

    //Get the chromosome position x
    var chr_x = draw.margin.left + (i + 0) * this._karyotype.margin + i * this._karyotype.chromosome.width;

    //Get the chromosome position y
    var chr_y = draw.margin.top + draw.height - chr_height;

    //Get the chromosome radius
    var chr_radius = this._karyotype.chromosome.radius;

    //Draw the chromosome
    canvas.Rect({ x: chr_x, y: chr_y, width: chr_width, height: chr_height, radius: chr_radius });

    //Set the chromsome fill color
    canvas.Fill({ color: this._fill.chromosome.color, opacity: this._fill.chromosome.opacity });

    //Save the position
    this._karyotype.positions.push({ x: chr_x, y: chr_y, width: chr_width, height: chr_height });

    //Check for draw the centromere
    if(typeof chr.centromere !== 'undefined')
    {
      //Centromere width
      var cent_width = this._karyotype.chromosome.width;

      //Centromere start
      var cent_start = draw.height * (chr.centromere[0] / this._karyotype.max);

      //Centromere end
      var cent_end = draw.height * (chr.centromere[1] / this._karyotype.max);

      //Centromere height
      var cent_height = Math.abs(cent_end - cent_start);

      //Centromere position x
      var cent_x = chr_x;

      //Centromere position y
      var cent_y = draw.margin.top + draw.height - chr_height + cent_start;

      //Clear the centromere region
      canvas.Clear({ x: cent_x, y: cent_y, width: cent_width, height: cent_height });

      //Centromere points
      var cent = [];

      //Add the top point
      cent.push([cent_x, cent_y]);

      //Add the middle point
      cent.push([cent_x + cent_width / 2, cent_y + cent_height / 2]);

      //Add the end point
      cent.push([cent_x, cent_y + cent_height]);

      //Add the end right
      cent.push([cent_x + cent_width, cent_y + cent_height]);

      //Add the middle right
      cent.push([cent_x + cent_width / 2, cent_y + cent_height / 2]);

      //Add the top right
      cent.push([cent_x + cent_width, cent_y]);

      //Draw the lines
      canvas.Line(cent);

      //Add the fill color
      canvas.Fill({ color: this._fill.centromere.color, opacity: this._fill.centromere.opacity });
    }

    //Get the chromosome name
    var text_txt = chr.name;

    //Get the text position x
    var text_x = chr_x + this._karyotype.chromosome.width / 2;

    //Get the text position y
    var text_y = draw.margin.top + draw.height + this._karyotype.text.margin;

    //Get the text color
    var text_color = this._karyotype.text.color;

    //Get the text size
    var text_size = this._karyotype.text.size;

    //Get the text font
    var text_font = this._karyotype.text.font;

    //Get the text align
    var text_align = this._karyotype.text.align;

    //Draw the chromosome title
    canvas.Text({ x: text_x, y: text_y, text: text_txt, color: text_color, size: text_size, font: text_font, align: text_align });

    //Get the regions for this chromosome
    var regions = (typeof this._regions.list[chr.name] === 'undefined') ? [] : this._regions.list[chr.name];

    //Read all the regions
    for(var j = 0; j < regions.length; j++)
    {
      //Get the region
      var re = regions[j];

      //Region start
      var re_start = draw.height * (re.start / this._karyotype.max);

      //Region end
      var re_end = draw.height * (re.end / this._karyotype.max);

      //Region width
      var re_width = this._karyotype.chromosome.width;

      //Region height
      var re_height = Math.max(Math.abs(re_end - re_start), 1);

      //Region position x
      var re_x = chr_x;

      //Region position y
      var re_y = draw.margin.top + draw.height - chr_height + re_start;

      //Draw the region
      canvas.Rect({ x: re_x, y: re_y, width: re_width, height: re_height });

      //Region fill
      canvas.Fill({ color: this._chromosome.regions.fill, opacity: this._chromosome.regions.opacity });
    }

    //Check the number of marks
    if(marks === 0){ continue; }

    //Get the mark rectangle position x
    var mark_x = chr_x + this._karyotype.width / 2 - this._marks.karyotypes.width / 2;

    //Get the mark rectange position y
    var mark_y = chr_y - this._marks.karyotypes.margin;

    //Get the mark rectange radius
    var mark_radius = this._marks.karyotypes.radius;

    //Get the mark width
    var mark_width = this._marks.karyotypes.width;

    //Get the mark rectangle height
    var mark_height = this._marks.karyotypes.height;

    //Draw the rectangle
    canvas.Rect({ x: mark_x, y: mark_y, width: mark_width, height: mark_height, radius: mark_radius });

    //Set the rectangle color
    canvas.Fill({ color: this._marks.fill });

    //Update the text position x
    this._marks.text.x = posx + this._karyotype.chromosome.width / 2;

    //Update the text position y
    this._marks.text.y = mark_y + this._marks.karyotypes.text;

    //Update the text
    this._marks.text.text = marks.toString();

    //Draw the text
    canvas.Text(this._marks.text);

    //Update the mark position x
    mark_x = posx + this._karyotype.width / 2;

    //Update the mark position y
    mark_y = mark_y + this._marks.karyotypes.height - this._marks.karyotypes.triangle;

    //Initialize the triangle array
    var tri = [];

    //Add the first point
    tri.push([ mark_x - this._marks.triangle, mark_y ]);

    //Add the middle point
    tri.push([ mark_x, mark_y + this._marks.triangle ]);

    //Add the first point
    tri.push([ mark_x + this._marks.triangle, mark_y ]);

    //Add the line
    canvas.Line(tri);

    //Add the fill color
    canvas.Fill(this._marks.fill);
  }

  //Reset the karyotypes hover
  this._karyotype.hover.index = -1;

  //Set loading as false
  this.loading(false);

  //Add the foot info
  this.foot(this._foot.default);
};

//Get the chromosome
jviz.modules.ideogram.prototype.karyotypeFindChromosome = function(x, y)
{
  //Get the actual draw
  var draw = this._karyotype.draw;

  //Check for click on the margin left
  if(x < draw.margin.left + 0 * this._karyotype.margin){ return -1; }

  //Check for click on the margin right
  if(draw.margin.left + draw.width - 0 * this._karyotype.margin < x){return -1; }

  //Check for click on the margin top
  if(y < draw.margin.top){ return -1; }

  //Check for click on the margin bottom
  if(draw.margin.top + draw.height < y){ return -1; }

  //Read all the chromosomes positions
  for(var i = 0; i < this._karyotype.positions.length; i++)
  {
    //Get the position
    var pos = this._karyotype.positions[i];

    //Check the left position x
    if(x < pos.x){ return -1; }

    //Check the right position x
    if(pos.x + pos.width < x){ continue; }

    //Return the chromosome index
    return i;
  }

  //Default, return -1
  return -1;
};

//Clicked on a chromosome
jviz.modules.ideogram.prototype.karyotypeClick = function(x, y)
{
  //Get the chromosome index
  var index = this.karyotypeFindChromosome(x, y);

  //Check for undefined chromosome
  if(index === -1){ return; }

  //Get the chromosome info
  var chr = this._genome.chromosomes[index];

  //Emit the event
  var result = this._events.emit('click:chromosome', chr.name, index);

  //Check for undefined result
  if(result === false){ return; }

  //Open this chromosome
  this.chromosome(index);
};

//Draw the karyotypes hover
jviz.modules.ideogram.prototype.karyotypeMove = function(x, y)
{
  //Get the hover chromosome
  var index = this.karyotypeFindChromosome(x, y);

  //Check the index
  if(index === this._karyotype.hover.index){ return; }

  //Update the index
  this._karyotype.hover.index = index;

  //Get the canvas
  var canvas = this._canvas.el.layer(1);

  //Clear the canvas
  canvas.Clear();

  //Check for no chromosome
  if(index === -1)
  {
    //Reset the foot content
    //this.foot(this._foot.default);

    //Remove the pointer cursor
    jviz.cursor.remove('pointer');

    //Exit
    return;
  }

  //Get the chromosome position
  var chr = this._karyotype.positions[index];

  //Calculate the hover position x
  var rect_x = chr.x - this._karyotype.hover.margin.left;

  //Calculate the hover position y
  var rect_y = chr.y - this._karyotype.hover.margin.top;

  //Calculate the hover width
  var rect_width = chr.width + this._karyotype.hover.margin.left + this._karyotype.hover.margin.right;

  //Calculate the hover height
  var rect_height = chr.height + this._karyotype.hover.margin.top + this._karyotype.hover.margin.bottom;

  //Get the hover radius
  var rect_radius = this._karyotype.hover.radius;

  //Draw
  canvas.Rect({ x: rect_x, y: rect_y, width: rect_width, height: rect_height, radius: rect_radius });

  //Set the fill color
  canvas.Fill({ color: this._karyotype.hover.color, opacity: this._karyotype.hover.opacity });

  //Get the chromosome name
  var chr_name = this._genome.chromosomes[index].name;

  //Get the regions on chromosome
  var chr_regions = (typeof this._regions.list[chr_name] !== 'undefined') ? this._regions.list[chr_name].length : 0;

  //Update the foot content
  //this.foot(this._foot.chromosome.replace('{chromosome}', chr_name).replace('{regions}', chr_regions));

  //Add the pointer cursor
  jviz.cursor.set('pointer');
};

//Preview mouse leave
jviz.modules.ideogram.prototype.karyotypeLeave = function()
{
  //Update the index
  this._karyotype.hover.index = -1;

  //Clear the canvas layer
  this._canvas.el.layer(1).Clear();
};

//Draw an empty karyotype
jviz.modules.ideogram.prototype.karyotypeEmpty = function()
{
  //Clear the karyotype view
  this.karyotypeClear();

  //Exit
  return this;
};

//Clear the karyotype
jviz.modules.ideogram.prototype.karyotypeClear = function()
{
  //Get the draw zone
  var draw = this._karyotype.draw;

  //Read all layers
  for(var i = 0; i < this._canvas.layers; i++)
  {
    //Get the layer
    var canvas = this._canvas.el.layer(i);

    //Clear a rectangle
    canvas.Clear({ x: 0, y: draw.top, width: draw.real_width, height: draw.real_height });
  }

  //Continue
  return this;
};
<|endoftext|>


<commit_before>(function() {
  document.body.style.margin = "0";

  var PATH_TO_VIDEO = "https://www.youtube.com/v/MAtCSio876c?version=3&autoplay=1&loop=1&playlist=MAtCSio876c";

  var allElements = document.querySelectorAll("body *");
  for (var i = 0; i < allElements.length; i++) {
    var element = allElements[i];
    setTimeout(function(element) {
      element.classList.add("animated");
      element.classList.add("infinite");
      element.classList.add("swing");
      element.style.WebkitAnimationDuration = "5s";
      element.style.animationDuration = "5s";
    }.bind(null, element), Math.random()*1000);
  }

  (function playVideo() {
    var video = document.createElement("iframe");
    video.setAttribute("class", "left-shark-video");
    (function moveVideo() {
      var x = ~~((window.innerWidth - 400)*Math.random());
      var y = ~~((window.innerHeight - 400)*Math.random());
      var scale = Math.random();
      video.style.transform = "translateX(" + x + "px) translateY(" + y + "px) scale(" + scale + ")";
      setTimeout(moveVideo, 4000);
    }());
    video.src = PATH_TO_VIDEO;
    video.height = 400;
    video.width = 400;
    video.autoplay = true;
    document.body.appendChild(video);
  }());

  function injectShark() {
    var img = document.createElement("img");
    img.setAttribute("class", "left-shark-gif");
    img.src = "http://i.imgur.com/c9AnBzU.gif";
    (function moveShark() {
      var x = ~~((window.innerWidth)*Math.random());
      var y = ~~((window.innerHeight)*Math.random());
      var z = -~~(Math.random()*500);
      img.style.transform = "translateX(" + x + "px) translateY(" + y + "px) translateZ(" + z + "px)";
      img.style.WebkitAnimationDuration = "5s";
      img.style.animationDuration = "5s";
      setTimeout(moveShark, 4000);
    }());
    document.body.appendChild(img);
  }

  var i = 10;
  while (i--) {
    setTimeout(injectShark, i*100);
  }

  (function injectWave() {
    var img = document.createElement("img");
    img.setAttribute("class", "waves");
    img.src = "http://www.skylinesup.com/assets/images/_bgs/xbg_waves.png.pagespeed.ic.pGjXSUvPiA.png";
    document.body.appendChild(img);
  }());

  (function injectFin() {
    var img = document.createElement("img");
    img.setAttribute("class", "fin");
    img.src = "http://images.clipartpanda.com/fin-clipart-blue-fin.svg";
    document.body.appendChild(img);
    var x = 0;
    requestAnimationFrame(function loop() {
      if (x > window.innerWidth) x = 0;
      img.style.transform = "translateX(-" + (x++) + "px)";
      requestAnimationFrame(loop);
    });
  }());

  (function injectPalm() {
    var img = document.createElement("img");
    img.setAttribute("class", "palm");
    img.src = "http://www.dzzyn.com/wp-content/uploads/2015/01/20-Free-Tree-PNG-Images-jamaicanroyalpalm01L.png";
    document.body.appendChild(img);
    img.onload = function() {
      setTimeout(function() {
        img.style.transform = "translateY(0)";
      }, 10);
    };
  }());

  return true;
})();
<commit_msg>fix broken youtube autoplay video so the left shark can continue to rock out with katy<commit_after>(function() {
  document.body.style.margin = "0";

  var PATH_TO_VIDEO = "https://www.youtube.com/embed/WmcWZ2Bzoho?autoplay=1&loop=1";

  var allElements = document.querySelectorAll("body *");
  for (var i = 0; i < allElements.length; i++) {
    var element = allElements[i];
    setTimeout(function(element) {
      element.classList.add("animated");
      element.classList.add("infinite");
      element.classList.add("swing");
      element.style.WebkitAnimationDuration = "5s";
      element.style.animationDuration = "5s";
    }.bind(null, element), Math.random()*1000);
  }

  (function playVideo() {
    var video = document.createElement("iframe");
    video.setAttribute("class", "left-shark-video");
    (function moveVideo() {
      var x = ~~((window.innerWidth - 400)*Math.random());
      var y = ~~((window.innerHeight - 400)*Math.random());
      var scale = Math.random();
      video.style.transform = "translateX(" + x + "px) translateY(" + y + "px) scale(" + scale + ")";
      setTimeout(moveVideo, 4000);
    }());
    video.src = PATH_TO_VIDEO;
    video.height = 400;
    video.width = 400;
    video.autoplay = true;
    document.body.appendChild(video);
  }());

  function injectShark() {
    var img = document.createElement("img");
    img.setAttribute("class", "left-shark-gif");
    img.src = "http://i.imgur.com/c9AnBzU.gif";
    (function moveShark() {
      var x = ~~((window.innerWidth)*Math.random());
      var y = ~~((window.innerHeight)*Math.random());
      var z = -~~(Math.random()*500);
      img.style.transform = "translateX(" + x + "px) translateY(" + y + "px) translateZ(" + z + "px)";
      img.style.WebkitAnimationDuration = "5s";
      img.style.animationDuration = "5s";
      setTimeout(moveShark, 4000);
    }());
    document.body.appendChild(img);
  }

  var i = 10;
  while (i--) {
    setTimeout(injectShark, i*100);
  }

  (function injectWave() {
    var img = document.createElement("img");
    img.setAttribute("class", "waves");
    img.src = "http://www.skylinesup.com/assets/images/_bgs/xbg_waves.png.pagespeed.ic.pGjXSUvPiA.png";
    document.body.appendChild(img);
  }());

  (function injectFin() {
    var img = document.createElement("img");
    img.setAttribute("class", "fin");
    img.src = "http://images.clipartpanda.com/fin-clipart-blue-fin.svg";
    document.body.appendChild(img);
    var x = 0;
    requestAnimationFrame(function loop() {
      if (x > window.innerWidth) x = 0;
      img.style.transform = "translateX(-" + (x++) + "px)";
      requestAnimationFrame(loop);
    });
  }());

  (function injectPalm() {
    var img = document.createElement("img");
    img.setAttribute("class", "palm");
    img.src = "http://www.dzzyn.com/wp-content/uploads/2015/01/20-Free-Tree-PNG-Images-jamaicanroyalpalm01L.png";
    document.body.appendChild(img);
    img.onload = function() {
      setTimeout(function() {
        img.style.transform = "translateY(0)";
      }, 10);
    };
  }());

  return true;
})();
<|endoftext|>


<commit_before>var Sprite = require('./sprite');
if (typeof navigator !== 'undefined') {
	navigator.vibrate = navigator.vibrate ||
		navigator.webkitVibrate ||
		navigator.mozVibrate ||
		navigator.msVibrate;
} else {
	navigator = {
		vibrate: false
	};
}

(function(global) {
	function Skier(data) {
		var discreteDirections = {
			'west': 270,
			'wsWest': 240,
			'sWest': 195,
			'south': 180,
			'sEast': 165,
			'esEast': 120,
			'east': 90
		};
		var that = new Sprite(data);
		var sup = {
			draw: that.superior('draw'),
			cycle: that.superior('cycle'),
			getSpeedX: that.superior('getSpeedX'),
			getSpeedY: that.superior('getSpeedY'),
			hits: that.superior('hits')
		};
		var directions = {
			esEast: function(xDiff) { return xDiff > 300; },
			sEast: function(xDiff) { return xDiff > 75; },
			wsWest: function(xDiff) { return xDiff < -300; },
			sWest: function(xDiff) { return xDiff < -75; }
		};

		var cancelableStateTimeout;
		var cancelableStateInterval;

		var canSpeedBoost = true;

		var obstaclesHit = [];
		var pixelsTravelled = 0;
		var standardSpeed = 5;
		var turnEaseCycles = 70;
		var speedX = 0;
		var speedXFactor = 0;
		var speedY = 0;
		var speedYFactor = 1;
		var trickStep = 0; // There are three of these

		that.isMoving = true;
		that.hasBeenHit = false;
		that.isJumping = false;
		that.isPerformingTrick = false;
		that.setSpeed(standardSpeed);

		that.reset = function () {
			obstaclesHit = [];
			pixelsTravelled = 0;
			that.isMoving = true;
			that.hasBeenHit = false;
			canSpeedBoost = true;
			setNormal();
		};

		function setNormal() {
			that.setSpeed(standardSpeed);
			that.isMoving = true;
			that.hasBeenHit = false;
			that.isJumping = false;
			that.isPerformingTrick = false;
			if (cancelableStateInterval) {
				clearInterval(cancelableStateInterval);
			}
			that.setMapPosition(undefined, undefined, 0);
		}

		function setCrashed() {
			that.isMoving = false;
			that.hasBeenHit = true;
			that.isJumping = false;
			that.isPerformingTrick = false;
			if (cancelableStateInterval) {
				clearInterval(cancelableStateInterval);
			}
			that.setMapPosition(undefined, undefined, 0);
		}

		function setJumping() {
			var currentSpeed = that.getSpeed();
			that.setSpeed(currentSpeed + 2);
			that.setSpeedY(currentSpeed + 2);
			that.isMoving = true;
			that.hasBeenHit = false;
			that.isJumping = true;
			that.setMapPosition(undefined, undefined, 1);
		}

		function getDiscreteDirection() {
			if (that.direction) {
				if (that.direction <= 90) {
					return 'east';
				} else if (that.direction > 90 && that.direction < 150) {
					return 'esEast';
				} else if (that.direction >= 150 && that.direction < 180) {
					return 'sEast';
				} else if (that.direction === 180) {
					return 'south';
				} else if (that.direction > 180 && that.direction <= 210) {
					return 'sWest';
				} else if (that.direction > 210 && that.direction < 270) {
					return 'wsWest';
				} else if (that.direction >= 270) {
					return 'west';
				} else {
					return 'south';
				}
			} else {
				var xDiff = that.movingToward[0] - that.mapPosition[0];
				var yDiff = that.movingToward[1] - that.mapPosition[1];
				if (yDiff <= 0) {
					if (xDiff > 0) {
						return 'east';
					} else {
						return 'west';
					}
				}

				if (directions.esEast(xDiff)) {
					return 'esEast';
				} else if (directions.sEast(xDiff)) {
					return 'sEast';
				} else if (directions.wsWest(xDiff)) {
					return 'wsWest';
				} else if (directions.sWest(xDiff)) {
					return 'sWest';
				}
			}
			return 'south';
		}

		function setDiscreteDirection(d) {
			if (discreteDirections[d]) {
				that.setDirection(discreteDirections[d]);
			}

			if (d === 'west' || d === 'east') {
				that.isMoving = false;
			} else {
				that.isMoving = true;
			}
		}

		function getBeingEatenSprite() {
			return 'blank';
		}

		function getJumpingSprite() {
			return 'jumping';
		}

		function getTrickSprite() {
			console.log('Trick step is', trickStep);
			if (trickStep === 0) {
				return 'jumping';
			} else if (trickStep === 1) {
				return 'somersault1';
			} else {
				return 'somersault2';
			}
		}

		that.stop = function () {
			if (that.direction > 180) {
				setDiscreteDirection('west');
			} else {
				setDiscreteDirection('east');
			}
		};

		that.turnEast = function () {
			var discreteDirection = getDiscreteDirection();

			switch (discreteDirection) {
				case 'west':
					setDiscreteDirection('wsWest');
					break;
				case 'wsWest':
					setDiscreteDirection('sWest');
					break;
				case 'sWest':
					setDiscreteDirection('south');
					break;
				case 'south':
					setDiscreteDirection('sEast');
					break;
				case 'sEast':
					setDiscreteDirection('esEast');
					break;
				case 'esEast':
					setDiscreteDirection('east');
					break;
				default:
					setDiscreteDirection('south');
					break;
			}
		};

		that.turnWest = function () {
			var discreteDirection = getDiscreteDirection();

			switch (discreteDirection) {
				case 'east':
					setDiscreteDirection('esEast');
					break;
				case 'esEast':
					setDiscreteDirection('sEast');
					break;
				case 'sEast':
					setDiscreteDirection('south');
					break;
				case 'south':
					setDiscreteDirection('sWest');
					break;
				case 'sWest':
					setDiscreteDirection('wsWest');
					break;
				case 'wsWest':
					setDiscreteDirection('west');
					break;
				default:
					setDiscreteDirection('south');
					break;
			}
		};

		that.stepWest = function () {
			that.mapPosition[0] -= that.speed * 2;
		};

		that.stepEast = function () {
			that.mapPosition[0] += that.speed * 2;
		};

		that.setMapPositionTarget = function (x, y) {
			if (that.hasBeenHit) return;

			if (Math.abs(that.mapPosition[0] - x) <= 75) {
				x = that.mapPosition[0];
			}

			that.movingToward = [ x, y ];

			// that.resetDirection();
		};

		that.startMovingIfPossible = function () {
			if (!that.hasBeenHit && !that.isBeingEaten) {
				that.isMoving = true;
			}
		};

		that.setTurnEaseCycles = function (c) {
			turnEaseCycles = c;
		};

		that.getPixelsTravelledDownMountain = function () {
			return pixelsTravelled;
		};

		that.resetSpeed = function () {
			that.setSpeed(standardSpeed);
		};

		that.cycle = function () {
			if (that.isMoving) {
				pixelsTravelled += that.speed;
			}

			if (that.isJumping) {
				that.setMapPositionTarget(undefined, that.mapPosition[1] + that.getSpeed());
			}

			sup.cycle();

			that.checkHittableObjects();
		};

		that.draw = function(dContext) {
			var spritePartToUse = function () {
				if (that.isBeingEaten) {
					return getBeingEatenSprite();
				}

				if (that.isJumping) {
					if (that.isPerformingTrick) {
						return getTrickSprite();
					}
					return getJumpingSprite();
				}

				if (that.hasBeenHit) {
					return 'hit';
				}

				return getDiscreteDirection();
			};

			return sup.draw(dContext, spritePartToUse());
		};

		that.hits = function (obs) {
			if (obstaclesHit.indexOf(obs.id) !== -1) {
				return false;
			}

			if (!obs.occupiesZIndex(that.mapPosition[2])) {
				return false;
			}

			if (sup.hits(obs)) {
				return true;
			}

			return false;
		};

		that.speedBoost = function () {
			var originalSpeed = that.speed;
			if (canSpeedBoost) {
				canSpeedBoost = false;
				that.setSpeed(that.speed * 2);
				setTimeout(function () {
					that.setSpeed(originalSpeed);
					setTimeout(function () {
						canSpeedBoost = true;
					}, 10000);
				}, 2000);
			}
		};

		that.attemptTrick = function () {
			if (that.isJumping) {
				that.isPerformingTrick = true;
				cancelableStateInterval = setInterval(function () {
					if (trickStep >= 2) {
						trickStep = 0;
					} else {
						trickStep += 1;
					}
				}, 300);
			}
		};

		function easeSpeedToTargetUsingFactor(sp, targetSpeed, f) {
			if (f === 0 || f === 1) {
				return targetSpeed;
			}

			if (sp < targetSpeed) {
				sp += that.getSpeed() * (f / turnEaseCycles);
			}

			if (sp > targetSpeed) {
				sp -= that.getSpeed() * (f / turnEaseCycles);
			}

			return sp;
		}

		that.getSpeedX = function () {
			if (getDiscreteDirection() === 'esEast' || getDiscreteDirection() === 'wsWest') {
				speedXFactor = 0.5;
				speedX = easeSpeedToTargetUsingFactor(speedX, that.getSpeed() * speedXFactor, speedXFactor);

				return speedX;
			}

			if (getDiscreteDirection() === 'sEast' || getDiscreteDirection() === 'sWest') {
				speedXFactor = 0.33;
				speedX = easeSpeedToTargetUsingFactor(speedX, that.getSpeed() * speedXFactor, speedXFactor);

				return speedX;
			}

			// So it must be south

			speedX = easeSpeedToTargetUsingFactor(speedX, 0, speedXFactor);

			return speedX;
		};

		that.setSpeedY = function(sy) {
			speedY = sy;
		};

		that.getSpeedY = function () {
			var targetSpeed;

			if (that.isJumping) {
				return speedY;
			}

			if (getDiscreteDirection() === 'esEast' || getDiscreteDirection() === 'wsWest') {
				speedYFactor = 0.6;
				speedY = easeSpeedToTargetUsingFactor(speedY, that.getSpeed() * 0.6, 0.6);

				return speedY;
			}

			if (getDiscreteDirection() === 'sEast' || getDiscreteDirection() === 'sWest') {
				speedYFactor = 0.85;
				speedY = easeSpeedToTargetUsingFactor(speedY, that.getSpeed() * 0.85, 0.85);

				return speedY;
			}

			if (getDiscreteDirection() === 'east' || getDiscreteDirection() === 'west') {
				speedYFactor = 1;
				speedY = 0;

				return speedY;
			}

			// So it must be south

			speedY = easeSpeedToTargetUsingFactor(speedY, that.getSpeed(), speedYFactor);

			return speedY;
		};

		that.hasHitObstacle = function (obs) {
			setCrashed();

			if (navigator.vibrate) {
				navigator.vibrate(500);
			}

			obstaclesHit.push(obs.id);

			that.resetSpeed();

			if (cancelableStateTimeout) {
				clearTimeout(cancelableStateTimeout);
			}
			cancelableStateTimeout = setTimeout(function() {
				setNormal();
			}, 1500);
		};

		that.hasHitJump = function () {
			setJumping();

			if (cancelableStateTimeout) {
				clearTimeout(cancelableStateTimeout);
			}
			cancelableStateTimeout = setTimeout(function() {
				setNormal();
			}, 1000);
		};

		that.isEatenBy = function (monster, whenEaten) {
			that.hasHitObstacle(monster);
			monster.startEating(whenEaten);
			obstaclesHit.push(monster.id);
			that.isMoving = false;
			that.isBeingEaten = true;
		};

		that.reset = function () {
			obstaclesHit = [];
			pixelsTravelled = 0;
			that.isMoving = true;
			that.isJumping = false;
			that.hasBeenHit = false;
			canSpeedBoost = true;
		};

		return that;
	}

	global.skier = Skier;
})(this);

if (typeof module !== 'undefined') {
	module.exports = this.skier;
}
<commit_msg>Fixed not being able to 'stand still' with mouse/touch<commit_after>var Sprite = require('./sprite');
if (typeof navigator !== 'undefined') {
	navigator.vibrate = navigator.vibrate ||
		navigator.webkitVibrate ||
		navigator.mozVibrate ||
		navigator.msVibrate;
} else {
	navigator = {
		vibrate: false
	};
}

(function(global) {
	function Skier(data) {
		var discreteDirections = {
			'west': 270,
			'wsWest': 240,
			'sWest': 195,
			'south': 180,
			'sEast': 165,
			'esEast': 120,
			'east': 90
		};
		var that = new Sprite(data);
		var sup = {
			draw: that.superior('draw'),
			cycle: that.superior('cycle'),
			getSpeedX: that.superior('getSpeedX'),
			getSpeedY: that.superior('getSpeedY'),
			hits: that.superior('hits')
		};
		var directions = {
			esEast: function(xDiff) { return xDiff > 300; },
			sEast: function(xDiff) { return xDiff > 75; },
			wsWest: function(xDiff) { return xDiff < -300; },
			sWest: function(xDiff) { return xDiff < -75; }
		};

		var cancelableStateTimeout;
		var cancelableStateInterval;

		var canSpeedBoost = true;

		var obstaclesHit = [];
		var pixelsTravelled = 0;
		var standardSpeed = 5;
		var turnEaseCycles = 70;
		var speedX = 0;
		var speedXFactor = 0;
		var speedY = 0;
		var speedYFactor = 1;
		var trickStep = 0; // There are three of these

		that.isMoving = true;
		that.hasBeenHit = false;
		that.isJumping = false;
		that.isPerformingTrick = false;
		that.setSpeed(standardSpeed);

		that.reset = function () {
			obstaclesHit = [];
			pixelsTravelled = 0;
			that.isMoving = true;
			that.hasBeenHit = false;
			canSpeedBoost = true;
			setNormal();
		};

		function setNormal() {
			that.setSpeed(standardSpeed);
			that.isMoving = true;
			that.hasBeenHit = false;
			that.isJumping = false;
			that.isPerformingTrick = false;
			if (cancelableStateInterval) {
				clearInterval(cancelableStateInterval);
			}
			that.setMapPosition(undefined, undefined, 0);
		}

		function setCrashed() {
			that.isMoving = false;
			that.hasBeenHit = true;
			that.isJumping = false;
			that.isPerformingTrick = false;
			if (cancelableStateInterval) {
				clearInterval(cancelableStateInterval);
			}
			that.setMapPosition(undefined, undefined, 0);
		}

		function setJumping() {
			var currentSpeed = that.getSpeed();
			that.setSpeed(currentSpeed + 2);
			that.setSpeedY(currentSpeed + 2);
			that.isMoving = true;
			that.hasBeenHit = false;
			that.isJumping = true;
			that.setMapPosition(undefined, undefined, 1);
		}

		function getDiscreteDirection() {
			if (that.direction) {
				if (that.direction <= 90) {
					return 'east';
				} else if (that.direction > 90 && that.direction < 150) {
					return 'esEast';
				} else if (that.direction >= 150 && that.direction < 180) {
					return 'sEast';
				} else if (that.direction === 180) {
					return 'south';
				} else if (that.direction > 180 && that.direction <= 210) {
					return 'sWest';
				} else if (that.direction > 210 && that.direction < 270) {
					return 'wsWest';
				} else if (that.direction >= 270) {
					return 'west';
				} else {
					return 'south';
				}
			} else {
				var xDiff = that.movingToward[0] - that.mapPosition[0];
				var yDiff = that.movingToward[1] - that.mapPosition[1];
				if (yDiff <= 0) {
					if (xDiff > 0) {
						return 'east';
					} else {
						return 'west';
					}
				}

				if (directions.esEast(xDiff)) {
					return 'esEast';
				} else if (directions.sEast(xDiff)) {
					return 'sEast';
				} else if (directions.wsWest(xDiff)) {
					return 'wsWest';
				} else if (directions.sWest(xDiff)) {
					return 'sWest';
				}
			}
			return 'south';
		}

		function setDiscreteDirection(d) {
			if (discreteDirections[d]) {
				that.setDirection(discreteDirections[d]);
			}

			if (d === 'west' || d === 'east') {
				that.isMoving = false;
			} else {
				that.isMoving = true;
			}
		}

		function getBeingEatenSprite() {
			return 'blank';
		}

		function getJumpingSprite() {
			return 'jumping';
		}

		function getTrickSprite() {
			console.log('Trick step is', trickStep);
			if (trickStep === 0) {
				return 'jumping';
			} else if (trickStep === 1) {
				return 'somersault1';
			} else {
				return 'somersault2';
			}
		}

		that.stop = function () {
			if (that.direction > 180) {
				setDiscreteDirection('west');
			} else {
				setDiscreteDirection('east');
			}
		};

		that.turnEast = function () {
			var discreteDirection = getDiscreteDirection();

			switch (discreteDirection) {
				case 'west':
					setDiscreteDirection('wsWest');
					break;
				case 'wsWest':
					setDiscreteDirection('sWest');
					break;
				case 'sWest':
					setDiscreteDirection('south');
					break;
				case 'south':
					setDiscreteDirection('sEast');
					break;
				case 'sEast':
					setDiscreteDirection('esEast');
					break;
				case 'esEast':
					setDiscreteDirection('east');
					break;
				default:
					setDiscreteDirection('south');
					break;
			}
		};

		that.turnWest = function () {
			var discreteDirection = getDiscreteDirection();

			switch (discreteDirection) {
				case 'east':
					setDiscreteDirection('esEast');
					break;
				case 'esEast':
					setDiscreteDirection('sEast');
					break;
				case 'sEast':
					setDiscreteDirection('south');
					break;
				case 'south':
					setDiscreteDirection('sWest');
					break;
				case 'sWest':
					setDiscreteDirection('wsWest');
					break;
				case 'wsWest':
					setDiscreteDirection('west');
					break;
				default:
					setDiscreteDirection('south');
					break;
			}
		};

		that.stepWest = function () {
			that.mapPosition[0] -= that.speed * 2;
		};

		that.stepEast = function () {
			that.mapPosition[0] += that.speed * 2;
		};

		that.setMapPositionTarget = function (x, y) {
			if (that.hasBeenHit) return;

			if (Math.abs(that.mapPosition[0] - x) <= 75) {
				x = that.mapPosition[0];
			}

			that.movingToward = [ x, y ];

			// that.resetDirection();
		};

		that.startMovingIfPossible = function () {
			if (!that.hasBeenHit && !that.isBeingEaten) {
				that.isMoving = true;
			}
		};

		that.setTurnEaseCycles = function (c) {
			turnEaseCycles = c;
		};

		that.getPixelsTravelledDownMountain = function () {
			return pixelsTravelled;
		};

		that.resetSpeed = function () {
			that.setSpeed(standardSpeed);
		};

		that.cycle = function () {
			if ( that.getSpeedX() <= 0 && that.getSpeedY() <= 0 ) {
						that.isMoving = false;
			}
			if (that.isMoving) {
				pixelsTravelled += that.speed;
			}

			if (that.isJumping) {
				that.setMapPositionTarget(undefined, that.mapPosition[1] + that.getSpeed());
			}

			sup.cycle();

			that.checkHittableObjects();
		};

		that.draw = function(dContext) {
			var spritePartToUse = function () {
				if (that.isBeingEaten) {
					return getBeingEatenSprite();
				}

				if (that.isJumping) {
					if (that.isPerformingTrick) {
						return getTrickSprite();
					}
					return getJumpingSprite();
				}

				if (that.hasBeenHit) {
					return 'hit';
				}

				return getDiscreteDirection();
			};

			return sup.draw(dContext, spritePartToUse());
		};

		that.hits = function (obs) {
			if (obstaclesHit.indexOf(obs.id) !== -1) {
				return false;
			}

			if (!obs.occupiesZIndex(that.mapPosition[2])) {
				return false;
			}

			if (sup.hits(obs)) {
				return true;
			}

			return false;
		};

		that.speedBoost = function () {
			var originalSpeed = that.speed;
			if (canSpeedBoost) {
				canSpeedBoost = false;
				that.setSpeed(that.speed * 2);
				setTimeout(function () {
					that.setSpeed(originalSpeed);
					setTimeout(function () {
						canSpeedBoost = true;
					}, 10000);
				}, 2000);
			}
		};

		that.attemptTrick = function () {
			if (that.isJumping) {
				that.isPerformingTrick = true;
				cancelableStateInterval = setInterval(function () {
					if (trickStep >= 2) {
						trickStep = 0;
					} else {
						trickStep += 1;
					}
				}, 300);
			}
		};

		function easeSpeedToTargetUsingFactor(sp, targetSpeed, f) {
			if (f === 0 || f === 1) {
				return targetSpeed;
			}

			if (sp < targetSpeed) {
				sp += that.getSpeed() * (f / turnEaseCycles);
			}

			if (sp > targetSpeed) {
				sp -= that.getSpeed() * (f / turnEaseCycles);
			}

			return sp;
		}

		that.getSpeedX = function () {
			if (getDiscreteDirection() === 'esEast' || getDiscreteDirection() === 'wsWest') {
				speedXFactor = 0.5;
				speedX = easeSpeedToTargetUsingFactor(speedX, that.getSpeed() * speedXFactor, speedXFactor);

				return speedX;
			}

			if (getDiscreteDirection() === 'sEast' || getDiscreteDirection() === 'sWest') {
				speedXFactor = 0.33;
				speedX = easeSpeedToTargetUsingFactor(speedX, that.getSpeed() * speedXFactor, speedXFactor);

				return speedX;
			}

			// So it must be south

			speedX = easeSpeedToTargetUsingFactor(speedX, 0, speedXFactor);

			return speedX;
		};

		that.setSpeedY = function(sy) {
			speedY = sy;
		};

		that.getSpeedY = function () {
			var targetSpeed;

			if (that.isJumping) {
				return speedY;
			}

			if (getDiscreteDirection() === 'esEast' || getDiscreteDirection() === 'wsWest') {
				speedYFactor = 0.6;
				speedY = easeSpeedToTargetUsingFactor(speedY, that.getSpeed() * 0.6, 0.6);

				return speedY;
			}

			if (getDiscreteDirection() === 'sEast' || getDiscreteDirection() === 'sWest') {
				speedYFactor = 0.85;
				speedY = easeSpeedToTargetUsingFactor(speedY, that.getSpeed() * 0.85, 0.85);

				return speedY;
			}

			if (getDiscreteDirection() === 'east' || getDiscreteDirection() === 'west') {
				speedYFactor = 1;
				speedY = 0;

				return speedY;
			}

			// So it must be south

			speedY = easeSpeedToTargetUsingFactor(speedY, that.getSpeed(), speedYFactor);

			return speedY;
		};

		that.hasHitObstacle = function (obs) {
			setCrashed();

			if (navigator.vibrate) {
				navigator.vibrate(500);
			}

			obstaclesHit.push(obs.id);

			that.resetSpeed();

			if (cancelableStateTimeout) {
				clearTimeout(cancelableStateTimeout);
			}
			cancelableStateTimeout = setTimeout(function() {
				setNormal();
			}, 1500);
		};

		that.hasHitJump = function () {
			setJumping();

			if (cancelableStateTimeout) {
				clearTimeout(cancelableStateTimeout);
			}
			cancelableStateTimeout = setTimeout(function() {
				setNormal();
			}, 1000);
		};

		that.isEatenBy = function (monster, whenEaten) {
			that.hasHitObstacle(monster);
			monster.startEating(whenEaten);
			obstaclesHit.push(monster.id);
			that.isMoving = false;
			that.isBeingEaten = true;
		};

		that.reset = function () {
			obstaclesHit = [];
			pixelsTravelled = 0;
			that.isMoving = true;
			that.isJumping = false;
			that.hasBeenHit = false;
			canSpeedBoost = true;
		};

		return that;
	}

	global.skier = Skier;
})(this);

if (typeof module !== 'undefined') {
	module.exports = this.skier;
}
<|endoftext|>


<commit_before>var subnames = ['Machine Learning + Genomics',
                'Machine Learning + Neuroscience',
                'Machine Learning & AI'];

// Prepare document
$(document).ready(function() {
    $('#name').hide();
    $('#subname').hide();
    $('#name').fadeIn(1000);
    $('#subname').fadeIn(1750);
});

// Cycle through subheader
var idx = 0;
setInterval(function() {
    $('#subname').delay(2000).fadeOut(1000);
    $('#subname').text(subnames[idx++ % subnames.length]);
    $('#subname').fadeIn(1000);
}, 4100);

<commit_msg>Update main js<commit_after>var subnames = ['Machine Learning + Genomics',
                'Machine Learning + Neuroscience',
                'Machine Learning & AI'];

// Prepare document
$(document).ready(function() {
    $('#name').hide();
    $('#subname').hide();
    $('#name').fadeIn(1000);
    $('#subname').fadeIn(1750);
});

// Cycle through subheader
var idx = 0;
setInterval(function() {
    $('#subname').fadeOut(1000).text(subnames[idx++ % subnames.length]).fadeIn(1000).delay(2000);
}, 4100);

<|endoftext|>


<commit_before>define(["lib/hexagon", "lib/pathfinding"], (hexagon, PF) => {
  return { init(grid, layers, tileTypeSelector, coordMouse, coordHex) {
    "use strict";

    const SCENE_WIDTH = hexagon.grid.pixelWidth(grid);
    const SCENE_HEIGHT = hexagon.grid.pixelHeight(grid);
    const TileType = { LAND: 0, ROCK: 1, WATER: 2, VOID: 3, SAND: 4 };
    const TileProperties = [
      {obstacle: false, color: "rgb(100, 50, 0)"},
      {obstacle: true, color: "rgb(100, 100, 100)"},
      {obstacle: true, color: "rgb(0, 150, 200)"},
      {obstacle: true, color: "rgb(0, 0, 0)"},
      {obstacle: false, color: "rgb(255, 218, 65)"}
    ];
    let selectedTileType = TileType.LAND;

    layers.style.width = SCENE_WIDTH + "px";
    layers.style.height = SCENE_HEIGHT + "px";
    for (let i = 0; i < layers.children.length; i++) {
      layers.children[i].width = SCENE_WIDTH;
      layers.children[i].height = SCENE_HEIGHT;
    }
    const BG_CTX = layers.children[0].getContext('2d');
    const CTX = layers.children[1].getContext("2d");
    let firstStep = {x: 0, y: 0};
    let lastStep = {x: 0, y: 0};
    let path = [];

    BG_CTX.fillStyle = "rgb(50, 50, 50)";
    BG_CTX.fillRect(0, 0, SCENE_WIDTH, SCENE_HEIGHT);
    hexagon.grid.draw(BG_CTX, grid, "rgb(150, 150, 150)");

    function drawScene() {
      CTX.clearRect(0, 0, SCENE_WIDTH, SCENE_HEIGHT);
      for (let entry of grid.data) {
        let pos = entry[0], tile = entry[1];
        if (tile !== null) {
          const obstacleCoord = hexagon.grid.axisToPixel(grid, pos.x, pos.y);
          hexagon.draw(CTX, obstacleCoord, grid.radius, TileProperties[tile].color);
        }
      }
      for (let step of path) {
        const stepCoord = hexagon.grid.axisToPixel(grid, step.x, step.y);
        hexagon.draw(CTX, stepCoord, grid.radius, "rgb(0, 255, 0)");
      }
      hexagon.draw(CTX, hexagon.grid.axisToPixel(grid, firstStep.x, firstStep.y), grid.radius, "rgb(255, 0, 0)");
      hexagon.draw(CTX, hexagon.grid.axisToPixel(grid, lastStep.x, lastStep.y), grid.radius, "rgb(255, 0, 0)");
    }

    drawScene();

    layers.onmousemove = (e) => {
      const currentCoordinates = hexagon.grid.pixelToAxis(grid, e.offsetX, e.offsetY);
      if (lastStep.x !== currentCoordinates.x || lastStep. y !== currentCoordinates.y) {
        lastStep = currentCoordinates;
        path = PF.shortestPathBetween(firstStep, lastStep, PF.hexDistance, (pos) => {
          if (!hexagon.grid.contains(grid, pos.x, pos.y)) {
            return false;
          }
          return grid.data.get(pos) === null || !TileProperties[grid.data.get(pos)].obstacle;
        });
        drawScene();
      }
      coordMouse.rows[0].cells[1].innerHTML = e.offsetX;
      coordMouse.rows[0].cells[3].innerHTML = e.offsetY;
      coordHex.rows[0].cells[1].innerHTML = lastStep.x;
      coordHex.rows[0].cells[3].innerHTML = lastStep.y;
    };

    tileTypeSelector.onclick = (e) => {
      selectedTileType = parseInt(tileTypeSelector.elements['tile-type'].value);
    };

    layers.onclick = (e) => {
      const obstacle = hexagon.grid.pixelToAxis(grid, e.offsetX, e.offsetY);
      if(hexagon.grid.contains(grid, obstacle.x, obstacle.y)) {
        grid.data.set(obstacle, selectedTileType);
      }
    };
  }}
});
<commit_msg>FIX : restore right type of land on open of page<commit_after>define(["lib/hexagon", "lib/pathfinding"], (hexagon, PF) => {
  return { init(grid, layers, tileTypeSelector, coordMouse, coordHex) {
    "use strict";

    const SCENE_WIDTH = hexagon.grid.pixelWidth(grid);
    const SCENE_HEIGHT = hexagon.grid.pixelHeight(grid);
    const TileType = { LAND: 0, ROCK: 1, WATER: 2, VOID: 3, SAND: 4 };
    const TileProperties = [
      {obstacle: false, color: "rgb(100, 50, 0)"},
      {obstacle: true, color: "rgb(100, 100, 100)"},
      {obstacle: true, color: "rgb(0, 150, 200)"},
      {obstacle: true, color: "rgb(0, 0, 0)"},
      {obstacle: false, color: "rgb(255, 218, 65)"}
    ];
    let selectedTileType = parseInt(tileTypeSelector.elements['tile-type'].value);

    layers.style.width = SCENE_WIDTH + "px";
    layers.style.height = SCENE_HEIGHT + "px";
    for (let i = 0; i < layers.children.length; i++) {
      layers.children[i].width = SCENE_WIDTH;
      layers.children[i].height = SCENE_HEIGHT;
    }
    const BG_CTX = layers.children[0].getContext('2d');
    const CTX = layers.children[1].getContext("2d");
    let firstStep = {x: 0, y: 0};
    let lastStep = {x: 0, y: 0};
    let path = [];

    BG_CTX.fillStyle = "rgb(50, 50, 50)";
    BG_CTX.fillRect(0, 0, SCENE_WIDTH, SCENE_HEIGHT);
    hexagon.grid.draw(BG_CTX, grid, "rgb(150, 150, 150)");

    function drawScene() {
      CTX.clearRect(0, 0, SCENE_WIDTH, SCENE_HEIGHT);
      for (let entry of grid.data) {
        let pos = entry[0], tile = entry[1];
        if (tile !== null) {
          const obstacleCoord = hexagon.grid.axisToPixel(grid, pos.x, pos.y);
          hexagon.draw(CTX, obstacleCoord, grid.radius, TileProperties[tile].color);
        }
      }
      for (let step of path) {
        const stepCoord = hexagon.grid.axisToPixel(grid, step.x, step.y);
        hexagon.draw(CTX, stepCoord, grid.radius, "rgb(0, 255, 0)");
      }
      hexagon.draw(CTX, hexagon.grid.axisToPixel(grid, firstStep.x, firstStep.y), grid.radius, "rgb(255, 0, 0)");
      hexagon.draw(CTX, hexagon.grid.axisToPixel(grid, lastStep.x, lastStep.y), grid.radius, "rgb(255, 0, 0)");
    }

    drawScene();

    layers.onmousemove = (e) => {
      const currentCoordinates = hexagon.grid.pixelToAxis(grid, e.offsetX, e.offsetY);
      if (lastStep.x !== currentCoordinates.x || lastStep. y !== currentCoordinates.y) {
        lastStep = currentCoordinates;
        path = PF.shortestPathBetween(firstStep, lastStep, PF.hexDistance, (pos) => {
          if (!hexagon.grid.contains(grid, pos.x, pos.y)) {
            return false;
          }
          return grid.data.get(pos) === null || !TileProperties[grid.data.get(pos)].obstacle;
        });
        drawScene();
      }
      coordMouse.rows[0].cells[1].innerHTML = e.offsetX;
      coordMouse.rows[0].cells[3].innerHTML = e.offsetY;
      coordHex.rows[0].cells[1].innerHTML = lastStep.x;
      coordHex.rows[0].cells[3].innerHTML = lastStep.y;
    };

    tileTypeSelector.onclick = (e) => {
      selectedTileType = parseInt(tileTypeSelector.elements['tile-type'].value);
    };

    layers.onclick = (e) => {
      const obstacle = hexagon.grid.pixelToAxis(grid, e.offsetX, e.offsetY);
      if(hexagon.grid.contains(grid, obstacle.x, obstacle.y)) {
        grid.data.set(obstacle, selectedTileType);
      }
    };
  }}
});
<|endoftext|>