<commit_before>window.addEventListener('load', function () {
  var date = new Date()
  var todaysDate = new Date()
  var calendar = document.querySelectorAll('[data-calendar-area="month"]')[0]
  var nextButton = document.querySelectorAll('[data-calendar-toggle="next"]')[0]
  var prevButton = document.querySelectorAll('[data-calendar-toggle="previous"]')[0]

  date.setDate(1)
  createMonth()

  function createCalendarDay(num, day, year) {
    var newDay = document.createElement('div')

    var dateEl = document.createElement('span')
    dateEl.innerHTML = num
    newDay.className = 'cal__date'
    newDay.setAttribute('data-calendar-date', date)

    if (num === 1) {
      var offset = ((day - 1) * 14.28)
      if (offset > 0) {
        newDay.style.marginLeft = offset + '%'
      }
    }

    if (date.getTime() <= todaysDate.getTime() - 1) {
      newDay.classList.add('cal__date--disabled')
    } else {
      newDay.classList.add('cal__date--active')
      newDay.setAttribute('data-calendar-status', 'active')
    }

    if (date.toString() === todaysDate.toString()) {
      newDay.classList.add('cal__date--today')
    }

    newDay.appendChild(dateEl)
    calendar.appendChild(newDay)
  }

  // Creates and populates all of the days to make up the month
  function createMonth() {
    var currentMonth = date.getMonth()
    while (date.getMonth() === currentMonth) {
      createCalendarDay(date.getDate(), date.getDay(), date.getFullYear())
      date.setDate(date.getDate() + 1)
    }
    // while loop trips over and day is at 30/31, bring it back
    date.setDate(1)
    date.setMonth(date.getMonth() - 1)
    // Set the text to the correct month
    var currentMonthText = document.querySelectorAll('[data-calendar-label="month"]')[0]
    currentMonthText.innerHTML = monthsAsString(date.getMonth()) + ' ' + date.getFullYear()
    activeAction()
  }

  // Clears all days from the calendar
  function clearCalendar() {
    calendar.innerHTML = ''
  }

  // Clears the calendar and shows the next month
  nextButton.addEventListener('click', function () {
    clearCalendar()
    var nextMonth = date.getMonth() + 1
    date.setMonth(nextMonth)
    createMonth()
  })
  // Clears the calendar and shows the previous month
  prevButton.addEventListener('click', function () {
    clearCalendar()
    var prevMonth = date.getMonth() - 1
    date.setMonth(prevMonth)
    createMonth()
  })

  function activeAction() {
    activeDates = document.querySelectorAll('[data-calendar-status="active"]')
    for (var i = 0; i < activeDates.length; i++) {
      activeDates[i].addEventListener('click', function (event) {
        var picked = document.querySelectorAll('[data-calendar-label="picked"]')[0]
        picked.innerHTML = this.dataset.calendarDate
        removeActiveClass()
        this.classList.add('cal__date--selected')
      });
    }
  }

  function removeActiveClass() {
    for (var i = 0; i < activeDates.length; i++) {
      activeDates[i].classList.remove('cal__date--selected')
    }
  }

  // Converts month ids to the relevant string
  function monthsAsString(monthIndex) {
    return [
      'January',
      'Febuary',
      'March',
      'April',
      'May',
      'June',
      'July',
      'August',
      'September',
      'October',
      'November',
      'December'
    ][monthIndex]
  }
})
<commit_msg>Lint JS<commit_after>window.addEventListener('load', function () {
  var date = new Date()
  var todaysDate = new Date()
  var calendar = document.querySelectorAll('[data-calendar-area="month"]')[0]
  var nextButton = document.querySelectorAll('[data-calendar-toggle="next"]')[0]
  var prevButton = document.querySelectorAll('[data-calendar-toggle="previous"]')[0]
  var activeDates

  date.setDate(1)
  createMonth()

  function createCalendarDay (num, day, year) {
    var newDay = document.createElement('div')

    var dateEl = document.createElement('span')
    dateEl.innerHTML = num
    newDay.className = 'cal__date'
    newDay.setAttribute('data-calendar-date', date)

    if (num === 1) {
      var offset = ((day - 1) * 14.28)
      if (offset > 0) {
        newDay.style.marginLeft = offset + '%'
      }
    }

    if (date.getTime() <= todaysDate.getTime() - 1) {
      newDay.classList.add('cal__date--disabled')
    } else {
      newDay.classList.add('cal__date--active')
      newDay.setAttribute('data-calendar-status', 'active')
    }

    if (date.toString() === todaysDate.toString()) {
      newDay.classList.add('cal__date--today')
    }

    newDay.appendChild(dateEl)
    calendar.appendChild(newDay)
  }

  // Creates and populates all of the days to make up the month
  function createMonth () {
    var currentMonth = date.getMonth()
    while (date.getMonth() === currentMonth) {
      createCalendarDay(date.getDate(), date.getDay(), date.getFullYear())
      date.setDate(date.getDate() + 1)
    }
    // while loop trips over and day is at 30/31, bring it back
    date.setDate(1)
    date.setMonth(date.getMonth() - 1)
    // Set the text to the correct month
    var currentMonthText = document.querySelectorAll('[data-calendar-label="month"]')[0]
    currentMonthText.innerHTML = monthsAsString(date.getMonth()) + ' ' + date.getFullYear()
    activeAction()
  }

  // Clears all days from the calendar
  function clearCalendar () {
    calendar.innerHTML = ''
  }

  // Clears the calendar and shows the next month
  nextButton.addEventListener('click', function () {
    clearCalendar()
    var nextMonth = date.getMonth() + 1
    date.setMonth(nextMonth)
    createMonth()
  })
  // Clears the calendar and shows the previous month
  prevButton.addEventListener('click', function () {
    clearCalendar()
    var prevMonth = date.getMonth() - 1
    date.setMonth(prevMonth)
    createMonth()
  })

  function activeAction () {
    activeDates = document.querySelectorAll('[data-calendar-status="active"]')
    for (var i = 0; i < activeDates.length; i++) {
      activeDates[i].addEventListener('click', function (event) {
        var picked = document.querySelectorAll('[data-calendar-label="picked"]')[0]
        picked.innerHTML = this.dataset.calendarDate
        removeActiveClass()
        this.classList.add('cal__date--selected')
      })
    }
  }

  function removeActiveClass () {
    for (var i = 0; i < activeDates.length; i++) {
      activeDates[i].classList.remove('cal__date--selected')
    }
  }

  // Converts month ids to the relevant string
  function monthsAsString (monthIndex) {
    return [
      'January',
      'Febuary',
      'March',
      'April',
      'May',
      'June',
      'July',
      'August',
      'September',
      'October',
      'November',
      'December'
    ][monthIndex]
  }
})
<|endoftext|>


<commit_before>//Require rtmidi library to recive\send midi message
var midi = require('midi');

var transferArray = new Array;

var sendArray = [];

function add8bitToArray(param) {

	var paramType = typeof(param.value);

	switch (paramType) {
		case 'number':

			for (var i = 0; i < param.size; i++) {
				transferArray.push(param.value);
			}

			break;
		case 'string':
			for (var i = 0; i < param.size; i++) {

				if (param.value[i])
					transferArray.push(param.value[i]);
				else
					transferArray.push(0);

			}
			break;
		case 'boolean':
			transferArray.push(param.value & 1);
			break;
		default:
			console.error('Unresolve params type: ' + paramType, param);
			break;
	}

}

//Settings for slider,rotator

function slider() {
	this.active = {
		value: 1,
		size: 1
	};
	this.reverse = {
		value: 0,
		size: 1
	};
	this.channel = {
		value: 0,
		size: 1
	};
	this.event = {
		value: 0,
		size: 1
	};
	this.min_out_value = {
		value: 0,
		size: 1
	};
	this.max_out_value = {
		value: 127,
		size: 1
	};
	this.reserved = {
		value: 0,
		size: 4
	};
}

//Setting for pedal

function pedal() {
	this.active = {
		value: 1,
		size: 1
	};
	this.behavior = {
		value: 0,
		size: 1
	};
	this.reverse = {
		value: 0,
		size: 1
	};
	this.channel = {
		value: 0,
		size: 1
	};
	this.event = {
		value: 0,
		size: 1
	};
	this.min_in_value = {
		value: 0,
		size: 2
	};
	this.max_in_value = {
		value: 3000,
		size: 2
	};
	this.min_out_value = {
		value: 0,
		size: 1
	};
	this.max_out_value = {
		value: 127,
		size: 1
	};
	this.reserved = {
		value: 0,
		size: 4
	};
}

//Settings for button

function button() {
	this.type = {
		value: 1,
		size: 1
	};
	this.behavior = {
		value: 1,
		size: 1
	};
	this.ccnum = {
		value: 1,
		size: 1
	};
	this.onvalue = {
		value: 0,
		size: 1
	};
	this.offvalue = {
		value: 0,
		size: 1
	};
	this.reserved = {
		value: 0,
		size: 5
	};
}

//Preset entity
var Preset = {
	id: {
		number: 1,
		value: 3452,
		size: 2
	},
	name: {
		number: 2,
		value: 'VintageD',
		size: 16
	},
	midiChannel: {
		number: 3,
		value: 1,
		size: 1
	},
	highResMidiEnable: {
		number: 4,
		value: true,
		size: 1
	},
	analogMidiEnable: {
		number: 5,
		value: false,
		size: 1
	},
	curve: {
		value: 123,
		size: 48
	},
	pitch: new slider(6),
	modulation: new slider(7),
	pedal1: new pedal(8),
	pedal2: new pedal(9),
	pedal3: new pedal(10),
	slider0: new slider(11),
	slider1: new slider(12),
	slider2: new slider(13),
	slider3: new slider(14),
	slider4: new slider(15),
	slider5: new slider(16),
	slider6: new slider(17),
	slider7: new slider(18),
	slider8: new slider(19),
	rotator1: new slider(20),
	rotator2: new slider(21),
	rotator3: new slider(22),
	rotator4: new slider(23),
	rotator5: new slider(24),
	rotator6: new slider(25),
	rotator7: new slider(26),
	rotator8: new slider(27),
	button1: new button(28),
	button2: new button(29),
	button3: new button(30),
	button4: new button(31),
	button5: new button(32),
	button6: new button(33),
	button7: new button(34),
	button8: new button(35),
	dawbutton1: new button(36),
	dawbutton2: new button(37),
	dawbutton3: new button(38),
	dawbutton4: new button(39),
	dawbutton5: new button(40)
};

var midiConnect = {
	init: function() {
		console.log('await port');
	},
	output: new midi.output(),
	input: new midi.input()
};

// Send a MIDI message.

function sendSysexMessages() {

	if (sendArray.length > 0) {
		var sendingMessage = sendArray[0];
		//Delete sending message
		sendArray.splice(0, 1);
		console.log('Will be send message: ' + sendingMessage);
		midiConnect.output.sendMessage(sendingMessage);

	} else {
		console.log('Transfer finish');
	}

};

window.onload = function() {

	require("nw.gui").Window.get().show();

	midiConnect.init();

	midiConnect.output.openPort(0);
	midiConnect.input.openPort(0);

	midiConnect.input.ignoreTypes(false, false, false);

	midiConnect.input.on('message', function(deltaTime, message) {

		if (message[1] == 4) {
			console.log('Transfer ok detect');
			sendSysexMessages();
		}
		// console.log('m:' + message + ' d:' + deltaTime);

	});

	//Перебираем все свойства пресетов
	for (var key in Preset) {
		if (!Preset.hasOwnProperty(key)) continue;

		var PresValue = Preset[key];

		if (PresValue.hasOwnProperty('value')) {

			add8bitToArray(PresValue);

		} else {

			for (var key2 in PresValue) {
				if (!PresValue.hasOwnProperty(key2)) continue;
				add8bitToArray(PresValue[key2]);
			}

		}

	}

	// Add listners
	$('#presetUpload').on('click', function() {

		//2 byte - action
		sendArray.push([0xF0, 0, 0]);
		sendArray.push([0xF0, 0, 1]);
		//1 byte data syze
		sendArray.push([0xF0, 0, 4]);
		//Data
		sendArray.push([0xF0, 0, 1]);
		sendArray.push([0xF0, 0, 2]);
		sendArray.push([0xF0, 0, 3]);
		sendArray.push([0xF0, 0, 4]);

		//End message action
		sendArray.push([1, 2, 0xF7]);

		sendSysexMessages();

		// midiConnect.output.sendMessage([144,1,2]);

	});

}<commit_msg>routine<commit_after>//Require rtmidi library to recive\send midi message
var midi = require('midi');

var transferArray = new Array;

var sendArray = [];

function add8bitToArray(param) {

	var paramType = typeof(param.value);

	switch (paramType) {
		case 'number':

			for (var i = 0; i < param.size; i++) {
				transferArray.push(param.value);
			}

			break;
		case 'string':
			for (var i = 0; i < param.size; i++) {

				if (param.value[i])
					transferArray.push(param.value[i]);
				else
					transferArray.push(0);

			}
			break;
		case 'boolean':
			transferArray.push(param.value & 1);
			break;
		default:
			console.error('Unresolve params type: ' + paramType, param);
			break;
	}

}

//Settings for slider,rotator

function slider() {
	this.active = {
		value: 1,
		size: 1
	};
	this.reverse = {
		value: 0,
		size: 1
	};
	this.channel = {
		value: 0,
		size: 1
	};
	this.event = {
		value: 0,
		size: 1
	};
	this.min_out_value = {
		value: 0,
		size: 1
	};
	this.max_out_value = {
		value: 127,
		size: 1
	};
	this.reserved = {
		value: 0,
		size: 4
	};
}

//Setting for pedal

function pedal() {
	this.active = {
		value: 1,
		size: 1
	};
	this.behavior = {
		value: 0,
		size: 1
	};
	this.reverse = {
		value: 0,
		size: 1
	};
	this.channel = {
		value: 0,
		size: 1
	};
	this.event = {
		value: 0,
		size: 1
	};
	this.min_in_value = {
		value: 0,
		size: 2
	};
	this.max_in_value = {
		value: 3000,
		size: 2
	};
	this.min_out_value = {
		value: 0,
		size: 1
	};
	this.max_out_value = {
		value: 127,
		size: 1
	};
	this.reserved = {
		value: 0,
		size: 4
	};
}

//Settings for button

function button() {
	this.type = {
		value: 1,
		size: 1
	};
	this.behavior = {
		value: 1,
		size: 1
	};
	this.ccnum = {
		value: 1,
		size: 1
	};
	this.onvalue = {
		value: 0,
		size: 1
	};
	this.offvalue = {
		value: 0,
		size: 1
	};
	this.reserved = {
		value: 0,
		size: 5
	};
}

//Preset entity
var Preset = {
	id: {
		number: 1,
		value: 3452,
		size: 2
	},
	name: {
		number: 2,
		value: 'VintageD',
		size: 16
	},
	midiChannel: {
		number: 3,
		value: 1,
		size: 1
	},
	highResMidiEnable: {
		number: 4,
		value: true,
		size: 1
	},
	analogMidiEnable: {
		number: 5,
		value: false,
		size: 1
	},
	curve: {
		value: 123,
		size: 48
	},
	pitch: new slider(6),
	modulation: new slider(7),
	pedal1: new pedal(8),
	pedal2: new pedal(9),
	pedal3: new pedal(10),
	slider0: new slider(11),
	slider1: new slider(12),
	slider2: new slider(13),
	slider3: new slider(14),
	slider4: new slider(15),
	slider5: new slider(16),
	slider6: new slider(17),
	slider7: new slider(18),
	slider8: new slider(19),
	rotator1: new slider(20),
	rotator2: new slider(21),
	rotator3: new slider(22),
	rotator4: new slider(23),
	rotator5: new slider(24),
	rotator6: new slider(25),
	rotator7: new slider(26),
	rotator8: new slider(27),
	button1: new button(28),
	button2: new button(29),
	button3: new button(30),
	button4: new button(31),
	button5: new button(32),
	button6: new button(33),
	button7: new button(34),
	button8: new button(35),
	dawbutton1: new button(36),
	dawbutton2: new button(37),
	dawbutton3: new button(38),
	dawbutton4: new button(39),
	dawbutton5: new button(40)
};

var midiConnect = {
	init: function() {
		console.log('await port');
	},
	output: new midi.output(),
	input: new midi.input()
};

// Send a MIDI message.

function sendSysexMessages() {

	if (sendArray.length > 0) {
		var sendingMessage = sendArray[0];
		//Delete sending message
		sendArray.splice(0, 1);
		console.log('Will be send message: ' + sendingMessage);
		midiConnect.output.sendMessage(sendingMessage);

	} else {
		sendArray = [];
		console.log('Transfer finish');
	}

};

window.onload = function() {

	require("nw.gui").Window.get().show();

	midiConnect.init();

	console.log('Port name: ' + midiConnect.output.getPortName(1));

	midiConnect.output.openPort(1);
	midiConnect.input.openPort(1);

	midiConnect.input.ignoreTypes(false, false, false);

	midiConnect.input.on('message', function(deltaTime, message) {

		if (message[1] == 4) {
			console.log('Transfer ok detect');
			sendSysexMessages();
		}
		// console.log('m:' + message + ' d:' + deltaTime);

	});

	//Перебираем все свойства пресетов
	for (var key in Preset) {
		if (!Preset.hasOwnProperty(key)) continue;

		var PresValue = Preset[key];

		if (PresValue.hasOwnProperty('value')) {

			add8bitToArray(PresValue);

		} else {

			for (var key2 in PresValue) {
				if (!PresValue.hasOwnProperty(key2)) continue;
				add8bitToArray(PresValue[key2]);
			}

		}

	}

	// Add listners
	$('#presetUpload').on('click', function() {

		//2 byte - action
		sendArray.push([0xF0, 1, 2]);
		sendArray.push([0xF0, 0, 1]);
		// //1 byte data syze
		sendArray.push([0xF0, 0, 4]);
		// //Data
		sendArray.push([0xF0, 0, 1]);
		sendArray.push([0xF0, 0, 2]);
		sendArray.push([0xF0, 0, 3]);
		sendArray.push([0xF0, 0, 4]);

		//End message action
		sendArray.push([0xF0,1,0xF7]);

		sendSysexMessages();

		// midiConnect.output.sendMessage([144,1,2]);

	});

}<|endoftext|>


<commit_before>function Cube (element_id) {
	var DOM = {};
	DOM.cube = document.getElementById(element_id);
	DOM.side = {}
	DOM.value = {}
	DOM.score = document.getElementsByClassName('score');
	DOM.max = document.getElementsByClassName('max');
	this.DOM = DOM;

	var axis = ['z','-y','y','-z','-x','x'];
	var side = {};
	this.side = side;
	var coords = ['x','y','z'];

	var score = 0;
	var max_value = 0;
	this.end = false;

	function init () {
		coords = ['x','y','z'];
		score = 0;
		max_value = 0;
		this.end = false;

		DOM.cube.innerHTML = '

';
		DOM.cube.style.webkitTransform = new WebKitCSSMatrix();

		for (i in axis) DOM.side[axis[i]]=document.getElementById('side_'+axis[i]);
		for (i in axis) DOM.value[axis[i]]=document.getElementById('side_'+axis[i]).childNodes[0];
		for (i in axis) {side[axis[i]]=Math.round(Math.random()*2);}

		rotate3d(-1,-1,0,30); // initial rotation
		fill(); // initial filling
	};
	this.init = init;

	function fill () { // fill DOM.cube cube sides with appropriate values
		for (i in axis) {
			var element = DOM.side[axis[i]];
			var value = side[axis[i]];
			element.childNodes[0].innerHTML=value;
			var color = get_color(value);
			element.style.backgroundColor = 'rgba('+color.join(',')+',.5)';
		}
	}

	function animate_sides(reseted,increased) {
		DOM.value[reseted].style.fontSize='50%';
		DOM.value[increased].style.fontSize='150%';
		function return_state () {
			DOM.value[reseted].style.fontSize='100%'
			DOM.value[increased].style.fontSize='100%';
		}
		setTimeout(return_state,100);
		// DOM.value[reseted].style.fontSize='100%';
	}

	function make (direction) {
		var current_sides = {};
		current_sides.front = coords[2];
		current_sides.down = coords[1];
		current_sides.right = coords[0]
		current_sides.back = (current_sides.front.length==1)?'-'+current_sides.front:current_sides.front[1];
		current_sides.up = (current_sides.down.length==1)?'-'+current_sides.down:current_sides.down[1];
		current_sides.left = (current_sides.right.length==1)?'-'+current_sides.right:current_sides.right[1];
	    var front_value = side[current_sides.front];
	    var compare_value = side[current_sides[direction]];

	   	if (front_value!=compare_value) {
	   		rotate(direction);
	   	} else {
	   		side[current_sides[direction]]++;
	   		score += side[current_sides[direction]];
	   		side[current_sides.front] = get_new_value();
	   		animate_sides(current_sides.front,current_sides[direction]);
	   		fill();
	   		for (i in DOM.score) {
	   			DOM.score[i].innerHTML = score;
	   		}
	   		if (check_fail()) {
	   			this.end = true;
	   			ga('send', 'event', 'game', 'end', {'metric1':side[current_sides[direction]],'metric2':score});

	   		} else this.end = false;
	   		var fail_text = "

tap or press space to restart
See source on github";
	   		if (side[current_sides[direction]]>max_value) {
	   			max_value=side[current_sides[direction]];

		   		for (i in DOM.max) {
		   			DOM.max[i].innerHTML = max_value;
		   		}
	   			if (max_value==5) show_info({top:'CONGRATULATIONS!',header:side[current_sides[direction]],text:'If you get 10 - you will win'+((check_fail())?fail_text:'')});
	   			if (max_value==10) {show_info({top:'YOU WON!',header:side[current_sides[direction]],text:'So... can you get 15?'+(check_fail())?fail_text:''});ga('send', 'event', 'game', 'win');}
	   			if (max_value==15) show_info({top:'AMAZING!',header:side[current_sides[direction]],text:"I'll bet - you will do 20!"+(check_fail())?fail_text:''});
	   			if (max_value>=20) {
	   				var graz = ['CONGRATULATIONS!','UNBELIEVABLE!','What a wonder!','Is that real?'];
	   				graz = graz[Math.floor(Math.random()*graz.length)];

	   				show_info({top:graz,header:side[current_sides[direction]],text:'Try to get '+(side[current_sides[direction]]+1)+(check_fail())?fail_text:''});
	   			};

	   		}
	   		if (check_fail() && !infobox) {

	   			show_info({top:'So sorry ):',header:max_value,text:"... and "+score+" points - that's all what you've got."+fail_text});
	   		}
	   	};
	   	var prev_front = document.getElementsByClassName('front')[0];
	   	prev_front.className='side';
	   	DOM.side[coords[2]].className='side front';
	};
	this.make = make;

	function get_new_value () {
		var values = unique([side['x'],side['-x'],side['y'],side['-y'],side['-z']]).sort();
		if (values[0]!=0) values.unshift(values[0]-1);
		var rand = 0;
        if (values.length==2) {
            rand = Math.round(Math.random());
        } else if (values.length>2) {
            rand = Math.round(Math.random()*9);
            rand = (rand < 4)?0:(rand < 9)?1:2;
        }

		return values[rand];
	}

	function check_fail () {
		var fail = false;
		if (   side['z']!=side['-y']
	        && side['z']!=side['-x']
	        && side['z']!=side['x']
	        && side['z']!=side['y']
	        && side['-z']!=side['-y']
	        && side['-z']!=side['-x']
	        && side['-z']!=side['x']
	        && side['-z']!=side['y']
	        && side['-y']!=side['-x']
	        && side['-y']!=side['x']
	        && side['y']!=side['-x']
	        && side['y']!=side['x']) fail = true;
		return fail;
	}

	function rotate (direction) {
		var t_angles = [0,0,0];
		switch (direction) {
	        case "up" : {
	            t_angles = convert_angles(1,0);
	        }; break;
	        case "down" : {
	            t_angles = convert_angles(-1,0);
	        }; break;
	        case "left" : {
	            t_angles = convert_angles(0,-1);
	        }; break;
	        case "right" : {
	            t_angles = convert_angles(0,1);
	        }; break;
	        default: throw new TypeError('direction must be "up", "down", "left" or "right", but not: "'+direction+'"');
	    };
		rotate3d(t_angles[0],t_angles[1],t_angles[2],90);
	}

	function convert_angles (x,y) {
		var new_angles = [0,0,0];

			switch (coords[0]) {
				case "x" : new_angles[0]=x;break;
				case "-x" : new_angles[0]=-x;break;
				case "y" : new_angles[1]=x;break;
				case "-y" : new_angles[1]=-x;break;
				case "z" : new_angles[2]=x;break;
				case "-z" : new_angles[2]=-x;break;
			}
			switch (coords[1]) {
				case "x" : new_angles[0]=y;break;
				case "-x" : new_angles[0]=-y;break;
				case "y" : new_angles[1]=y;break;
				case "-y" : new_angles[1]=-y;break;
				case "z" : new_angles[2]=y;break;
				case "-z" : new_angles[2]=-y;break;
			}

			switch ([x,y].join(',')) {
				case "1,0": { //up
					var temp = coords[2];
					coords[2] = coords[1];
					coords[1] = (temp.length==1)?'-'+temp:temp[1];
				}; break;
				case "-1,0": { //down
					var temp = coords[1];
					coords[1] = coords[2];
					coords[2] = (temp.length==1)?'-'+temp:temp[1];
				}; break;
				case "0,1": { //right
					var temp = coords[0];
					coords[0] = coords[2];
					coords[2] = (temp.length==1)?'-'+temp:temp[1];
				}; break;
				case "0,-1": { //left
					var temp = coords[2];
					coords[2] = coords[0];
					coords[0] = (temp.length==1)?'-'+temp:temp[1];
				}; break;
			};

		var tX = 0,tY=0,tZ=0;

		return new_angles;
	}

	function rotate3d(x,y,z,degree) {
		var matrix = new WebKitCSSMatrix(DOM.cube.style.webkitTransform);
		matrix = matrix.rotateAxisAngle(x,y,z,degree);
		DOM.cube.style.webkitTransform = matrix.toString();
	}

	init();

	return this;
}

var infobox = false;
var touch = {start:{x:undefined,y:undefined},end:{x:undefined,y:undefined}};
var cube = new Cube('cube3d') // main cube object

function get_color (value) {
	Math.seedrandom(value);
    var color = [(Math.round(Math.random()*150)+55),(Math.round(Math.random()*250)+5),(Math.round(Math.random()*250)+5)];
    Math.seedrandom();
    return color;
}

function unique(arr) {
  var obj = {};
  var result = [];

  nextInput:
  for(var i=0; i<arr.length; i++) {
    var str = arr[i];
    for(var j=0; j<result.length; j++) {
      if (result[j] == str) continue nextInput;
    }
    result.push(str);
  }

  return result;
}

function show_info (params) {
	var DOM_info = document.getElementById('info');
	var DOM_top = document.getElementById('info_top');
	var DOM_h1 = document.getElementById('info_h1');
	var DOM_p = document.getElementById('info_p');
	DOM_top.innerHTML = params.top;
	DOM_h1.innerHTML = params.header;
	DOM_p.innerHTML = params.text;
	DOM_info.style.backgroundColor = 'rgba('+get_color(params.header).join(',')+',.5)';
	DOM_info.childNodes[0].style.boxShadow = '0 0 2em rgb('+get_color(params.header).join(',')+')';
	DOM_info.style.display = 'block';

	setTimeout(function(){
		DOM_info.style.opacity = 1;
	},0);

	infobox = true;
}
show_info({top:'',header:'hello'
		  ,text:'press ←,↑,→,↓
or
swipe ←,↑,→,↓.
Chosen side will increased, if it equal to front, cube will rotate otherwise.
 Press space or tap to close info.'});

function hide_info () {
	var DOM_info = document.getElementById('info');
	DOM_info.style.backgroundColor = '';
	DOM_info.style.opacity = 0;
	setTimeout(function(){DOM_info.style.display = 'none';},0);
	infobox = false;
	if (cube.end) cube.init();
}

function touchStart (e) {
	e.preventDefault();
	touch.start.x = e.changedTouches[0].clientX;
	touch.start.y = e.changedTouches[0].clientY;
};
function touchMove (e) {};
function touchCansel (e) {};
function touchEnd (e) {
	if (e.target.nodeName != 'A') {
		e.preventDefault();
		touch.end.x = e.changedTouches[0].clientX;
		touch.end.y = e.changedTouches[0].clientY;
		touch_handler();
	}
}

function touch_handler() {
	var evnt = '';
	var dX = touch.end.x - touch.start.x;
	var dY = touch.end.y - touch.start.y;
	if (Math.abs(dX)==Math.abs(dY)) {
		evnt = 'tap';
	} else {
		var d = 0;
		if (Math.abs(dX)>Math.abs(dY)) {
			d = Math.abs(dX);
			evnt = (dX>0)?'right':'left';
		} else {
			d = Math.abs(dY);
			evnt = (dY>0)?'down':'up';
		}
		if (d<20) evnt = 'tap';
	}
	event_handler(evnt);
}

function keyup(ev) {
	var table = {
		 32:'space'
		,37:'left'
		,38:'up'
		,39:'right'
		,40:'down'
	}
	if (table[ev.which]) event_handler(table[ev.which])
}

function event_handler(ev) {
	if (infobox) {
		if (ev=='tap' || ev=='space') hide_info();
	} else {
		cube.make(ev);
	}
}
<commit_msg>another ga changes<commit_after>function Cube (element_id) {
	var DOM = {};
	DOM.cube = document.getElementById(element_id);
	DOM.side = {}
	DOM.value = {}
	DOM.score = document.getElementsByClassName('score');
	DOM.max = document.getElementsByClassName('max');
	this.DOM = DOM;

	var axis = ['z','-y','y','-z','-x','x'];
	var side = {};
	this.side = side;
	var coords = ['x','y','z'];

	var score = 0;
	var max_value = 0;
	this.end = false;

	function init () {
		coords = ['x','y','z'];
		score = 0;
		max_value = 0;
		this.end = false;

		DOM.cube.innerHTML = '

';
		DOM.cube.style.webkitTransform = new WebKitCSSMatrix();

		for (i in axis) DOM.side[axis[i]]=document.getElementById('side_'+axis[i]);
		for (i in axis) DOM.value[axis[i]]=document.getElementById('side_'+axis[i]).childNodes[0];
		for (i in axis) {side[axis[i]]=Math.round(Math.random()*2);}

		rotate3d(-1,-1,0,30); // initial rotation
		fill(); // initial filling
	};
	this.init = init;

	function fill () { // fill DOM.cube cube sides with appropriate values
		for (i in axis) {
			var element = DOM.side[axis[i]];
			var value = side[axis[i]];
			element.childNodes[0].innerHTML=value;
			var color = get_color(value);
			element.style.backgroundColor = 'rgba('+color.join(',')+',.5)';
		}
	}

	function animate_sides(reseted,increased) {
		DOM.value[reseted].style.fontSize='50%';
		DOM.value[increased].style.fontSize='150%';
		function return_state () {
			DOM.value[reseted].style.fontSize='100%'
			DOM.value[increased].style.fontSize='100%';
		}
		setTimeout(return_state,100);
		// DOM.value[reseted].style.fontSize='100%';
	}

	function make (direction) {
		var current_sides = {};
		current_sides.front = coords[2];
		current_sides.down = coords[1];
		current_sides.right = coords[0]
		current_sides.back = (current_sides.front.length==1)?'-'+current_sides.front:current_sides.front[1];
		current_sides.up = (current_sides.down.length==1)?'-'+current_sides.down:current_sides.down[1];
		current_sides.left = (current_sides.right.length==1)?'-'+current_sides.right:current_sides.right[1];
	    var front_value = side[current_sides.front];
	    var compare_value = side[current_sides[direction]];

	   	if (front_value!=compare_value) {
	   		rotate(direction);
	   	} else {
	   		side[current_sides[direction]]++;
	   		score += side[current_sides[direction]];
	   		side[current_sides.front] = get_new_value();
	   		animate_sides(current_sides.front,current_sides[direction]);
	   		fill();
	   		for (i in DOM.score) {
	   			DOM.score[i].innerHTML = score;
	   		}
	   		if (check_fail()) {
	   			this.end = true;
	   			ga('send', 'event', 'max', 'max-'+side[current_sides[direction]]);

	   		} else this.end = false;
	   		var fail_text = "

tap or press space to restart
See source on github";
	   		if (side[current_sides[direction]]>max_value) {
	   			max_value=side[current_sides[direction]];

		   		for (i in DOM.max) {
		   			DOM.max[i].innerHTML = max_value;
		   		}
	   			if (max_value==5) show_info({top:'CONGRATULATIONS!',header:side[current_sides[direction]],text:'If you get 10 - you will win'+((check_fail())?fail_text:'')});
	   			if (max_value==10) {show_info({top:'YOU WON!',header:side[current_sides[direction]],text:'So... can you get 15?'+(check_fail())?fail_text:''});ga('send', 'event', 'game', 'win');}
	   			if (max_value==15) show_info({top:'AMAZING!',header:side[current_sides[direction]],text:"I'll bet - you will do 20!"+(check_fail())?fail_text:''});
	   			if (max_value>=20) {
	   				var graz = ['CONGRATULATIONS!','UNBELIEVABLE!','What a wonder!','Is that real?'];
	   				graz = graz[Math.floor(Math.random()*graz.length)];

	   				show_info({top:graz,header:side[current_sides[direction]],text:'Try to get '+(side[current_sides[direction]]+1)+(check_fail())?fail_text:''});
	   			};

	   		}
	   		if (check_fail() && !infobox) {

	   			show_info({top:'So sorry ):',header:max_value,text:"... and "+score+" points - that's all what you've got."+fail_text});
	   		}
	   	};
	   	var prev_front = document.getElementsByClassName('front')[0];
	   	prev_front.className='side';
	   	DOM.side[coords[2]].className='side front';
	};
	this.make = make;

	function get_new_value () {
		var values = unique([side['x'],side['-x'],side['y'],side['-y'],side['-z']]).sort();
		if (values[0]!=0) values.unshift(values[0]-1);
		var rand = 0;
        if (values.length==2) {
            rand = Math.round(Math.random());
        } else if (values.length>2) {
            rand = Math.round(Math.random()*9);
            rand = (rand < 4)?0:(rand < 9)?1:2;
        }

		return values[rand];
	}

	function check_fail () {
		var fail = false;
		if (   side['z']!=side['-y']
	        && side['z']!=side['-x']
	        && side['z']!=side['x']
	        && side['z']!=side['y']
	        && side['-z']!=side['-y']
	        && side['-z']!=side['-x']
	        && side['-z']!=side['x']
	        && side['-z']!=side['y']
	        && side['-y']!=side['-x']
	        && side['-y']!=side['x']
	        && side['y']!=side['-x']
	        && side['y']!=side['x']) fail = true;
		return fail;
	}

	function rotate (direction) {
		var t_angles = [0,0,0];
		switch (direction) {
	        case "up" : {
	            t_angles = convert_angles(1,0);
	        }; break;
	        case "down" : {
	            t_angles = convert_angles(-1,0);
	        }; break;
	        case "left" : {
	            t_angles = convert_angles(0,-1);
	        }; break;
	        case "right" : {
	            t_angles = convert_angles(0,1);
	        }; break;
	        default: throw new TypeError('direction must be "up", "down", "left" or "right", but not: "'+direction+'"');
	    };
		rotate3d(t_angles[0],t_angles[1],t_angles[2],90);
	}

	function convert_angles (x,y) {
		var new_angles = [0,0,0];

			switch (coords[0]) {
				case "x" : new_angles[0]=x;break;
				case "-x" : new_angles[0]=-x;break;
				case "y" : new_angles[1]=x;break;
				case "-y" : new_angles[1]=-x;break;
				case "z" : new_angles[2]=x;break;
				case "-z" : new_angles[2]=-x;break;
			}
			switch (coords[1]) {
				case "x" : new_angles[0]=y;break;
				case "-x" : new_angles[0]=-y;break;
				case "y" : new_angles[1]=y;break;
				case "-y" : new_angles[1]=-y;break;
				case "z" : new_angles[2]=y;break;
				case "-z" : new_angles[2]=-y;break;
			}

			switch ([x,y].join(',')) {
				case "1,0": { //up
					var temp = coords[2];
					coords[2] = coords[1];
					coords[1] = (temp.length==1)?'-'+temp:temp[1];
				}; break;
				case "-1,0": { //down
					var temp = coords[1];
					coords[1] = coords[2];
					coords[2] = (temp.length==1)?'-'+temp:temp[1];
				}; break;
				case "0,1": { //right
					var temp = coords[0];
					coords[0] = coords[2];
					coords[2] = (temp.length==1)?'-'+temp:temp[1];
				}; break;
				case "0,-1": { //left
					var temp = coords[2];
					coords[2] = coords[0];
					coords[0] = (temp.length==1)?'-'+temp:temp[1];
				}; break;
			};

		var tX = 0,tY=0,tZ=0;

		return new_angles;
	}

	function rotate3d(x,y,z,degree) {
		var matrix = new WebKitCSSMatrix(DOM.cube.style.webkitTransform);
		matrix = matrix.rotateAxisAngle(x,y,z,degree);
		DOM.cube.style.webkitTransform = matrix.toString();
	}

	init();

	return this;
}

var infobox = false;
var touch = {start:{x:undefined,y:undefined},end:{x:undefined,y:undefined}};
var cube = new Cube('cube3d') // main cube object

function get_color (value) {
	Math.seedrandom(value);
    var color = [(Math.round(Math.random()*150)+55),(Math.round(Math.random()*250)+5),(Math.round(Math.random()*250)+5)];
    Math.seedrandom();
    return color;
}

function unique(arr) {
  var obj = {};
  var result = [];

  nextInput:
  for(var i=0; i<arr.length; i++) {
    var str = arr[i];
    for(var j=0; j<result.length; j++) {
      if (result[j] == str) continue nextInput;
    }
    result.push(str);
  }

  return result;
}

function show_info (params) {
	var DOM_info = document.getElementById('info');
	var DOM_top = document.getElementById('info_top');
	var DOM_h1 = document.getElementById('info_h1');
	var DOM_p = document.getElementById('info_p');
	DOM_top.innerHTML = params.top;
	DOM_h1.innerHTML = params.header;
	DOM_p.innerHTML = params.text;
	DOM_info.style.backgroundColor = 'rgba('+get_color(params.header).join(',')+',.5)';
	DOM_info.childNodes[0].style.boxShadow = '0 0 2em rgb('+get_color(params.header).join(',')+')';
	DOM_info.style.display = 'block';

	setTimeout(function(){
		DOM_info.style.opacity = 1;
	},0);

	infobox = true;
}
show_info({top:'',header:'hello'
		  ,text:'press ←,↑,→,↓
or
swipe ←,↑,→,↓.
Chosen side will increased, if it equal to front, cube will rotate otherwise.
 Press space or tap to close info.'});

function hide_info () {
	var DOM_info = document.getElementById('info');
	DOM_info.style.backgroundColor = '';
	DOM_info.style.opacity = 0;
	setTimeout(function(){DOM_info.style.display = 'none';},0);
	infobox = false;
	if (cube.end) cube.init();
}

function touchStart (e) {
	e.preventDefault();
	touch.start.x = e.changedTouches[0].clientX;
	touch.start.y = e.changedTouches[0].clientY;
};
function touchMove (e) {};
function touchCansel (e) {};
function touchEnd (e) {
	if (e.target.nodeName != 'A') {
		e.preventDefault();
		touch.end.x = e.changedTouches[0].clientX;
		touch.end.y = e.changedTouches[0].clientY;
		touch_handler();
	}
}

function touch_handler() {
	var evnt = '';
	var dX = touch.end.x - touch.start.x;
	var dY = touch.end.y - touch.start.y;
	if (Math.abs(dX)==Math.abs(dY)) {
		evnt = 'tap';
	} else {
		var d = 0;
		if (Math.abs(dX)>Math.abs(dY)) {
			d = Math.abs(dX);
			evnt = (dX>0)?'right':'left';
		} else {
			d = Math.abs(dY);
			evnt = (dY>0)?'down':'up';
		}
		if (d<20) evnt = 'tap';
	}
	event_handler(evnt);
}

function keyup(ev) {
	var table = {
		 32:'space'
		,37:'left'
		,38:'up'
		,39:'right'
		,40:'down'
	}
	if (table[ev.which]) event_handler(table[ev.which])
}

function event_handler(ev) {
	if (infobox) {
		if (ev=='tap' || ev=='space') hide_info();
	} else {
		cube.make(ev);
	}
}
<|endoftext|>


<commit_before>//Created by Brandon Dail

'use strict';

var svgElements = [];

var createSVGReference = function(selector, options){

	//container object
	var svg = {};
	if(document.querySelector) svg.elem   = document.querySelector(selector);
	else return false; //fuck browsers that don't have querySelector

	//general options
	svg._options = _.assign({

		visible: false,
		isTweened: false,
		duration: 0.5,
		scrollDirection: null,
		scrollBegin: 0,
		scrollEnd: 0

	}, options);

	//TODO add option for appearance type (fade, scroll, spin, etc);

	svg.intermediateTween = {};

	if(options.init){
		svg._initialTween = options.init;
		TweenLite.to(svg.elem, svg._options.duration, _.assign(options.init));
	}

	//TODO allow for object prop to be excluded and assumed to have remained the same
	var tweenFunc = function(){

		var tweenModel = {};

		//TODO Abstract this out so we can use it here and when we find the differences onscroll
		//Compare and find the differences between the start and end states
		_.forEach(svg._options.scrollEndState, function(value, key){

			if(options.init[key] ){

				tweenModel[key] = options.init.css && options.init.css[key] ?  value - options.init.css[key] : value - options.init[key];
			}

			else {
				tweenModel[key] = value;
			}
		});

		var totalTraversal = svg._options.scrollEnd - svg._options.scrollBegin;

		var tween = {};
		_.forEach(tweenModel, function(value, key){

			tween[key] = value / totalTraversal;

		});

		return tween;

	};

	svg.tween = tweenFunc();

	//add the svg element to the svgElements list
	svgElements.push(svg);
	return svg;
};

//TODO this needs to be local to each SVG

//TODO fix tweenFunc so it caches the css properties for us earlier.

var tweenIt = function(){

	_.forEach(svgElements, function(svg){

		if(window.pageYOffset < 0)
			TweenLite.to(svg.elem, 0.016, svg._initialTween);

		if(window.pageYOffset > svg._options.scrollEnd){
			TweenLite.to(svg.elem, 0.016, svg._options.scrollEndState);
		}

		if(window.pageYOffset <= svg._options.scrollEnd && window.pageYOffset >= svg._options.scrollBegin && window.pageYOffset > 0){

			if(svg._options.isTweened){

				//TODO this math is all fucked, see the bottom notes.
				_.forEach(svg._initialTween.css, function(value, key){
					svg.intermediateTween.css[key] = svg._initialTween.css[key] + (svg.tween[key] * window.pageYOffset)

				})

			}

			//otherwise lets initiate the tween;
			else {
				svg._options.isTweened = true;
			}

			TweenLite.to(svg.elem, 0.016, svg.intermediateTween);

		}

	});

}

//TODO add option for media-query like conditional animations
//TODO add option to use css classes to declare start and end states

window.addEventListener('scroll', function(){

	window.requestAnimationFrame(tweenIt);

}, false);

window.addEventListener('load', tweenIt, false);

<commit_msg>v0.0.1<commit_after>
var scrollJS = (function(){

	svgElements = [];

	//return function
	return function(selector, options){

		//container object
		var svg = {};
		if(document.querySelector) svg.elem   = document.querySelector(selector);
		else return false; //fuck browsers that don't have querySelector

		//general options
		svg._options = _.assign({

			visible: false,
			isTweened: false,
			duration: 0.5,
			scrollDirection: null,
			scrollBegin: 0,
			scrollEnd: 0

		}, options);

		//TODO add option for appearance type (fade, scroll, spin, etc);

		svg.intermediateTween = {};

		//TODO parse numeric values from css-specifc attribitues, i.e., 100 from 'border-radius: 100%'
		if(options.init){
			svg._initialTween = options.init;
			TweenLite.to(svg.elem, svg._options.duration, _.assign(options.init));
		}

		//TODO allow for object prop to be excluded and assumed to have remained the same
		var tweenFunc = function(){

			var tweenModel = {};

			//TODO Abstract this out so we can use it here and when we find the differences onscroll
			//Compare and find the differences between the start and end states
			_.forEach(svg._options.scrollEndState, function(value, key){

				if(options.init[key] ){

					tweenModel[key] = options.init.css && options.init.css[key] ?  value - options.init.css[key] : value - options.init[key];
				}

				else {
					tweenModel[key] = value;
				}
			});

			console.log('tweenModel', tweenModel);

			var totalTraversal = svg._options.scrollEnd - svg._options.scrollBegin;
			console.log('totalTraversal', totalTraversal);
			var tween = {};
			_.forEach(tweenModel, function(value, key){

				tween[key] = value / totalTraversal;

			});
			console.log('tween', tween);
			return tween;

		};

		svg.tween = tweenFunc();

		//add the svg element to the svgElements list
		svgElements.push(svg);
		return svg;
	};

})();

var svgElements = [];
'use strict';

//TODO this needs to be local to each SVG

//TODO fix tweenFunc so it caches the css properties for us earlier.

var tweenIt = function(){

	//console.log('tweenIt invoked');

	_.forEach(svgElements, function(svg){

		if(window.pageYOffset < 0)
			TweenMax.to(svg.elem, 0.016, svg._initialTween);

		if(window.pageYOffset > svg._options.scrollEnd){
			TweenMax.to(svg.elem, 0.016, svg._options.scrollEndState);
		}

		if(window.pageYOffset <= svg._options.scrollEnd && window.pageYOffset >= svg._options.scrollBegin && window.pageYOffset > 0){

			//console.log('Should be tweening!');

			if(svg._options.isTweened){

				//TODO make function so it can be called recursively

				_.forEach(svg._initialTween, function(value, key){

					if ( key === 'css' ) {

						_.forEach(svg._initialTween[key], function(value, key){
							svg.intermediateTween.css[key] = value + (svg.tween[key] * window.pageYOffset)
						})

					}

					else {

						svg.intermediateTween[key] = svg._initialTween[key] + (svg.tween[key] * window.pageYOffset)
						//console.log(key, value);

					}

				})

			}

			//otherwise lets initiate the tween;
			else {
				svg._options.isTweened = true;
			}

			//console.log(svg.intermediateTween);
			TweenMax.to(svg.elem, 0.016, svg.intermediateTween);

		}

	});

}

//TODO add option for media-query like conditional animations
//TODO add option to use css classes to declare start and end states

window.addEventListener('scroll', function(){

	window.requestAnimationFrame(tweenIt);

}, false);

window.addEventListener('load', tweenIt, false);

<|endoftext|>


<commit_before>

var scrollJS = (function(){

	var scrollElements        = [],
		tweenableElements     = [],

		tweenElementPrototype = {

			// Used to set tween positions

			at : function(scrollPosition, scrollState){

				if(typeof scrollPosition !== "number" || scrollPosition < 0) throw new Error('Scroll position must be a number greater than 0');
				if(this._tweenPositionDefined(scrollPosition)) throw new Error('Scroll position already defined for this element');
				if(Object.keys(scrollState).length === 0){ throw new Error('Scroll state must have at least one value')  };

				var breakpoint = {};
				for(value in scrollState){
					if(scrollState.hasOwnProperty(value)){
						breakpoint[value] = scrollState[value];
					}
				}

				breakpoint['scrollPosition'] = scrollPosition;

				this.tweenBreakpoints.push(breakpoint);

				this._updateTweens();
			},

			// Used in _updateTweens to ensure that the tweenBreakpoint elements are in order

			_sortCompareFunction : function(first, second){
				if(first.scrollPosition < second.scrollPosition) return -1;
				if(first.scrollPosition > second.scrollPosition) return 1;
				return 0;

			},

			_updateTweens : function(){

				// Sort the breakpoints so we have them in order
				this.tweenBreakpoints = this.tweenBreakpoints.sort(this._sortCompareFunction);

				//for(var value in this.tweenBreakpoints[0]){
				//	if(this.tweenBreakpoints[0].hasOwnProperty(value) && value !== 'increment' && value !== 'scrollPosition'){
				//		this.zeroTween[value] = this.tweenBreakpoints[0][value];
				//	}
				//
				//}

				for(var i = 0; i < this.tweenBreakpoints.length; i++){

					if(this.tweenBreakpoints[i + 1]){

						this._calculateTweenIncrement(this.tweenBreakpoints[i], this.tweenBreakpoints[i + 1])
					}
				}
			},

			_calculateTweenIncrement : function(firstTween, secondTween){

				var totalTraversal = secondTween.scrollPosition - firstTween.scrollPosition;

				// We always store the increment values on the first object
				if(!firstTween.increment) firstTween.increment = {};

				for(var type in firstTween){
					if(firstTween.hasOwnProperty(type) && type !== 'scrollPosition' && type !== 'increment' && secondTween[type] === undefined){
						console.log(type);
						secondTween[type] = firstTween[type];
					}

				}

				//TODO if value is in secondTween but not in firstTween, set value to 0 for firstTween
				for(var value in secondTween){

					if(secondTween.hasOwnProperty(value) && value !== 'increment'){
						firstTween.increment[value] = (secondTween[value] - firstTween[value]) / totalTraversal;
					}

				}

			},

			//TODO set a value on the tweenElement that we can check quickly
			//TODO  so that we know if a new tweenPair is needed

			_getActiveTweenPair: function(){

				var offset = window.pageYOffset;
				if(offset < this.cache.activeTweenPairUpperBound && offset > this.cache.activeTweenPairLowerBound) return;

				var breakpoints = this.tweenBreakpoints.map(function(value){ return value.scrollPosition });

				if(!this.initialTweenPairSet){

					if(breakpoints[breakpoints.length - 1] < offset){
						this._activeTweenPair.splice(0);
						this._activeTweenPair.push(this.tweenBreakpoints[breakpoints.length - 2], this.tweenBreakpoints[breakpoints.length - 1]);
						this._initialTweenPairSet = true;
						return;
					}

				}

				for(var i = 0; i < breakpoints.length; i++){
					if((offset > breakpoints[i] || breakpoints[i] === 0) && offset < breakpoints[i + 1]){
						this._activeTweenPair.splice(0);
						this._activeTweenPair.push(this.tweenBreakpoints[i], this.tweenBreakpoints[i+1]);
						this.cache['activeTweenPairUpperBound'] = breakpoints[i + 1];
						this.cache['activeTweenPairLowerBound'] = breakpoints[i];
						return;
					}
				}

			},

			_animateTweens : function(){

				//TODO gix issue with activeTweenPair not loading when the page is loaded at an offset > 0
				this._getActiveTweenPair();

				if(window.pageYOffset <= this._activeTweenPair[1].scrollPosition && window.pageYOffset >= 0){
					this._isTweenable = true;

					var tweenState = {};

					for(var value in this._activeTweenPair[1]){

						if(this._activeTweenPair[1].hasOwnProperty(value) && value !== 'scrollPosition' && value !== 'increment'){

							// Set Tween Boundaries once so we know the lowest and highest scroll values for excess scrolls.

							//TODO this is not working
							if(!this._tweenBoundariesSet){
								console.log('Invoked for: ', this);
								this._setTweenBoundaries(this.tweenBreakpoints[this.tweenBreakpoints.length - 1], this._finalTween);
								this._setTweenBoundaries(this.tweenBreakpoints[0], this._zeroTween);
								this._tweenBoundariesSet  = true;
							}

							tweenState[value] = this._activeTweenPair[0][value] + (this._activeTweenPair[0].increment[value] * ( window.pageYOffset  - this._activeTweenPair[0].scrollPosition));
						}
					}

					this._tweenBoundariesSet = true;

					TweenLite.to(this.elem, 0.016, tweenState);

				}

				if(window.pageYOffset >=  this.tweenBreakpoints[this.tweenBreakpoints.length -1].scrollPosition && this._isTweenable){
					console.log('FINAL TWEENED!');
					this.isTweenable = false;
					TweenLite.to(this.elem, 0.016, this._finalTween);

				}

				if(window.pageYOffset < 0 && this._isTweenable){
					this._isTweenable = false;
					TweenLite.to(this.elem, 0.016, this._zeroTween);
				}

				if(window.pageYOffset >= this.tweenBreakpoints[this.tweenBreakpoints.length - 1].scrollPosition && !this._persist){
					this._dereferenceNullElement();
				}

			},

			_setTweenBoundaries : function(src, target){

				for(var value in src){

					if(src.hasOwnProperty(value) && value !== 'increment' && value !== 'scrollPosition'){
						if(typeof src[value] === 'object') this._setTweenBoundaries(src[value], target[value]);
						target[value] = src[value];
					}
				}

				},

			// Checks to be sure that we haven't already defined a state for the position
			// TODO add option for tweenElement to overwrite previous tweenState if desired
			_tweenPositionDefined  : function(scrollPosition){

				for(var i = 0; i < this.tweenBreakpoints.length; i++){
					var currentTween = this.tweenBreakpoints[i];
					if(currentTween[scrollPosition] !== undefined) return true;
				}

				return false;
			},

			_dereferenceNullElement : function(){
				TweenLite.to(this.elem, 0.016, this.finalTween);
				scrollElements.splice(scrollElements.indexOf(this), 1);
				console.log('Removed reference');
			},

			_getTweenBreakpoints : function(){
				return this.tweenBreakpoints;
			}

		};

	var scrollObject  =  function(selector, options) {

		var tweenElement = Object.create(tweenElementPrototype);

		// DOM element being Tween'd
		tweenElement.elem = document.querySelector ? document.querySelector(selector) : false;
		if(!tweenElement.elem){ throw new Error('CSS  Selector invalid or querySelector() not supported in your browser')};

		tweenElement.tweenBreakpoints = [];
		tweenElement.cache = {};

		if(options) tweenElement._options =  options;

		tweenElement._persist             = true;
		tweenElement._zeroTween          = {};
		tweenElement._finalTween         = {};
		tweenElement._isTweenable        = true;
		tweenElement.initialTweenPairSet = false;
		tweenElement._tweenBoundariesSet = false;
		tweenElement._activeTweenPair    = [];

		scrollElements.push(tweenElement);
		return tweenElement;

	};

	scrollObject._getScrollElements        = function(){  return scrollElements           };
	scrollObject._getTweenableElements     = function(){  return tweenableElements        };

	// ONE EVENT LISTENER TO RULE THEM ALL!

	window.addEventListener('scroll', function(){
		for(var i = 0; i < scrollElements.length; i++){
			scrollElements[i]._animateTweens.apply(scrollElements[i]);
		}
	});

	var initalParse = window.addEventListener('DOMContentLoaded', function(){
		for(var i = 0; i < scrollElements.length; i++){
			scrollElements[i]._getActiveTweenPair.apply(scrollElements[i]);
			scrollElements[i]._animateTweens.apply(scrollElements[i]);
		}
	});

	return scrollObject;

})();

/*

 Need function that decides which tweenBreakpoint is active. Should be easy enough to
 use the tweenBreakpoint array since it will always be ordered from least to greatest

 */

<commit_msg>fixed bug with ._isTweenable typo<commit_after>

var scrollJS = (function(){

	var scrollElements        = [],
		tweenableElements     = [],

		tweenElementPrototype = {

			// Used to set tween positions

			at : function(scrollPosition, scrollState){

				if(typeof scrollPosition !== "number" || scrollPosition < 0) throw new Error('Scroll position must be a number greater than 0');
				if(this._tweenPositionDefined(scrollPosition)) throw new Error('Scroll position already defined for this element');
				if(Object.keys(scrollState).length === 0){ throw new Error('Scroll state must have at least one value')  };

				var breakpoint = {};
				for(value in scrollState){
					if(scrollState.hasOwnProperty(value)){
						breakpoint[value] = scrollState[value];
					}
				}

				breakpoint['scrollPosition'] = scrollPosition;

				this.tweenBreakpoints.push(breakpoint);

				this._updateTweens();
			},

			// Used in _updateTweens to ensure that the tweenBreakpoint elements are in order

			_sortCompareFunction : function(first, second){
				if(first.scrollPosition < second.scrollPosition) return -1;
				if(first.scrollPosition > second.scrollPosition) return 1;
				return 0;

			},

			_updateTweens : function(){

				// Sort the breakpoints so we have them in order
				this.tweenBreakpoints = this.tweenBreakpoints.sort(this._sortCompareFunction);

				//for(var value in this.tweenBreakpoints[0]){
				//	if(this.tweenBreakpoints[0].hasOwnProperty(value) && value !== 'increment' && value !== 'scrollPosition'){
				//		this.zeroTween[value] = this.tweenBreakpoints[0][value];
				//	}
				//
				//}

				for(var i = 0; i < this.tweenBreakpoints.length; i++){

					if(this.tweenBreakpoints[i + 1]){

						this._calculateTweenIncrement(this.tweenBreakpoints[i], this.tweenBreakpoints[i + 1])
					}
				}
			},

			_calculateTweenIncrement : function(firstTween, secondTween){

				var totalTraversal = secondTween.scrollPosition - firstTween.scrollPosition;

				// We always store the increment values on the first object
				if(!firstTween.increment) firstTween.increment = {};

				for(var type in firstTween){
					if(firstTween.hasOwnProperty(type) && type !== 'scrollPosition' && type !== 'increment' && secondTween[type] === undefined){
						console.log(type);
						secondTween[type] = firstTween[type];
					}

				}

				//TODO if value is in secondTween but not in firstTween, set value to 0 for firstTween
				for(var value in secondTween){

					if(secondTween.hasOwnProperty(value) && value !== 'increment'){
						firstTween.increment[value] = (secondTween[value] - firstTween[value]) / totalTraversal;
					}

				}

			},

			//TODO set a value on the tweenElement that we can check quickly
			//TODO  so that we know if a new tweenPair is needed

			_getActiveTweenPair: function(){

				var offset = window.pageYOffset;
				if(offset < this.cache.activeTweenPairUpperBound && offset > this.cache.activeTweenPairLowerBound) return;

				var breakpoints = this.tweenBreakpoints.map(function(value){ return value.scrollPosition });

				if(!this.initialTweenPairSet){

					if(breakpoints[breakpoints.length - 1] < offset){
						this._activeTweenPair.splice(0);
						this._activeTweenPair.push(this.tweenBreakpoints[breakpoints.length - 2], this.tweenBreakpoints[breakpoints.length - 1]);
						this._initialTweenPairSet = true;
						return;
					}

				}

				for(var i = 0; i < breakpoints.length; i++){
					if((offset > breakpoints[i] || breakpoints[i] === 0) && offset < breakpoints[i + 1]){
						this._activeTweenPair.splice(0);
						this._activeTweenPair.push(this.tweenBreakpoints[i], this.tweenBreakpoints[i+1]);
						this.cache['activeTweenPairUpperBound'] = breakpoints[i + 1];
						this.cache['activeTweenPairLowerBound'] = breakpoints[i];
						return;
					}
				}

			},

			_animateTweens : function(){

				//TODO gix issue with activeTweenPair not loading when the page is loaded at an offset > 0
				this._getActiveTweenPair();

				if(window.pageYOffset <= this._activeTweenPair[1].scrollPosition && window.pageYOffset >= 0){
					this._isTweenable = true;

					var tweenState = {};

					for(var value in this._activeTweenPair[1]){

						if(this._activeTweenPair[1].hasOwnProperty(value) && value !== 'scrollPosition' && value !== 'increment'){

							// Set Tween Boundaries once so we know the lowest and highest scroll values for excess scrolls.

							//TODO this is not working
							if(!this._tweenBoundariesSet){
								console.log('Invoked for: ', this);
								this._setTweenBoundaries(this.tweenBreakpoints[this.tweenBreakpoints.length - 1], this._finalTween);
								this._setTweenBoundaries(this.tweenBreakpoints[0], this._zeroTween);
								this._tweenBoundariesSet  = true;
							}

							tweenState[value] = this._activeTweenPair[0][value] + (this._activeTweenPair[0].increment[value] * ( window.pageYOffset  - this._activeTweenPair[0].scrollPosition));
						}
					}

					this._tweenBoundariesSet = true;

					TweenLite.to(this.elem, 0.016, tweenState);

				}

				if(window.pageYOffset >=  this.tweenBreakpoints[this.tweenBreakpoints.length -1].scrollPosition && this._isTweenable){
					console.log('FINAL TWEENED!');
					this._isTweenable = false;
					TweenLite.to(this.elem, 0.016, this._finalTween);

				}

				if(window.pageYOffset < 0 && this._isTweenable){
					this._isTweenable = false;
					TweenLite.to(this.elem, 0.016, this._zeroTween);
				}

				if(window.pageYOffset >= this.tweenBreakpoints[this.tweenBreakpoints.length - 1].scrollPosition && !this._persist){
					this._dereferenceNullElement();
				}

			},

			_setTweenBoundaries : function(src, target){

				for(var value in src){

					if(src.hasOwnProperty(value) && value !== 'increment' && value !== 'scrollPosition'){
						if(typeof src[value] === 'object') this._setTweenBoundaries(src[value], target[value]);
						target[value] = src[value];
					}
				}

				},

			// Checks to be sure that we haven't already defined a state for the position
			// TODO add option for tweenElement to overwrite previous tweenState if desired
			_tweenPositionDefined  : function(scrollPosition){

				for(var i = 0; i < this.tweenBreakpoints.length; i++){
					var currentTween = this.tweenBreakpoints[i];
					if(currentTween[scrollPosition] !== undefined) return true;
				}

				return false;
			},

			_dereferenceNullElement : function(){
				TweenLite.to(this.elem, 0.016, this.finalTween);
				scrollElements.splice(scrollElements.indexOf(this), 1);
				console.log('Removed reference');
			},

			_getTweenBreakpoints : function(){
				return this.tweenBreakpoints;
			}

		};

	var scrollObject  =  function(selector, options) {

		var tweenElement = Object.create(tweenElementPrototype);

		// DOM element being Tween'd
		tweenElement.elem = document.querySelector ? document.querySelector(selector) : false;
		if(!tweenElement.elem){ throw new Error('CSS  Selector invalid or querySelector() not supported in your browser')};

		tweenElement.tweenBreakpoints = [];
		tweenElement.cache = {};

		if(options) tweenElement._options =  options;

		tweenElement._persist             = true;
		tweenElement._zeroTween          = {};
		tweenElement._finalTween         = {};
		tweenElement._isTweenable        = true;
		tweenElement.initialTweenPairSet = false;
		tweenElement._tweenBoundariesSet = false;
		tweenElement._activeTweenPair    = [];

		scrollElements.push(tweenElement);
		return tweenElement;

	};

	scrollObject._getScrollElements        = function(){  return scrollElements           };
	scrollObject._getTweenableElements     = function(){  return tweenableElements        };

	// ONE EVENT LISTENER TO RULE THEM ALL!

	window.addEventListener('scroll', function(){
		for(var i = 0; i < scrollElements.length; i++){
			scrollElements[i]._animateTweens.apply(scrollElements[i]);
		}
	});

	var initalParse = window.addEventListener('DOMContentLoaded', function(){
		for(var i = 0; i < scrollElements.length; i++){
			scrollElements[i]._getActiveTweenPair.apply(scrollElements[i]);
			scrollElements[i]._animateTweens.apply(scrollElements[i]);
		}
	});

	return scrollObject;

})();

/*

 Need function that decides which tweenBreakpoint is active. Should be easy enough to
 use the tweenBreakpoint array since it will always be ordered from least to greatest

 */

<|endoftext|>


<commit_before>var vk = require('./index')
var scalar = vk.scalar
var vector2d = vk.vector2d
var vector3d = vk.vector3d
var util = vk.util

function exScalar() {
  var keyframes = [{
    stop: 0,
    value: 0
  }, {
    stop: 0.5,
    value: 1
  }, {
    stop: 1,
    value: 0
  }]

  console.log('linear   (t=0):',
    scalar.keyframeInterpolate(keyframes, 0))

  console.log('linear (t=0.5):',
    scalar.keyframeInterpolate(keyframes, 0.5))

  console.log('linear   (t=1):',
    scalar.keyframeInterpolate(keyframes, 1))

  console.log('linear (t=0.1):',
    scalar.keyframeInterpolate(keyframes, 0.1))

  console.log('smooth (t=0.1):',
    scalar.keyframeInterpolate(keyframes, 0.1, 'smooth'))
}

function exVector2d() {
  var keyframes = [{
    stop: 0,
    value: [0, 100]
  }, {
    stop: 0.5,
    value: [100, 100]
  }, {
    stop: 1,
    value: [100, 0]
  }]

  console.log('linear   (t=0):',
    vector2d.keyframeInterpolate(keyframes, 0))

  console.log('linear (t=0.5):',
    vector2d.keyframeInterpolate(keyframes, 0.5))

  console.log('linear   (t=1):',
    vector2d.keyframeInterpolate(keyframes, 1))

  console.log('linear (t=0.1):',
    vector2d.keyframeInterpolate(keyframes, 0.1))

  console.log('smooth (t=0.1):',
    vector2d.keyframeInterpolate(keyframes, 0.1, 'smooth'))
}

function exVector3d() {
  var keyframes = [{
    stop: 0,
    value: [0, 0, 255]
  }, {
    stop: 0.5,
    value: [0, 255, 0]
  }, {
    stop: 1,
    value: [0, 0, 255]
  }]

  var result = vector3d.keyframeInterpolate(keyframes, 0.25)
  console.log('\nvector    (t=0.25):', result)
  console.log('rgb color (t=0.25):', util.vector3dToRgb(result))
  console.log('hex color (t=0.25):', util.vector3dToHex(result))

  result = vector3d.keyframeInterpolate(keyframes, 0.5)
  console.log('\vvector    (t=0.5):', result)
  console.log('rgb color (t=0.5):', util.vector3dToRgb(result))
  console.log('hex color (t=0.5):', util.vector3dToHex(result))

  result = vector3d.keyframeInterpolate(keyframes, 0.9)
  console.log('\nvector    (t=0.9):', result)
  console.log('rgb color (t=0.9):', util.vector3dToRgb(result))
  console.log('hex color (t=0.9):', util.vector3dToHex(result))
}

function exCustom() {
  var alpha = {

    zero() {
      return '*'
    },

    linearInterpolate(a, b, t) {
      return vk.scalar.linearInterpolate(a.charCodeAt(0), b.charCodeAt(0), t)
    },

    smoothInterpolate(a, b, t) {
      return vk.scalar.smoothInterpolate(a.charCodeAt(0), b.charCodeAt(0), t)
    },

    keyframeInterpolate(keyframes, t, timing='linear', lib=alpha) {
      var result = vk.scalar.keyframeInterpolate(keyframes, t, timing, lib)
      return String.fromCharCode(Math.round(result))
    }
  }

  var keyframes = [{
    stop: 0,
    value: 'a'
  }, {
    stop: 0.5,
    value: 'z'
  }, {
    stop: 1,
    value: 'a'
  }]

  console.log('linear   (t=0):',
    alpha.keyframeInterpolate(keyframes, 0, 'linear'))

  console.log('linear (t=0.5):',
    alpha.keyframeInterpolate(keyframes, 0.5, 'linear'))

  console.log('linear   (t=1):',
    alpha.keyframeInterpolate(keyframes, 1, 'linear'))

  console.log('linear (t=0.1):',
    alpha.keyframeInterpolate(keyframes, 0.1, 'linear'))

  console.log('smooth (t=0.1):',
    alpha.keyframeInterpolate(keyframes, 0.1, 'smooth'))
}

console.log('\nscalar')
console.log('--------')
exScalar()

console.log('\nvector2d')
console.log('--------')
exVector2d()

console.log('\nvector3d')
console.log('--------')
exVector3d()

console.log('\ncustom')
console.log('------')
exCustom()

console.log()

var keyframeSearch = require('./index').search.keyframeSearch

// var list = [
//   // {stop: 0},
//   {stop: 1},
//   {stop: 2},
//   {stop: 3},
//   {stop: 4},
//   {stop: 5},
//   {stop: 6},
//   {stop: 7},
//   {stop: 8},
//   {stop: 9},
//   {stop: 10},
//   // {stop: 11}
// ]

let list = []
for (let i = 0; i < 3; i++) {
  list.push({stop: Math.random()})
}
list = list.sort((a, b) => a.stop - b.stop)

console.log('low, high:', list[0], list[list.length-1])
let time = Math.random()
console.log('time:', time)
var result = keyframeSearch(list, time)
console.log(result)

<commit_msg>Restore<commit_after>var vk = require('./index')
var scalar = vk.scalar
var vector2d = vk.vector2d
var vector3d = vk.vector3d
var util = vk.util

function exScalar() {
  var keyframes = [{
    stop: 0,
    value: 0
  }, {
    stop: 0.5,
    value: 1
  }, {
    stop: 1,
    value: 0
  }]

  console.log('linear   (t=0):',
    scalar.keyframeInterpolate(keyframes, 0))

  console.log('linear (t=0.5):',
    scalar.keyframeInterpolate(keyframes, 0.5))

  console.log('linear   (t=1):',
    scalar.keyframeInterpolate(keyframes, 1))

  console.log('linear (t=0.1):',
    scalar.keyframeInterpolate(keyframes, 0.1))

  console.log('smooth (t=0.1):',
    scalar.keyframeInterpolate(keyframes, 0.1, 'smooth'))
}

function exVector2d() {
  var keyframes = [{
    stop: 0,
    value: [0, 100]
  }, {
    stop: 0.5,
    value: [100, 100]
  }, {
    stop: 1,
    value: [100, 0]
  }]

  console.log('linear   (t=0):',
    vector2d.keyframeInterpolate(keyframes, 0))

  console.log('linear (t=0.5):',
    vector2d.keyframeInterpolate(keyframes, 0.5))

  console.log('linear   (t=1):',
    vector2d.keyframeInterpolate(keyframes, 1))

  console.log('linear (t=0.1):',
    vector2d.keyframeInterpolate(keyframes, 0.1))

  console.log('smooth (t=0.1):',
    vector2d.keyframeInterpolate(keyframes, 0.1, 'smooth'))
}

function exVector3d() {
  var keyframes = [{
    stop: 0,
    value: [0, 0, 255]
  }, {
    stop: 0.5,
    value: [0, 255, 0]
  }, {
    stop: 1,
    value: [0, 0, 255]
  }]

  var result = vector3d.keyframeInterpolate(keyframes, 0.25)
  console.log('\nvector    (t=0.25):', result)
  console.log('rgb color (t=0.25):', util.vector3dToRgb(result))
  console.log('hex color (t=0.25):', util.vector3dToHex(result))

  result = vector3d.keyframeInterpolate(keyframes, 0.5)
  console.log('\vvector    (t=0.5):', result)
  console.log('rgb color (t=0.5):', util.vector3dToRgb(result))
  console.log('hex color (t=0.5):', util.vector3dToHex(result))

  result = vector3d.keyframeInterpolate(keyframes, 0.9)
  console.log('\nvector    (t=0.9):', result)
  console.log('rgb color (t=0.9):', util.vector3dToRgb(result))
  console.log('hex color (t=0.9):', util.vector3dToHex(result))
}

function exCustom() {
  var alpha = {

    zero() {
      return '*'
    },

    linearInterpolate(a, b, t) {
      return vk.scalar.linearInterpolate(a.charCodeAt(0), b.charCodeAt(0), t)
    },

    smoothInterpolate(a, b, t) {
      return vk.scalar.smoothInterpolate(a.charCodeAt(0), b.charCodeAt(0), t)
    },

    keyframeInterpolate(keyframes, t, timing='linear', lib=alpha) {
      var result = vk.scalar.keyframeInterpolate(keyframes, t, timing, lib)
      return String.fromCharCode(Math.round(result))
    }
  }

  var keyframes = [{
    stop: 0,
    value: 'a'
  }, {
    stop: 0.5,
    value: 'z'
  }, {
    stop: 1,
    value: 'a'
  }]

  console.log('linear   (t=0):',
    alpha.keyframeInterpolate(keyframes, 0, 'linear'))

  console.log('linear (t=0.5):',
    alpha.keyframeInterpolate(keyframes, 0.5, 'linear'))

  console.log('linear   (t=1):',
    alpha.keyframeInterpolate(keyframes, 1, 'linear'))

  console.log('linear (t=0.1):',
    alpha.keyframeInterpolate(keyframes, 0.1, 'linear'))

  console.log('smooth (t=0.1):',
    alpha.keyframeInterpolate(keyframes, 0.1, 'smooth'))
}

console.log('\nscalar')
console.log('--------')
exScalar()

console.log('\nvector2d')
console.log('--------')
exVector2d()

console.log('\nvector3d')
console.log('--------')
exVector3d()

console.log('\ncustom')
console.log('------')
exCustom()

console.log()

// var tweenSearch = require('./index').search.tweenSearch

// var list = [
//   {stop: 1},
//   {stop: 2},
//   {stop: 3},
//   {stop: 4},
//   {stop: 5},
//   {stop: 6},
//   {stop: 7},
//   {stop: 8},
//   {stop: 9},
//   {stop: 10},
// ]

// let list = []
// for (let i = 0; i < 9; i++) {
//   list.push({stop: Math.random()})
// }
// list = list.sort((a, b) => a.stop - b.stop)

// console.log('low, high:', list[0], list[list.length-1])
// let time = 4 // Math.random()
// console.log('time:', time)
// var result = tweenSearch(list, time)
// console.log(result)
<|endoftext|>


<commit_before>import React from 'react';
import {Dimensions, View} from 'react-native';
import {NavigationMotion, spring} from 'navigation-react-native';

export default ({stateNavigator}) => (
  <NavigationMotion
    startStateKey="sceneNorth"
    unmountedStyle={state => state.unmountedStyle()}
    mountedStyle={state => state.mountedStyle()}
    crumbStyle={state => state.crumbStyle()}
    style={{flex: 1}}
    stateNavigator={stateNavigator}>
    {({translateX  = 0, translateY = 0}, scene, url) => (
      <View
        key={url}
        style={{
          position: 'absolute',
          left: 0,
          right: 0,
          top: 0,
          bottom: 0,
          transform: [
            {translateX: Dimensions.get('window').width * translateX},
            {translateY: Dimensions.get('window').height * translateY},
          ]
        }}>
        {scene}
      </View>
    )}
  </NavigationMotion>
);
<commit_msg>Removed redundant spring import<commit_after>import React from 'react';
import {Dimensions, View} from 'react-native';
import {NavigationMotion} from 'navigation-react-native';

export default ({stateNavigator}) => (
  <NavigationMotion
    startStateKey="sceneNorth"
    unmountedStyle={state => state.unmountedStyle()}
    mountedStyle={state => state.mountedStyle()}
    crumbStyle={state => state.crumbStyle()}
    style={{flex: 1}}
    stateNavigator={stateNavigator}>
    {({translateX  = 0, translateY = 0}, scene, url) => (
      <View
        key={url}
        style={{
          position: 'absolute',
          left: 0,
          right: 0,
          top: 0,
          bottom: 0,
          transform: [
            {translateX: Dimensions.get('window').width * translateX},
            {translateY: Dimensions.get('window').height * translateY},
          ]
        }}>
        {scene}
      </View>
    )}
  </NavigationMotion>
);
<|endoftext|>


<commit_before>var vue = new Vue({
	el:'#lucky-draw',
	data:{
		players: [],
		rewards: [],
		buffer: [] ,
		history: [],
		rewards_history:[],
		Img : [],
		currentPlayer :0 ,
		form:{
			Name: ''
		},
		isGameStart : false ,
		isGameFinished: false ,
		showRewardName: '',
		showRewardImg:'',
		isImgOpened: false ,
		isFirstTime: true
	},

	methods : {
		addPlayer:function(){
			if(this.checkForm()){
				this.players.push({
					Name: this.form.Name,
					isRewarded : false ,
					rewardId : -1 ,
				});
				this.clearForm();
			}
		},
		checkForm:function(){
			if (this.form.Name.length >0){
				return true;
			}
			return false ;
		},
		clearForm:function(){
			this.form.Name = '' ;
		},
		startBtn:function(){
			this.isGameStart = true ;
			if(this.isFirstTime){
				this.rewards_history.push({rewardId:0,
				"name" : "None",
				"img_url" : "img/rewards/None.png"});
				this.isFirstTime = false;
				for (var i = 0; i < this.rewards.length; i++) {
					this.rewards_history.push(this.rewards[i]);
				}
			}
			this.addEmptyReward(this.buffer);
			for (var i = 0; i < this.rewards.length; i++) {
				this.buffer.push(this.rewards[i]);
			}
			for (var i = 0; i < this.players.length; i++) {
				console.log(this.buffer);
				var rand = Math.floor(Math.random()*this.buffer.length);
				var img = $('');
				this.buffer.splice(rand,1);
				img.attr('src','img/close.png');
				img.attr('onmouseover', 'this.src="img/close-hover.png"');
		       	img.attr('onmouseout', 'this.src="img/close.png"');
		       	img.attr('width', '320');
		       	img.attr('height', '180');
		       	// img.attr('data-toggle','model');
		       	// img.attr('data-target','#mymodal2');
		       	// data-toggle="modal" data-target="#myModal" v-if="!isGameStart"
		       	img.attr('onclick', 'OnClick(this)');
		       	img.appendTo('#reward-drawers');
				console.log(img);
				this.Img.push(img);

				// var element = $('#reward-drawers').append(img);
				// this.$compile(element.get(0));
				// console.log(img);

				}
		},
		addEmptyReward:function(reward){
			if(this.players.length > 5 ){
				console.log(this.players);
				for (var i = 0; i < this.players.length-5; i++) {
					console.log('ss');
					reward.push({
						"rewardId":0,
						"name" : "None",
						"img_url" : "img/rewards/None.png"
					});
				}
			}
		},
		getReward:function(img) {
			this.removeAtt(img);
			var rewardId = img.id.substring(7);
			// console.log(img);
			this.showRewardImg = this.getRewardImg(rewardId);
			this.showRewardName = this.getRewardName(rewardId);
			$('#reward-'+rewardId).attr('src',this.showRewardImg);
			this.players[this.currentPlayer].isRewarded = true ;
			this.players[this.currentPlayer].rewardId = rewardId;
			this.isImgOpened = true ;
			this.history.push(this.players[this.currentPlayer]);
			console.log(rewardId);
			setTimeout(function(){
    				alert(vue.showRewardName);
				}, 100);
			if(this.currentPlayer < this.players.length-1){
				this.currentPlayer++;
			}else{
				setTimeout(function(){
    				vue.end();
				}, 2000);

			}

			// body...
		},
		removeAtt:function(img){
			img.removeAttribute("onmouseover");
			img.removeAttribute("onmouseout");
			img.removeAttribute("onclick");
		},

		getPlayerName:function(index){
			return this.players[index].Name;
		},

		getRewardImg:function(rewardId){
			for (var i = 0; i < this.rewards_history.length; i++) {
				if(this.rewards_history[i].rewardId == rewardId){
					return this.rewards_history[i].img_url;
				}
			}
		},
		getRewardName(rewardId){
			for (var i = 0; i < this.rewards_history.length; i++) {
				console.log(this.rewards_history[i].name);
			}
			for (var i = 0; i < this.rewards_history.length; i++) {
				if(this.rewards_history[i].rewardId == rewardId){
					if(this.rewards_history[i].name== "None"){
						return "!!Unlucky Try Agiain Next Time!!";
					}
					console.log(i);
					return "You Get "+this.rewards_history[i].name+" !!";
				}
			}
		},
		getPureRewardName(rewardId){
			for (var i = 0; i < this.rewards_history.length; i++) {
				if(this.rewards_history[i].rewardId == rewardId){
					return this.rewards_history[i].name;
				}
			}
			return '-' ;
		},
		end:function() {
			this.isGameFinished = true ;
		},
		replay:function(){
			//Clear all element except history
			this.players = [] ;
			this.Img = [] ;
			this.buffer = [] ;
			this.currentPlayer = 0 ;
			this.isGameStart =  false ;
			this.isGameFinished =  false ;
			this.showRewardName =  '';
			this.showRewardImg = '' ;
			this.isImgOpened = false ;
		}

	},

	computed :{

		getCurrentPlayer: function(){
			return this.getPlayerName(this.currentPlayer);
		},

		isGameReady: function(){
			if (this.players.length >= 5){
				return true;
			}
			return false ;
		}

	},

	mounted: function () {
		 $.ajax({
            url: 'reward.config.json',
            method: 'GET',
            context: this,
            success: function (data) {
                this.rewards = data;
				// this.rewards_history = data;
            },
            error: function (error) {
                alert(JSON.stringify(error));
            }
        });

				// this.players.push({
				// 	Name : "act",
				// 	isRewarded : false,
				// 	rewardId : -1
				// }),
				// this.players.push({
				// 	Name : "za",
				// 	isRewarded : false,
				// 	rewardId : -1
				// }),
				// this.players.push({
				// 	Name : "007",
				// 	isRewarded : false,
				// 	rewardId : -1
				// }),
				// this.players.push({
				// 	Name : "eieiza",
				// 	isRewarded : false,
				// 	rewardId : -1
				// }),
				// this.players.push({
				// 	Name : "555+",
				// 	isRewarded : false,
				// 	rewardId : -1
				// })
	},
	filters:{
		isEmpty:function(value){
			// console.log(this.players);
			if(value == 'None'){
				return '-'
			}
			return value;
		}
	}

});

function OnClick(element){
	vue.getReward(element);
}
<commit_msg>Fixed Bugs Lab 9<commit_after>var vue = new Vue({
	el:'#lucky-draw',
	data:{
		players: [],
		rewards: [],
		buffer: [] ,
		history: [],
		rewards_history:[],
		Img : [],
		currentPlayer :0 ,
		form:{
			Name: ''
		},
		isGameStart : false ,
		isGameFinished: false ,
		showRewardName: '',
		showRewardImg:'',
		isImgOpened: false ,
		isFirstTime: true
	},

	methods : {
		addPlayer:function(){
			if(this.checkForm()){
				this.players.push({
					Name: this.form.Name,
					isRewarded : false ,
					rewardId : -1 ,
				});
				this.clearForm();
			}
		},
		checkForm:function(){
			if (this.form.Name.length >0){
				return true;
			}
			return false ;
		},
		clearForm:function(){
			this.form.Name = '' ;
		},
		startBtn:function(){
			this.isGameStart = true ;
			if(this.isFirstTime){
				this.rewards_history.push({rewardId:0,
				"name" : "None",
				"img_url" : "img/rewards/None.png"});
				this.isFirstTime = false;
				for (var i = 0; i < this.rewards.length; i++) {
					this.rewards_history.push(this.rewards[i]);
				}
			}
			this.addEmptyReward(this.buffer);
			for (var i = 0; i < this.rewards.length; i++) {
				this.buffer.push(this.rewards[i]);
			}
			for (var i = 0; i < this.players.length; i++) {
				console.log(this.buffer);
				var rand = Math.floor(Math.random()*this.buffer.length);
				var img = $('');
				this.buffer.splice(rand,1);
				img.attr('src','img/close.png');
				img.attr('onmouseover', 'this.src="img/close-hover.png"');
		       	img.attr('onmouseout', 'this.src="img/close.png"');
		       	img.attr('width', '320');
		       	img.attr('height', '180');
		       	// img.attr('data-toggle','model');
		       	// img.attr('data-target','#mymodal2');
		       	// data-toggle="modal" data-target="#myModal" v-if="!isGameStart"
		       	img.attr('onclick', 'OnClick(this)');
		       	img.appendTo('#reward-drawers');
				console.log(img);
				this.Img.push(img);

				// var element = $('#reward-drawers').append(img);
				// this.$compile(element.get(0));
				// console.log(img);

				}
		},
		addEmptyReward:function(reward){
			if(this.players.length > 5 ){
				console.log(this.players);
				for (var i = 0; i < this.players.length-5; i++) {
					console.log('ss');
					reward.push({
						"rewardId":i+this.players.length,
						"name" : "None",
						"img_url" : "img/rewards/None.png"
					});
				}
			}
		},
		getReward:function(img) {
			this.removeAtt(img);
			var rewardId = img.id.substring(7);
			// console.log(img);
			this.showRewardImg = this.getRewardImg(rewardId);
			this.showRewardName = this.getRewardName(rewardId);
			$('#reward-'+rewardId).attr('src',this.showRewardImg);
			this.players[this.currentPlayer].isRewarded = true ;
			this.players[this.currentPlayer].rewardId = rewardId;
			this.isImgOpened = true ;
			this.history.push(this.players[this.currentPlayer]);
			setTimeout(function(){
    				alert(vue.showRewardName);
				}, 100);
			if(this.currentPlayer < this.players.length-1){
				this.currentPlayer++;
			}else{
				setTimeout(function(){
    				vue.end();
				}, 2000);

			}

			// body...
		},
		removeAtt:function(img){
			img.removeAttribute("onmouseover");
			img.removeAttribute("onmouseout");
			img.removeAttribute("onclick");
		},

		getPlayerName:function(index){
			return this.players[index].Name;
		},

		getRewardImg:function(rewardId){
			if(rewardId>5){
				return this.rewards_history[0].img_url;
			}
			for (var i = 1; i < this.rewards_history.length; i++) {

				if(this.rewards_history[i].rewardId == rewardId){
					// console.log(this.rewards_history[i].img_url);
					return this.rewards_history[i].img_url;
				}
			}
		},
		getRewardName(rewardId){
			// for (var i = 0; i < this.rewards_history.length; i++) {
			// 	console.log(this.rewards_history[i].name);
			// }
			if(rewardId>5){
				return "Unlucky Try Again Next Time!!";
			}
			for (var i = 1 ;i < this.rewards_history.length; i++) {
				if(this.rewards_history[i].rewardId == rewardId){
					return "You Get "+this.rewards_history[i].name+" !!";
				}
			}
		},
		getPureRewardName(rewardId){
			for (var i = 0; i < this.rewards_history.length; i++) {
				if(this.rewards_history[i].rewardId == rewardId){
					return this.rewards_history[i].name;
				}
			}
			return '-' ;
		},
		end:function() {
			this.isGameFinished = true ;
		},
		replay:function(){
			//Clear all element except history
			this.players = [] ;
			this.Img = [] ;
			this.buffer = [] ;
			this.currentPlayer = 0 ;
			this.isGameStart =  false ;
			this.isGameFinished =  false ;
			this.showRewardName =  '';
			this.showRewardImg = '' ;
			this.isImgOpened = false ;
		}

	},

	computed :{

		getCurrentPlayer: function(){
			return this.getPlayerName(this.currentPlayer);
		},

		isGameReady: function(){
			if (this.players.length >= 5){
				return true;
			}
			return false ;
		}

	},

	mounted: function () {
		 $.ajax({
            url: 'reward.config.json',
            method: 'GET',
            context: this,
            success: function (data) {
                this.rewards = data;
				// this.rewards_history = data;
            },
            error: function (error) {
                alert(JSON.stringify(error));
            }
        });

				// this.players.push({
				// 	Name : "act",
				// 	isRewarded : false,
				// 	rewardId : -1
				// }),
				// this.players.push({
				// 	Name : "za",
				// 	isRewarded : false,
				// 	rewardId : -1
				// }),
				// this.players.push({
				// 	Name : "007",
				// 	isRewarded : false,
				// 	rewardId : -1
				// }),
				// this.players.push({
				// 	Name : "eieiza",
				// 	isRewarded : false,
				// 	rewardId : -1
				// }),
				// this.players.push({
				// 	Name : "555+",
				// 	isRewarded : false,
				// 	rewardId : -1
				// })
	},
	filters:{
		isEmpty:function(value){
			// console.log(this.players);
			if(value == 'None'){
				return '-'
			}
			return value;
		}
	}

});

function OnClick(element){
	vue.getReward(element);
}
<|endoftext|>