<commit_before>
google.load('search', '1');

function player_init(){
  var width = (($(document).width())>1280? 1280: 1280);
  $('body').css('width', width);

  $('#player_wrapper #album_artwork').attr('src', '/images/nothumb.png');
  google.search.Search.getBranding('google_branding');
}

function loadMusic(files) {
  var musicFiles = _(files).select(function (file) {
    var path = file.webkitRelativePath || file.mozFullPath;
    var fileName = file.fileName;
    var size = file.fileSize;
    var lpath = path.toLowerCase();
    return !/\.$/.test(lpath) &&
      (/\.mp3$/.test(lpath)) ||
      (/\.ogg$/.test(lpath)) ||
      (/\.m4a$/.test(lpath))
  });

  var total = musicFiles.length, progress = 0;

  function incProgress() {
    progress++;
    $('#addmusic').html(progress+' / '+total);
    if(progress == total) {
      $.app.Storage.save();
    } else {
      newMuFile(musicFiles[progress]);
    }
  }

  $.app.liveFiles = {};

  function newMuFile(f) {
    $.app.liveFiles[f.webkitRelativePath] = f;
    var muFile = new $.app.MuFile(f, incProgress);
  }

  newMuFile(musicFiles[progress]);
}

function getPrettySongName(muFile) {
  var name = muFile.name.length > muFile.title.length ?
    muFile.name : muFile.title;
  return name.replace(/\.\w+$/,'');
}

function getYoutubeSearchURL(muFile) {
  var name = getPrettySongName(muFile);
  return 'http://www.youtube.com/results?search_query='+
    name.split(/\s+/).join('+')+'+'+
    muFile.artist.split(/\s+/).join('+');
}

function getLyricsSearchURL(muFile) {
  var name = getPrettySongName(muFile);
  return 'http://www.google.com/search?q='+
    name.split(/\s+/).join('+')+'+'+
    muFile.artist.split(/\s+/).join('+')+'+lyrics';
}

function getArtistWikipediaURL(muFile) {
  return 'http://en.wikipedia.org/w/index.php?search='+
          muFile.artist.split(/\s+/).join('+');
}

function getAmazonLink(muFile) {
  return 'http://www.amazon.com/s?ie=UTF8&x=0&ref_=nb_sb_noss&y=0&field-keywords='+encodeURI(muFile.artist)+'&url=search-alias%3Ddigital-music&_encoding=UTF8&tag=myfreq-20&linkCode=ur2&camp=1789&creative=390957'
}

function getSongEntryHtml(muFile, asSearchResult) {
  var name = getPrettySongName(muFile);
  var entryHTML = '
'+
    '  '+
    ''+getPrettySongName(muFile)+''+
    '  '+
    ''+muFile.album+''+
    '  '+
    ''+muFile.artist+''+
    '  '+
    (asSearchResult ?
      '+' :
      '-'+
      '>')+
  '
';
  var entry = $(entryHTML);

  entry
    .hover(
      function () { $(this).addClass('focused_entry'); },
      function () { $(this).removeClass('focused_entry'); }
    )
    .find('.entry_action').data('muFile',muFile);

  return entry;
}

function getObjectURL(path) {
  if($.app.liveFiles) {
    var liveFile = $.app.liveFiles[path];
    return liveFile ? window.webkitURL.createObjectURL(liveFile) : null;
  } else {
    return null;
  }
}

function searchImage(query, callback) {
  function onComplete() {
    if (imageSearch.results && imageSearch.results.length > 0) {
      var results = imageSearch.results;
      callback(results[0].tbUrl);
    }
  }

  var imageSearch = new google.search.ImageSearch();
  imageSearch.setSearchCompleteCallback(this, onComplete, null);
  imageSearch.execute(query);
}

function updateSongInfo(muFile){
  var songInfo = $('#player_column #player_controls #song_info');
  $('#title', songInfo).text(muFile.title);
  $('#artist', songInfo).text(muFile.artist);
  $('#album', songInfo).text(muFile.album);
}

var currentPlaying = null;
$.app.nextSong = function () {
  currentPlaying.removeClass('active_entry');
  var nextDiv = currentPlaying.next();
  if(nextDiv.length == 0) {
    nextDiv = currentPlaying.parent().children().first();
  }
  play(nextDiv);
}

function play(div) {
  var muFile = div.find('.entry_action').data('muFile');
  console.log(div);
  var url = getObjectURL(muFile.path);
  if(url) {
    $('#player').get(0).src = url;
    $('#player').get(0).play();
    currentPlaying = div;
    currentPlaying.addClass('active_entry');
    searchImage(muFile.album+' '+muFile.artist,function (tbUrl) {
      $('#player_wrapper #album_artwork').attr('src',tbUrl);
    });
    updateSongInfo(muFile);
  } else {
    alert('Add music again');
  }
}

$(document).ready(function () {
  player_init();

  $.app.Storage.load();

  $('#addmusic').click(function () {
    $('input[name=actual_addmusic]').click();
  });

  $('input[name=search]').keyup(function (e) {

    var divResults = $('#search_results');
    divResults.empty();
    var text = $(this).val();

    if(!text || (text && text.length < 4)) { return; }

    var results = $.app.Storage.search($(this).val());
    _(results).each(function (muFile) {
      divResults.append(getSongEntryHtml(muFile, true));
    });

    divResults.find('.entry_action')
      .click(function () {
        var muFile = $(this).data('muFile');
        var player_entry = getSongEntryHtml(muFile, false);
        player_entry.find('.entry_action').click(function () {
          play($(this).parent());
        });
        player_entry.find('.remove_action').click(function () {
          play($(this).parent().remove());
        });
        $('#playlist_wrapper #playlist').append(player_entry);
      });

  })
  .focus(function (e){
    $(this).val('');
  })
  .focusout(function (e){
    if($(this).val() == ''){
      $(this).val('Search...');
    }
  });
});

<commit_msg>remove active_entry class for all children<commit_after>
google.load('search', '1');

function player_init(){
  var width = (($(document).width())>1280? 1280: 1280);
  $('body').css('width', width);

  $('#player_wrapper #album_artwork').attr('src', '/images/nothumb.png');
  google.search.Search.getBranding('google_branding');
}

function loadMusic(files) {
  var musicFiles = _(files).select(function (file) {
    var path = file.webkitRelativePath || file.mozFullPath;
    var fileName = file.fileName;
    var size = file.fileSize;
    var lpath = path.toLowerCase();
    return !/\.$/.test(lpath) &&
      (/\.mp3$/.test(lpath)) ||
      (/\.ogg$/.test(lpath)) ||
      (/\.m4a$/.test(lpath))
  });

  var total = musicFiles.length, progress = 0;

  function incProgress() {
    progress++;
    $('#addmusic').html(progress+' / '+total);
    if(progress == total) {
      $.app.Storage.save();
    } else {
      newMuFile(musicFiles[progress]);
    }
  }

  $.app.liveFiles = {};

  function newMuFile(f) {
    $.app.liveFiles[f.webkitRelativePath] = f;
    var muFile = new $.app.MuFile(f, incProgress);
  }

  newMuFile(musicFiles[progress]);
}

function getPrettySongName(muFile) {
  var name = muFile.name.length > muFile.title.length ?
    muFile.name : muFile.title;
  return name.replace(/\.\w+$/,'');
}

function getYoutubeSearchURL(muFile) {
  var name = getPrettySongName(muFile);
  return 'http://www.youtube.com/results?search_query='+
    name.split(/\s+/).join('+')+'+'+
    muFile.artist.split(/\s+/).join('+');
}

function getLyricsSearchURL(muFile) {
  var name = getPrettySongName(muFile);
  return 'http://www.google.com/search?q='+
    name.split(/\s+/).join('+')+'+'+
    muFile.artist.split(/\s+/).join('+')+'+lyrics';
}

function getArtistWikipediaURL(muFile) {
  return 'http://en.wikipedia.org/w/index.php?search='+
          muFile.artist.split(/\s+/).join('+');
}

function getAmazonLink(muFile) {
  return 'http://www.amazon.com/s?ie=UTF8&x=0&ref_=nb_sb_noss&y=0&field-keywords='+encodeURI(muFile.artist)+'&url=search-alias%3Ddigital-music&_encoding=UTF8&tag=myfreq-20&linkCode=ur2&camp=1789&creative=390957'
}

function getSongEntryHtml(muFile, asSearchResult) {
  var name = getPrettySongName(muFile);
  var entryHTML = '
'+
    '  '+
    ''+getPrettySongName(muFile)+''+
    '  '+
    ''+muFile.album+''+
    '  '+
    ''+muFile.artist+''+
    '  '+
    (asSearchResult ?
      '+' :
      '-'+
      '>')+
  '
';
  var entry = $(entryHTML);

  entry
    .hover(
      function () { $(this).addClass('focused_entry'); },
      function () { $(this).removeClass('focused_entry'); }
    )
    .find('.entry_action').data('muFile',muFile);

  return entry;
}

function getObjectURL(path) {
  if($.app.liveFiles) {
    var liveFile = $.app.liveFiles[path];
    return liveFile ? window.webkitURL.createObjectURL(liveFile) : null;
  } else {
    return null;
  }
}

function searchImage(query, callback) {
  function onComplete() {
    if (imageSearch.results && imageSearch.results.length > 0) {
      var results = imageSearch.results;
      callback(results[0].tbUrl);
    }
  }

  var imageSearch = new google.search.ImageSearch();
  imageSearch.setSearchCompleteCallback(this, onComplete, null);
  imageSearch.execute(query);
}

function updateSongInfo(muFile){
  var songInfo = $('#player_column #player_controls #song_info');
  $('#title', songInfo).text(muFile.title);
  $('#artist', songInfo).text(muFile.artist);
  $('#album', songInfo).text(muFile.album);
}

var currentPlaying = null;
$.app.nextSong = function () {
  var nextDiv = currentPlaying.next();
  if(nextDiv.length == 0) {
    nextDiv = currentPlaying.parent().children().first();
  }
  play(nextDiv);
}

function play(div) {
  var muFile = div.find('.entry_action').data('muFile');
  var url = getObjectURL(muFile.path);
  if(url) {
    $('#player').get(0).src = url;
    $('#player').get(0).play();
    currentPlaying = div;
    currentPlaying.parent().children().removeClass('active_entry');
    currentPlaying.addClass('active_entry');
    searchImage(muFile.album+' '+muFile.artist,function (tbUrl) {
      $('#player_wrapper #album_artwork').attr('src',tbUrl);
    });
    updateSongInfo(muFile);
  } else {
    alert('Add music again');
  }
}

$(document).ready(function () {
  player_init();

  $.app.Storage.load();

  $('#addmusic').click(function () {
    $('input[name=actual_addmusic]').click();
  });

  $('input[name=search]').keyup(function (e) {

    var divResults = $('#search_results');
    divResults.empty();
    var text = $(this).val();

    if(!text || (text && text.length < 4)) { return; }

    var results = $.app.Storage.search($(this).val());
    _(results).each(function (muFile) {
      divResults.append(getSongEntryHtml(muFile, true));
    });

    divResults.find('.entry_action')
      .click(function () {
        var muFile = $(this).data('muFile');
        var player_entry = getSongEntryHtml(muFile, false);
        player_entry.find('.entry_action').click(function () {
          play($(this).parent());
        });
        player_entry.find('.remove_action').click(function () {
          play($(this).parent().remove());
        });
        $('#playlist_wrapper #playlist').append(player_entry);
      });

  })
  .focus(function (e){
    $(this).val('');
  })
  .focusout(function (e){
    if($(this).val() == ''){
      $(this).val('Search...');
    }
  });
});

<|endoftext|>


<commit_before>(function () {
	// Commenting out proper scoping for console access     var Hockey = {};
	Hockey = {};

	// Create Stage
	Hockey.stage = new Kinetic.Stage({
		container: 'container',
		width:235,
		height:620
	});

	// Last mouse position captured by event handlers
	Hockey.lastPosition = { x: 0, y: 0 };

	Hockey.rink = new Rink(Hockey);

	Hockey.teams = [];
	var playersLayer = new Kinetic.Layer( {id: 'players'} );
	for(var i = 1; i <= 2; ++i) {
		Hockey.teams.push(new Team(Hockey, i, playersLayer));
	}
	Hockey.stage.add(playersLayer);

	Hockey.puck = new Puck(Hockey);

	Hockey.detectCollisions = function() {
		var playerCollisions = [];
		var puckLocation = this.puck.getLocation();
		for(i = 0; i < this.teams.length; i++) {
			for(j = 0; j < this.teams[i].players.length; j++) {
				playerCollision = this.teams[i].players[j].detectCollision(puckLocation);
				if(playerCollision && playerCollision.collisionType) {
					playerCollisions.push(playerCollision);
				}
				this.teams[i].players[j].rotationSpeed = 0; // Reset the rotation speed after every detection, I think
			}
		}
		// Detect Goals
		for(var i = 0; i < this.rink.goalLines.length; i++) {
			if(Math.abs(puckLocation.y - this.rink.goalLines[i] - this.rink.offset.x) < 2) {
				if(console) console.log('goal?');
			}
		}

		return playerCollisions.length > 0 ? playerCollisions : null;
	}

	Hockey.handleCollisions = function() {
		var collisions = this.detectCollisions();
		if(collisions != null) {
			for(var i = 0; i < collisions.length; i++) {
				var collision = collisions[i];
				if(collision.collisionType == Player.CONSTANTS.collisionTypes.SHOT) {
					var shotAngle = (collision.player.stickAngle + (Math.PI / 2 * collision.player.rotationDirection));
					var shotSpeed = 5 * collision.rotationSpeed + collision.movementSpeed; // init value for a stationary puck
					if ( Math.abs(collision.movementSpeed) + collision.rotationSpeed == 0) { // stationary player
						shotSpeed = this.puck.velocity * .2;
					} else if (this.puck.velocity > 0) { // moving puck, stationary player
						var shotSpeed = Math.min( 10, (collision.rotationSpeed + _hockey.puck.velocity + collision.rotationSpeed) * 2 + 1); //
					}
					if(shotSpeed > 1) {  // don't bother trying to shoot w/o velocity
						if(console) console.log('Shot by Player', collision.player.position.positionId, ' on team ', collision.player.team.id);
						this.puck.shoot(shotSpeed, shotAngle);
					}
				} else if(collision.collisionType == Player.CONSTANTS.collisionTypes.BUMP) {
					// Body Stroke direction should depend on the angle where the puck hits the circle of the body.  This is just a placeholder
					var bumpSpeed = Math.max(1.2, this.puck.velocity * .3);
					if(console) console.log("Bump off player", collision.player.position.positionId, " on team ", collision.player.team.id, collision.deflectionAngle, this.puck.velocity, bumpSpeed);
					// move the puck out of the range of another bump before moving to prevent the dreaded double/triple/infiniti-bump
					// new x and y positions are out of wack, let's revisit this
					this.puck.puck.setX(collision.newX + this.rink.offset.x);
					this.puck.puck.setY(collision.newY + this.rink.offset.y);
					this.puck.layer.draw();
					this.puck.shoot(bumpSpeed, collision.deflectionAngle);
				}
			}
		}
	}

	var _hockey = Hockey;
	Hockey.stage.on('mousemove touchmove', function(event) {
		var eventPosition = this.getPointerPosition();
		var x = eventPosition.x;
		var y = eventPosition.y - _hockey.rink.offset.y;

		// Control team 0
		var selectedPlayer = _hockey.teams[0].getSelectedPlayer();
		if(selectedPlayer != null) {
			if(!selectedPlayer.animation || !selectedPlayer.animation.isRunning()) {
				// Move vertically only
				selectedPlayer.move(selectedPlayer.location.x, y);
			}
			if(Math.abs(x - _hockey.lastPosition.x) > 1) { // Don't rotate on slight deviations
				var rotationRads = (x - _hockey.lastPosition.x)
				if(Math.abs(rotationRads) < 5) { // rotate at least the 5 px of movement worth
					rotationRads = rotationRads < 0 ? -5 : 5;
				}
				selectedPlayer.rotate( rotationRads / 10);
			}

			_hockey.handleCollisions();

		}
		_hockey.lastPosition = {x: x, y: y};
	});

	// assume 600px height rink for meow
	var scale = window.innerHeight / 600
	//console.log(document.getElementById("zoom-wrapper").style["-webkit-transform"] = "scale("+scale + ")");
})();<commit_msg>Fixing goalline technology to reflect the shot speed<commit_after>(function () {
	// Commenting out proper scoping for console access     var Hockey = {};
	Hockey = {};

	// Create Stage
	Hockey.stage = new Kinetic.Stage({
		container: 'container',
		width:235,
		height:620
	});

	// Last mouse position captured by event handlers
	Hockey.lastPosition = { x: 0, y: 0 };

	Hockey.rink = new Rink(Hockey);

	Hockey.teams = [];
	var playersLayer = new Kinetic.Layer( {id: 'players'} );
	for(var i = 1; i <= 2; ++i) {
		Hockey.teams.push(new Team(Hockey, i, playersLayer));
	}
	Hockey.stage.add(playersLayer);

	Hockey.puck = new Puck(Hockey);

	Hockey.detectCollisions = function() {
		var playerCollisions = [];
		var puckLocation = this.puck.getLocation();
		for(i = 0; i < this.teams.length; i++) {
			for(j = 0; j < this.teams[i].players.length; j++) {
				playerCollision = this.teams[i].players[j].detectCollision(puckLocation);
				if(playerCollision && playerCollision.collisionType) {
					playerCollisions.push(playerCollision);
				}
				this.teams[i].players[j].rotationSpeed = 0; // Reset the rotation speed after every detection, I think
			}
		}
		// Detect Goals
		for(var i = 0; i < this.rink.goalLines.length; i++) {
			if(Math.abs(puckLocation.y + this.rink.offset.y - this.rink.goalLines[i]) < Math.abs(this.puck.velocity)) {
				Hockey.puck.shot.stop();
				if(console) console.log('goal?');
			}
		}

		return playerCollisions.length > 0 ? playerCollisions : null;
	}

	Hockey.handleCollisions = function() {
		var collisions = this.detectCollisions();
		if(collisions != null) {
			for(var i = 0; i < collisions.length; i++) {
				var collision = collisions[i];
				if(collision.collisionType == Player.CONSTANTS.collisionTypes.SHOT) {
					var shotAngle = (collision.player.stickAngle + (Math.PI / 2 * collision.player.rotationDirection));
					var shotSpeed = 5 * collision.rotationSpeed + collision.movementSpeed; // init value for a stationary puck
					if ( Math.abs(collision.movementSpeed) + collision.rotationSpeed == 0) { // stationary player
						shotSpeed = this.puck.velocity * .2;
					} else if (this.puck.velocity > 0) { // moving puck, stationary player
						var shotSpeed = Math.min( 10, (collision.rotationSpeed + _hockey.puck.velocity + collision.rotationSpeed) * 2 + 1); //
					}
					if(shotSpeed > 1) {  // don't bother trying to shoot w/o velocity
						if(console) console.log('Shot by Player', collision.player.position.positionId, ' on team ', collision.player.team.id);
						this.puck.shoot(shotSpeed, shotAngle);
					}
				} else if(collision.collisionType == Player.CONSTANTS.collisionTypes.BUMP) {
					// Body Stroke direction should depend on the angle where the puck hits the circle of the body.  This is just a placeholder
					var bumpSpeed = Math.max(1.2, this.puck.velocity * .3);
					if(console) console.log("Bump off player", collision.player.position.positionId, " on team ", collision.player.team.id, collision.deflectionAngle, this.puck.velocity, bumpSpeed);
					// move the puck out of the range of another bump before moving to prevent the dreaded double/triple/infiniti-bump
					// new x and y positions are out of wack, let's revisit this
					this.puck.puck.setX(collision.newX + this.rink.offset.x);
					this.puck.puck.setY(collision.newY + this.rink.offset.y);
					this.puck.layer.draw();
					this.puck.shoot(bumpSpeed, collision.deflectionAngle);
				}
			}
		}
	}

	var _hockey = Hockey;
	Hockey.stage.on('mousemove touchmove', function(event) {
		var eventPosition = this.getPointerPosition();
		var x = eventPosition.x;
		var y = eventPosition.y - _hockey.rink.offset.y;

		// Control team 0
		var selectedPlayer = _hockey.teams[0].getSelectedPlayer();
		if(selectedPlayer != null) {
			if(!selectedPlayer.animation || !selectedPlayer.animation.isRunning()) {
				// Move vertically only
				selectedPlayer.move(selectedPlayer.location.x, y);
			}
			if(Math.abs(x - _hockey.lastPosition.x) > 1) { // Don't rotate on slight deviations
				var rotationRads = (x - _hockey.lastPosition.x)
				if(Math.abs(rotationRads) < 5) { // rotate at least the 5 px of movement worth
					rotationRads = rotationRads < 0 ? -5 : 5;
				}
				selectedPlayer.rotate( rotationRads / 10);
			}

			_hockey.handleCollisions();

		}
		_hockey.lastPosition = {x: x, y: y};
	});

	// assume 600px height rink for meow
	var scale = window.innerHeight / 600
	//console.log(document.getElementById("zoom-wrapper").style["-webkit-transform"] = "scale("+scale + ")");
})();<|endoftext|>


<commit_before>phoxy._.EarlyStage.ajax = function (url, callback, data, x)
{  // https://gist.github.com/Xeoncross/7663273
  try
  {
    x = new(window.XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');
    x.open(data ? 'POST' : 'GET', url, 1);
    x.setRequestHeader('X-Lain', 'Wake up');
    x.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    x.onreadystatechange = function () {
      x.readyState > 3 && callback && callback(x.responseText, x);
    };
    x.send(data)
  } catch (e)
  {
    window.console && console.log(e);
  }
};

phoxy._.EarlyStage.LoadConfig = function()
{
  phoxy._.EarlyStage.ajax(phoxy._.prestart.config || "api/phoxy", function early_conf_loaded(response)
  {
    phoxy.state.early.loaded++;
    var data = JSON.parse(response);
    phoxy._.config = data;
    phoxy.state.conf_loaded = true;
  })
}

phoxy._.EarlyStage.DependenciesLoaded = function()
{
  if (phoxy.state.runlevel < 2)
    return setTimeout(arguments.callee, 10);
  if (!phoxy.state.conf_loaded) // wait until phoxy.Config()uration loaded
    return setTimeout(arguments.callee, 10);
  phoxy.state.runlevel += 0.5; // because config downloaded

  if (typeof phoxy._.prestart.OnBeforeCompile === 'function')
    phoxy._.prestart.OnBeforeCompile();

  phoxy._.EarlyStage.Compile();
  if (typeof phoxy.Config().verbose !== 'undefined')
    phoxy.state.verbose = phoxy.Config().verbose;

  if (typeof phoxy._.prestart.OnAfterCompile === 'function')
    phoxy._.prestart.OnAfterCompile();

  phoxy._.EarlyStage.PreloadInitialClientCode();
  phoxy._.EarlyStage.HomePageLoad();

  // Entering runlevel 3, compilation finished
  phoxy.state.runlevel += 0.5;
};

phoxy._.EarlyStage.Compile = function()
{
  for (var k in phoxy._.EarlyStage.systems)
  {
    var system_name = phoxy._.EarlyStage.systems[k];
    if (system_name === undefined)
      continue; // skip compilation

    if (typeof phoxy[system_name]['_'] !== 'undefined')
    {
      for (var subsytem in phoxy[system_name]['_'])
        phoxy._[subsytem] = phoxy[system_name]._[subsytem];
      delete phoxy[system_name]['_'];
    }

    for (var func in phoxy[system_name])
      if (typeof phoxy[func] !== 'undefined')
        throw "Phoxy method mapping failed on '" + func + '. Already exsists.';
      else
        phoxy[func] = phoxy[system_name][func];
    delete phoxy[system_name];
  }

  if (phoxy._.prestart.sync_cascade)
  {
    phoxy.state.sync_cascade = true;
    phoxy._.render.RenderStrategy = phoxy._.render.SyncRender_Strategy;
  }
  else
  {
    phoxy.state.sync_cascade = false;
    phoxy._.render.RenderStrategy = phoxy._.render.AsyncRender_Strategy;
  }

  // Move bootstrapped ajax into his place
  phoxy._.internal.ajax = phoxy._.EarlyStage.ajax;

  phoxy.state.compiled = true;
};

phoxy._.EarlyStage.PreloadInitialClientCode = function()
{
  if (typeof phoxy._.prestart.OnBeforeFirstApiCall === 'function')
    phoxy._.prestart.OnBeforeFirstApiCall();

  phoxy._.EarlyStage.initial_client_code = 0;
  phoxy._.EarlyStage.total_amount = 0;

  phoxy._.EarlyStage.initial_preloaded = [];

  function InitialCodePreload(script)
  {
    phoxy.AJAX(script.getAttribute('phoxy'), function on_intial_code_preloaded(response)
    {
      phoxy._.EarlyStage.initial_preloaded.push(response);
    });
  }

  // Invoke client code
  var scripts = document.getElementsByTagName('script');
  for (var i = 0; i < scripts.length; i++)
    if (scripts[i].getAttribute('phoxy') === null)
      continue;
    else
    {
      phoxy._.EarlyStage.initial_client_code++;
      phoxy._.EarlyStage.total_amount++;
      InitialCodePreload(scripts[i]);
    }
}

phoxy._.EarlyStage.EnterFinalExecution = function()
{
  if (phoxy.state.runlevel < 3)
    return setTimeout(arguments.callee, 50);

  phoxy._.enjs.OverloadENJSCanvas();
  requirejs.config({baseUrl: phoxy.Config()['js_dir']});

  if (typeof phoxy._.prestart.OnExecutingInitialClientCode === 'function')
    phoxy._.prestart.OnExecutingInitialClientCode();

  phoxy._.EarlyStage.ExecuteInitialClientCode();
}

phoxy._.EarlyStage.ExecuteInitialClientCode = function()
{
  if (phoxy._.EarlyStage.initial_client_code === 0)
  {
    if (typeof phoxy._.prestart.OnInitialClientCodeComplete === 'function')
      phoxy._.prestart.OnInitialClientCodeComplete();
    return;
  }

  // reshedule if nothing to process
  if (phoxy._.EarlyStage.initial_client_code > 0 && phoxy._.EarlyStage.initial_preloaded.length === 0)
    return setTimeout(arguments.callee, 50);

  var code = phoxy._.EarlyStage.initial_preloaded.pop();

  phoxy.state.runlevel += 1 / phoxy._.EarlyStage.total_amount;
  phoxy.ApiAnswer(code, function when_client_code_applied()
  {
    if (--phoxy._.EarlyStage.initial_client_code)
      return;
    phoxy._.EarlyStage.ExecuteInitialClientCode();
  });
}

phoxy._.EarlyStage.HomePageLoad = function()
{
  if (phoxy._.prestart.no_home_call !== undefined)
    return;

  var home_result;
  function when_home_result_ready()
  {
    if (phoxy._.EarlyStage.initial_client_code > 0)
      return setTimeout(arguments.callee, 50);
    // Wait for initial code to complete, before execute first page code
    phoxy.ApiAnswer(home_result, phoxy._.prestart.OnFirstPageRendered);
  }

  phoxy.AJAX(location.pathname.substr(1) + location.search, function(response)
  {
    home_result = response;
    when_home_result_ready();
  });
}<commit_msg>Make ajax request less CPU freaky<commit_after>phoxy._.EarlyStage.ajax = function (url, callback, data, x)
{
  function ajax_Fetch(url, callback, data, x)
  {
  }

  function ajax_XMLHttpRequest(url, callback, data, x)
  {
    try
    {
      x = new (window.XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');

      x.open(data ? 'POST' : 'GET', url, 1);

      x.setRequestHeader('X-Lain', 'Wake up');
      x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

      x.onload = function () {
        callback(x.responseText, x);
      };

      x.send(data)
    } catch (e)
    {
      window.console && console.log(e);
    }
  }

  if (typeof window.fetch != 'undefined')
    phoxy._.EarlyStage.ajax = ajax_Fetch;
  else
    phoxy._.EarlyStage.ajax = ajax_XMLHttpRequest;

  phoxy._.EarlyStage.ajax.apply(this, arguments);
};

phoxy._.EarlyStage.LoadConfig = function()
{
  phoxy._.EarlyStage.ajax(phoxy._.prestart.config || "api/phoxy", function early_conf_loaded(response)
  {
    phoxy.state.early.loaded++;
    var data = JSON.parse(response);
    phoxy._.config = data;
    phoxy.state.conf_loaded = true;
  })
}

phoxy._.EarlyStage.DependenciesLoaded = function()
{
  if (phoxy.state.runlevel < 2)
    return setTimeout(arguments.callee, 10);
  if (!phoxy.state.conf_loaded) // wait until phoxy.Config()uration loaded
    return setTimeout(arguments.callee, 10);
  phoxy.state.runlevel += 0.5; // because config downloaded

  if (typeof phoxy._.prestart.OnBeforeCompile === 'function')
    phoxy._.prestart.OnBeforeCompile();

  phoxy._.EarlyStage.Compile();
  if (typeof phoxy.Config().verbose !== 'undefined')
    phoxy.state.verbose = phoxy.Config().verbose;

  if (typeof phoxy._.prestart.OnAfterCompile === 'function')
    phoxy._.prestart.OnAfterCompile();

  phoxy._.EarlyStage.PreloadInitialClientCode();
  phoxy._.EarlyStage.HomePageLoad();

  // Entering runlevel 3, compilation finished
  phoxy.state.runlevel += 0.5;
};

phoxy._.EarlyStage.Compile = function()
{
  for (var k in phoxy._.EarlyStage.systems)
  {
    var system_name = phoxy._.EarlyStage.systems[k];
    if (system_name === undefined)
      continue; // skip compilation

    if (typeof phoxy[system_name]['_'] !== 'undefined')
    {
      for (var subsytem in phoxy[system_name]['_'])
        phoxy._[subsytem] = phoxy[system_name]._[subsytem];
      delete phoxy[system_name]['_'];
    }

    for (var func in phoxy[system_name])
      if (typeof phoxy[func] !== 'undefined')
        throw "Phoxy method mapping failed on '" + func + '. Already exsists.';
      else
        phoxy[func] = phoxy[system_name][func];
    delete phoxy[system_name];
  }

  if (phoxy._.prestart.sync_cascade)
  {
    phoxy.state.sync_cascade = true;
    phoxy._.render.RenderStrategy = phoxy._.render.SyncRender_Strategy;
  }
  else
  {
    phoxy.state.sync_cascade = false;
    phoxy._.render.RenderStrategy = phoxy._.render.AsyncRender_Strategy;
  }

  // Move bootstrapped ajax into his place
  phoxy._.internal.ajax = phoxy._.EarlyStage.ajax;

  phoxy.state.compiled = true;
};

phoxy._.EarlyStage.PreloadInitialClientCode = function()
{
  if (typeof phoxy._.prestart.OnBeforeFirstApiCall === 'function')
    phoxy._.prestart.OnBeforeFirstApiCall();

  phoxy._.EarlyStage.initial_client_code = 0;
  phoxy._.EarlyStage.total_amount = 0;

  phoxy._.EarlyStage.initial_preloaded = [];

  function InitialCodePreload(script)
  {
    phoxy.AJAX(script.getAttribute('phoxy'), function on_intial_code_preloaded(response)
    {
      phoxy._.EarlyStage.initial_preloaded.push(response);
    });
  }

  // Invoke client code
  var scripts = document.getElementsByTagName('script');
  for (var i = 0; i < scripts.length; i++)
    if (scripts[i].getAttribute('phoxy') === null)
      continue;
    else
    {
      phoxy._.EarlyStage.initial_client_code++;
      phoxy._.EarlyStage.total_amount++;
      InitialCodePreload(scripts[i]);
    }
}

phoxy._.EarlyStage.EnterFinalExecution = function()
{
  if (phoxy.state.runlevel < 3)
    return setTimeout(arguments.callee, 50);

  phoxy._.enjs.OverloadENJSCanvas();
  requirejs.config({baseUrl: phoxy.Config()['js_dir']});

  if (typeof phoxy._.prestart.OnExecutingInitialClientCode === 'function')
    phoxy._.prestart.OnExecutingInitialClientCode();

  phoxy._.EarlyStage.ExecuteInitialClientCode();
}

phoxy._.EarlyStage.ExecuteInitialClientCode = function()
{
  if (phoxy._.EarlyStage.initial_client_code === 0)
  {
    if (typeof phoxy._.prestart.OnInitialClientCodeComplete === 'function')
      phoxy._.prestart.OnInitialClientCodeComplete();
    return;
  }

  // reshedule if nothing to process
  if (phoxy._.EarlyStage.initial_client_code > 0 && phoxy._.EarlyStage.initial_preloaded.length === 0)
    return setTimeout(arguments.callee, 50);

  var code = phoxy._.EarlyStage.initial_preloaded.pop();

  phoxy.state.runlevel += 1 / phoxy._.EarlyStage.total_amount;
  phoxy.ApiAnswer(code, function when_client_code_applied()
  {
    if (--phoxy._.EarlyStage.initial_client_code)
      return;
    phoxy._.EarlyStage.ExecuteInitialClientCode();
  });
}

phoxy._.EarlyStage.HomePageLoad = function()
{
  if (phoxy._.prestart.no_home_call !== undefined)
    return;

  var home_result;
  function when_home_result_ready()
  {
    if (phoxy._.EarlyStage.initial_client_code > 0)
      return setTimeout(arguments.callee, 50);
    // Wait for initial code to complete, before execute first page code
    phoxy.ApiAnswer(home_result, phoxy._.prestart.OnFirstPageRendered);
  }

  phoxy.AJAX(location.pathname.substr(1) + location.search, function(response)
  {
    home_result = response;
    when_home_result_ready();
  });
}
<|endoftext|>


<commit_before>/**
 * @author qiao / https://github.com/qiao
 * @author mrdoob / http://mrdoob.com
 * @author alteredq / http://alteredqualia.com/
 * @author WestLangley / http://github.com/WestLangley
 * @author erich666 / http://erichaines.com
 */
/*global THREE, console */

// This set of controls performs orbiting, dollying (zooming), and panning. It maintains
// the "up" direction as +Y, unlike the TrackballControls. Touch on tablet and phones is
// supported.
//
//    Orbit - left mouse / touch: one finger move
//    Zoom - middle mouse, or mousewheel / touch: two finger spread or squish
//    Pan - right mouse, or arrow keys / touch: three finter swipe

THREE.OrbitControls = function ( object, domElement ) {

	this.object = object;
	this.domElement = ( domElement !== undefined ) ? domElement : document;

	// API

	// Set to false to disable this control
	this.enabled = true;

	// "target" sets the location of focus, where the control orbits around
	// and where it pans with respect to.
	this.target = new THREE.Vector3();

	// center is old, deprecated; use "target" instead
	this.center = this.target;

	// This option actually enables dollying in and out; left as "zoom" for
	// backwards compatibility
	this.noZoom = false;
	this.zoomSpeed = 1.0;

	// Limits to how far you can dolly in and out ( PerspectiveCamera only )
	this.minDistance = 0;
	this.maxDistance = Infinity;

	// Limits to how far you can zoom in and out ( OrthographicCamera only )
	this.minZoom = 0;
	this.maxZoom = Infinity;

	// Set to true to disable this control
	this.noRotate = false;
	this.rotateSpeed = 1.0;

	// Set to true to disable this control
	this.noPan = false;
	this.keyPanSpeed = 7.0;	// pixels moved per arrow key push

	// Set to true to automatically rotate around the target
	this.autoRotate = false;
	this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60

	// How far you can orbit vertically, upper and lower limits.
	// Range is 0 to Math.PI radians.
	this.minPolarAngle = 0; // radians
	this.maxPolarAngle = Math.PI; // radians

	// How far you can orbit horizontally, upper and lower limits.
	// If set, must be a sub-interval of the interval [ - Math.PI, Math.PI ].
	this.minAzimuthAngle = - Infinity; // radians
	this.maxAzimuthAngle = Infinity; // radians

	// Set to true to disable use of the keys
	this.noKeys = false;

	// The four arrow keys
	this.keys = { LEFT: 37, UP: 38, RIGHT: 39, BOTTOM: 40 };

	// Mouse buttons
	this.mouseButtons = { ORBIT: THREE.MOUSE.LEFT, ZOOM: THREE.MOUSE.MIDDLE, PAN: THREE.MOUSE.RIGHT };

	////////////
	// internals

	var scope = this;

	var EPS = 0.000001;

	var rotateStart = new THREE.Vector2();
	var rotateEnd = new THREE.Vector2();
	var rotateDelta = new THREE.Vector2();

	var panStart = new THREE.Vector2();
	var panEnd = new THREE.Vector2();
	var panDelta = new THREE.Vector2();
	var panOffset = new THREE.Vector3();

	var offset = new THREE.Vector3();

	var dollyStart = new THREE.Vector2();
	var dollyEnd = new THREE.Vector2();
	var dollyDelta = new THREE.Vector2();

	var theta;
	var phi;
	var phiDelta = 0;
	var thetaDelta = 0;
	var scale = 1;
	var pan = new THREE.Vector3();

	var lastPosition = new THREE.Vector3();
	var lastQuaternion = new THREE.Quaternion();

	var STATE = { NONE : -1, ROTATE : 0, DOLLY : 1, PAN : 2, TOUCH_ROTATE : 3, TOUCH_DOLLY : 4, TOUCH_PAN : 5 };

	var state = STATE.NONE;

	// for reset

	this.target0 = this.target.clone();
	this.position0 = this.object.position.clone();
	this.zoom0 = this.object.zoom;

	// so camera.up is the orbit axis

	var quat = new THREE.Quaternion().setFromUnitVectors( object.up, new THREE.Vector3( 0, 1, 0 ) );
	var quatInverse = quat.clone().inverse();

	// events

	var changeEvent = { type: 'change' };
	var startEvent = { type: 'start' };
	var endEvent = { type: 'end' };

	this.rotateLeft = function ( angle ) {

		if ( angle === undefined ) {

			angle = getAutoRotationAngle();

		}

		thetaDelta -= angle;

	};

	this.rotateUp = function ( angle ) {

		if ( angle === undefined ) {

			angle = getAutoRotationAngle();

		}

		phiDelta -= angle;

	};

	// pass in distance in world space to move left
	this.panLeft = function ( distance ) {

		var te = this.object.matrix.elements;

		// get X column of matrix
		panOffset.set( te[ 0 ], te[ 1 ], te[ 2 ] );
		panOffset.multiplyScalar( - distance );

		pan.add( panOffset );

	};

	// pass in distance in world space to move up
	this.panUp = function ( distance ) {

		var te = this.object.matrix.elements;

		// get Y column of matrix
		panOffset.set( te[ 4 ], te[ 5 ], te[ 6 ] );
		panOffset.multiplyScalar( distance );

		pan.add( panOffset );

	};

	// pass in x,y of change desired in pixel space,
	// right and down are positive
	this.pan = function ( deltaX, deltaY ) {

		var element = scope.domElement === document ? scope.domElement.body : scope.domElement;

		if ( scope.object instanceof THREE.PerspectiveCamera ) {

			// perspective
			var position = scope.object.position;
			var offset = position.clone().sub( scope.target );
			var targetDistance = offset.length();

			// half of the fov is center to top of screen
			targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 );

			// we actually don't use screenWidth, since perspective camera is fixed to screen height
			scope.panLeft( 2 * deltaX * targetDistance / element.clientHeight );
			scope.panUp( 2 * deltaY * targetDistance / element.clientHeight );

		} else if ( scope.object instanceof THREE.OrthographicCamera ) {

			// orthographic
			scope.panLeft( deltaX * (scope.object.right - scope.object.left) / element.clientWidth );
			scope.panUp( deltaY * (scope.object.top - scope.object.bottom) / element.clientHeight );

		} else {

			// camera neither orthographic or perspective
			console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' );

		}

	};

	this.dollyIn = function ( dollyScale ) {

		if ( dollyScale === undefined ) {

			dollyScale = getZoomScale();

		}

		if ( scope.object instanceof THREE.PerspectiveCamera ) {

			scale /= dollyScale;

		} else if ( scope.object instanceof THREE.OrthographicCamera ) {

			scope.object.zoom = Math.max( this.minZoom, Math.min( this.maxZoom, this.object.zoom * dollyScale ) );
			scope.object.updateProjectionMatrix();
			scope.dispatchEvent( changeEvent );

		} else {

			console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );

		}

	};

	this.dollyOut = function ( dollyScale ) {

		if ( dollyScale === undefined ) {

			dollyScale = getZoomScale();

		}

		if ( scope.object instanceof THREE.PerspectiveCamera ) {

			scale *= dollyScale;

		} else if ( scope.object instanceof THREE.OrthographicCamera ) {

			scope.object.zoom = Math.max( this.minZoom, Math.min( this.maxZoom, this.object.zoom / dollyScale ) );
			scope.object.updateProjectionMatrix();
			scope.dispatchEvent( changeEvent );

		} else {

			console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );

		}

	};

	this.update = function () {

		var position = this.object.position;

		offset.copy( position ).sub( this.target );

		// rotate offset to "y-axis-is-up" space
		offset.applyQuaternion( quat );

		// angle from z-axis around y-axis

		theta = Math.atan2( offset.x, offset.z );

		// angle from y-axis

		phi = Math.atan2( Math.sqrt( offset.x * offset.x + offset.z * offset.z ), offset.y );

		if ( this.autoRotate && state === STATE.NONE ) {

			this.rotateLeft( getAutoRotationAngle() );

		}

		theta += thetaDelta;
		phi += phiDelta;

		// restrict theta to be between desired limits
		theta = Math.max( this.minAzimuthAngle, Math.min( this.maxAzimuthAngle, theta ) );

		// restrict phi to be between desired limits
		phi = Math.max( this.minPolarAngle, Math.min( this.maxPolarAngle, phi ) );

		// restrict phi to be betwee EPS and PI-EPS
		phi = Math.max( EPS, Math.min( Math.PI - EPS, phi ) );

		var radius = offset.length() * scale;

		// restrict radius to be between desired limits
		radius = Math.max( this.minDistance, Math.min( this.maxDistance, radius ) );

		// move target to panned location
		this.target.add( pan );

		offset.x = radius * Math.sin( phi ) * Math.sin( theta );
		offset.y = radius * Math.cos( phi );
		offset.z = radius * Math.sin( phi ) * Math.cos( theta );

		// rotate offset back to "camera-up-vector-is-up" space
		offset.applyQuaternion( quatInverse );

		position.copy( this.target ).add( offset );

		this.object.lookAt( this.target );

		thetaDelta = 0;
		phiDelta = 0;
		scale = 1;
		pan.set( 0, 0, 0 );

		// update condition is:
		// min(camera displacement, camera rotation in radians)^2 > EPS
		// using small-angle approximation cos(x/2) = 1 - x^2 / 8

		if ( lastPosition.distanceToSquared( this.object.position ) > EPS
		    || 8 * (1 - lastQuaternion.dot(this.object.quaternion)) > EPS ) {

			this.dispatchEvent( changeEvent );

			lastPosition.copy( this.object.position );
			lastQuaternion.copy (this.object.quaternion );

		}

	};

	this.reset = function () {

		state = STATE.NONE;

		this.target.copy( this.target0 );
		this.object.position.copy( this.position0 );
		this.object.zoom = this.zoom0;

		this.object.updateProjectionMatrix();
		this.dispatchEvent( changeEvent );

		this.update();

	};

	this.getPolarAngle = function () {

		return phi;

	};

	this.getAzimuthalAngle = function () {

		return theta

	};

	function getAutoRotationAngle() {

		return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;

	}

	function getZoomScale() {

		return Math.pow( 0.95, scope.zoomSpeed );

	}

	function onMouseDown( event ) {

		if ( scope.enabled === false ) return;
		event.preventDefault();

		if ( event.button === scope.mouseButtons.ORBIT ) {
			if ( scope.noRotate === true ) return;

			state = STATE.ROTATE;

			rotateStart.set( event.clientX, event.clientY );

		} else if ( event.button === scope.mouseButtons.ZOOM ) {
			if ( scope.noZoom === true ) return;

			state = STATE.DOLLY;

			dollyStart.set( event.clientX, event.clientY );

		} else if ( event.button === scope.mouseButtons.PAN ) {
			if ( scope.noPan === true ) return;

			state = STATE.PAN;

			panStart.set( event.clientX, event.clientY );

		}

		if ( state !== STATE.NONE ) {
			document.addEventListener( 'mousemove', onMouseMove, false );
			document.addEventListener( 'mouseup', onMouseUp, false );
			scope.dispatchEvent( startEvent );
		}

	}

	function onMouseMove( event ) {

		if ( scope.enabled === false ) return;

		event.preventDefault();

		var element = scope.domElement === document ? scope.domElement.body : scope.domElement;

		if ( state === STATE.ROTATE ) {

			if ( scope.noRotate === true ) return;

			rotateEnd.set( event.clientX, event.clientY );
			rotateDelta.subVectors( rotateEnd, rotateStart );

			// rotating across whole screen goes 360 degrees around
			scope.rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientWidth * scope.rotateSpeed );

			// rotating up and down along whole screen attempts to go 360, but limited to 180
			scope.rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight * scope.rotateSpeed );

			rotateStart.copy( rotateEnd );

		} else if ( state === STATE.DOLLY ) {

			if ( scope.noZoom === true ) return;

			dollyEnd.set( event.clientX, event.clientY );
			dollyDelta.subVectors( dollyEnd, dollyStart );

			if ( dollyDelta.y > 0 ) {

				scope.dollyIn();

			} else if ( dollyDelta.y < 0 ) {

				scope.dollyOut();

			}

			dollyStart.copy( dollyEnd );

		} else if ( state === STATE.PAN ) {

			if ( scope.noPan === true ) return;

			panEnd.set( event.clientX, event.clientY );
			panDelta.subVectors( panEnd, panStart );

			scope.pan( panDelta.x, panDelta.y );

			panStart.copy( panEnd );

		}

		if ( state !== STATE.NONE ) scope.update();

	}

	function onMouseUp( /* event */ ) {

		if ( scope.enabled === false ) return;

		document.removeEventListener( 'mousemove', onMouseMove, false );
		document.removeEventListener( 'mouseup', onMouseUp, false );
		scope.dispatchEvent( endEvent );
		state = STATE.NONE;

	}

	function onMouseWheel( event ) {

		if ( scope.enabled === false || scope.noZoom === true || state !== STATE.NONE ) return;

		event.preventDefault();
		event.stopPropagation();

		var delta = 0;

		if ( event.wheelDelta !== undefined ) { // WebKit / Opera / Explorer 9

			delta = event.wheelDelta;

		} else if ( event.detail !== undefined ) { // Firefox

			delta = - event.detail;

		}

		if ( delta > 0 ) {

			scope.dollyOut();

		} else if ( delta < 0 ) {

			scope.dollyIn();

		}

		scope.update();
		scope.dispatchEvent( startEvent );
		scope.dispatchEvent( endEvent );

	}

	function onKeyDown( event ) {

		if ( scope.enabled === false || scope.noKeys === true || scope.noPan === true ) return;

		switch ( event.keyCode ) {

			case scope.keys.UP:
				scope.pan( 0, scope.keyPanSpeed );
				scope.update();
				break;

			case scope.keys.BOTTOM:
				scope.pan( 0, - scope.keyPanSpeed );
				scope.update();
				break;

			case scope.keys.LEFT:
				scope.pan( scope.keyPanSpeed, 0 );
				scope.update();
				break;

			case scope.keys.RIGHT:
				scope.pan( - scope.keyPanSpeed, 0 );
				scope.update();
				break;

		}

	}

	function touchstart( event ) {

		if ( scope.enabled === false ) return;

		switch ( event.touches.length ) {

			case 1:	// one-fingered touch: rotate

				if ( scope.noRotate === true ) return;

				state = STATE.TOUCH_ROTATE;

				rotateStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
				break;

			case 2:	// two-fingered touch: dolly

				if ( scope.noZoom === true ) return;

				state = STATE.TOUCH_DOLLY;

				var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX;
				var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY;
				var distance = Math.sqrt( dx * dx + dy * dy );
				dollyStart.set( 0, distance );
				break;

			case 3: // three-fingered touch: pan

				if ( scope.noPan === true ) return;

				state = STATE.TOUCH_PAN;

				panStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
				break;

			default:

				state = STATE.NONE;

		}

		if ( state !== STATE.NONE ) scope.dispatchEvent( startEvent );

	}

	function touchmove( event ) {

		if ( scope.enabled === false ) return;

		event.preventDefault();
		event.stopPropagation();

		var element = scope.domElement === document ? scope.domElement.body : scope.domElement;

		switch ( event.touches.length ) {

			case 1: // one-fingered touch: rotate

				if ( scope.noRotate === true ) return;
				if ( state !== STATE.TOUCH_ROTATE ) return;

				rotateEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
				rotateDelta.subVectors( rotateEnd, rotateStart );

				// rotating across whole screen goes 360 degrees around
				scope.rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientWidth * scope.rotateSpeed );
				// rotating up and down along whole screen attempts to go 360, but limited to 180
				scope.rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight * scope.rotateSpeed );

				rotateStart.copy( rotateEnd );

				scope.update();
				break;

			case 2: // two-fingered touch: dolly

				if ( scope.noZoom === true ) return;
				if ( state !== STATE.TOUCH_DOLLY ) return;

				var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX;
				var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY;
				var distance = Math.sqrt( dx * dx + dy * dy );

				dollyEnd.set( 0, distance );
				dollyDelta.subVectors( dollyEnd, dollyStart );

				if ( dollyDelta.y > 0 ) {

					scope.dollyOut();

				} else if ( dollyDelta.y < 0 ) {

					scope.dollyIn();

				}

				dollyStart.copy( dollyEnd );

				scope.update();
				break;

			case 3: // three-fingered touch: pan

				if ( scope.noPan === true ) return;
				if ( state !== STATE.TOUCH_PAN ) return;

				panEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
				panDelta.subVectors( panEnd, panStart );

				scope.pan( panDelta.x, panDelta.y );

				panStart.copy( panEnd );

				scope.update();
				break;

			default:

				state = STATE.NONE;

		}

	}

	function touchend( /* event */ ) {

		if ( scope.enabled === false ) return;

		scope.dispatchEvent( endEvent );
		state = STATE.NONE;

	}

	this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
	this.domElement.addEventListener( 'mousedown', onMouseDown, false );
	this.domElement.addEventListener( 'mousewheel', onMouseWheel, false );
	this.domElement.addEventListener( 'DOMMouseScroll', onMouseWheel, false ); // firefox

	this.domElement.addEventListener( 'touchstart', touchstart, false );
	this.domElement.addEventListener( 'touchend', touchend, false );
	this.domElement.addEventListener( 'touchmove', touchmove, false );

	window.addEventListener( 'keydown', onKeyDown, false );

	// force an update at start
	this.update();

};

THREE.OrbitControls.prototype = Object.create( THREE.EventDispatcher.prototype );
THREE.OrbitControls.prototype.constructor = THREE.OrbitControls;<commit_msg>remove unused file<commit_after><|endoftext|>


<commit_before>(function (window) {
    "use strict";

    var document = window.document,
		console = window.console,
		$ = window.jQuery,
		grace = window.grace;

    $.fn.gracePanelsa = function (options) {

        var defaults = {
            animationDuration: 500,
            title: "test Title"
        };

        options = $.extend({}, defaults, options);

        function initEach() {
            var $gracePanelsa = $(this);
            $gracePanelsa.find(".panelsa-btn").each(function () {
                if (jQuery(this).attr('class').indexOf("opened") != -1) {
                    jQuery(this).prepend('
' + options.title + '
');
                    jQuery(this).addClass('panelsa-a-opened');
                } else {
                    jQuery(this).prepend('
' + options.title + '
');
                    jQuery(this).addClass('panelsa-a-closed');
                }

                var tabContent = $(this).siblings(".panelsa-content");

                var orgHeight;
                if (!tabContent.is(":visible")) {
                    tabContent.show();
                    orgHeight = tabContent.height();
                    tabContent.hide();
                } else {
                    orgHeight = tabContent.height();
                }
                $(this).click(function () {
                    if (jQuery(this).attr('class').indexOf("opened") != -1) {
                        jQuery(this).removeClass('panelsa-a-opened');
                        jQuery(this).addClass('panelsa-a-closed');
                    }
                    else {
                        jQuery(this).removeClass('panelsa-a-closed');
                        jQuery(this).addClass('panelsa-a-opened');
                    }
                    var curHeight = $(this).siblings(".panelsa-content").height();
                    if (curHeight <= 0 || tabContent.is(":hidden")) {
                        tabContent.css({ display: "block", height: 0, opacity: 0 }).animate({ height: orgHeight, opacity: 1 }, options.animationDuration);
                    } else {
                        tabContent.animate({ height: 0, opacity: 0 }, options.animationDuration);
                    }
                });
            });
        }
        grace.patcher.patch($.fn.gracePanelsa, this);
        return this.each(initEach);
    };

})(window);
<commit_msg>delete the patch  and update jQuery as $<commit_after>(function (window) {
    "use strict";

    var document = window.document,
		console = window.console,
		$ = window.jQuery,
		grace = window.grace;

    $.fn.gracePanelsa = function (options) {

        var defaults = {
            animationDuration: 500,
            title: "test Title"
        };

        options = $.extend({}, defaults, options);

        function initEach() {
            var $gracePanelsa = $(this);
            $gracePanelsa.find(".panelsa-btn").each(function () {
                if ($(this).attr('class').indexOf("opened") != -1) {
                    $(this).prepend('
' + options.title + '
');
                    $(this).addClass('panelsa-a-opened');
                } else {
                    $(this).prepend('
' + options.title + '
');
                    $(this).addClass('panelsa-a-closed');
                }

                var tabContent = $(this).siblings(".panelsa-content");

                var orgHeight;
                if (!tabContent.is(":visible")) {
                    tabContent.show();
                    orgHeight = tabContent.height();
                    tabContent.hide();
                } else {
                    orgHeight = tabContent.height();
                }
                $(this).click(function () {
                    if ($(this).attr('class').indexOf("opened") != -1) {
                        $(this).removeClass('panelsa-a-opened');
                        $(this).addClass('panelsa-a-closed');
                    }
                    else {
                        $(this).removeClass('panelsa-a-closed');
                        $(this).addClass('panelsa-a-opened');
                    }
                    var curHeight = $(this).siblings(".panelsa-content").height();
                    if (curHeight <= 0 || tabContent.is(":hidden")) {
                        tabContent.css({ display: "block", height: 0, opacity: 0 }).animate({ height: orgHeight, opacity: 1 }, options.animationDuration);
                    } else {
                        tabContent.animate({ height: 0, opacity: 0 }, options.animationDuration);
                    }
                });
            });
        }
        return this.each(initEach);
    };

})(window);
<|endoftext|>


<commit_before>$(document).ready(function()
{
	$("#content").fadeIn(1000);
	$("#authErr").hide();
});

$("button#share").click(function()
{
	$("#content").hide();
	$("#loading").fadeIn(500);
	chrome.tabs.query({active: true, currentWindow: true}, function(tabs)
	{
		$.ajax({
			type: "POST",
			url: "https://player.me/api/v1/feed",
			data: {"post": ($("input#comment").val()!="")?$("input#comment").val()+"

"+tabs[0].url:tabs[0].url},
			dataType: "json"
		}).done(function(data)
		{
			$("#loading").hide();
			if(data.results == "Must be logged on to do this")
			{
				$("#auth").fadeIn(500);
			}
			else
			{
				$("#content").fadeIn(500);
				$("input#comment").val("");
			}
		});
	});
});

$("button#login").click(function()
{
	if($("input#user").val()=="" || $("input#password").val()=="")
	{
		$("#authErr").fadeIn(500);
	}
	else
	{
		$("#authErr").hide();
		$("#auth").hide();
		$("#loading").fadeIn(500);
		$.ajax({
			type: "POST",
			url: "https://player.me/api/v1/auth/login",
			data: {"login": $("input#user").val(), "password": $("input#password").val(), "remember": true},
			dataType: "json"
		}).done(function(data)
		{
			$("#loading").hide();
			if(data.results[0] == "Wrong username/password")
			{
				$("#auth").fadeIn(500);
				$("#authErr").fadeIn(600);
			}
			else
			{

				$("#content").fadeIn(500);
			}
		});
	}
});<commit_msg>Made posts much cleaner<commit_after>$(document).ready(function()
{
	$("#content").fadeIn(1000);
	$("#authErr").hide();
});

$("button#share").click(function()
{
	$("#content").hide();
	$("#loading").fadeIn(500);
	chrome.tabs.query({active: true, currentWindow: true}, function(tabs)
	{
		$.ajax({
			type: "POST",
			url: "https://player.me/api/v1/feed",
			data: {"post": ($("input#comment").val()!="") ? $("input#comment").val()+"[ ]("+tabs[0].url+")" : "[ ]("+tabs[0].url+")"},
			dataType: "json"
		}).done(function(data)
		{
			$("#loading").hide();
			if(data.results == "Must be logged on to do this")
			{
				$("#auth").fadeIn(500);
			}
			else
			{
				$("#content").fadeIn(500);
				$("input#comment").val("");
			}
		});
	});
});

$("button#login").click(function()
{
	if($("input#user").val()=="" || $("input#password").val()=="")
	{
		$("#authErr").fadeIn(500);
	}
	else
	{
		$("#authErr").hide();
		$("#auth").hide();
		$("#loading").fadeIn(500);
		$.ajax({
			type: "POST",
			url: "https://player.me/api/v1/auth/login",
			data: {"login": $("input#user").val(), "password": $("input#password").val(), "remember": true},
			dataType: "json"
		}).done(function(data)
		{
			$("#loading").hide();
			if(data.results[0] == "Wrong username/password")
			{
				$("#auth").fadeIn(500);
				$("#authErr").fadeIn(600);
			}
			else
			{

				$("#content").fadeIn(500);
			}
		});
	}
});<|endoftext|>


<commit_before>$(document).ready(function () {
  var nrOfEntries = 5,
      lineChart,
      pieCharts = [],
      barCharts = [],
      monthNames = [ "November", "Dezember", "Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober" ],
      months = [],
      totalBarData = [],
      totalPieData = [],
      pieColors =      [ "#F00", "#CF0", "#0F6", "#06F", "#C0F" ],
      pieColorsLight = [ "rgba(255, 0, 0, 0.75)", "rgba(204,255,0,0.75)", "rgba(0, 255, 102, 0.75)", "rgba(0, 102, 255, 0.75)", "rgba(204, 0, 255, 0.75)" ],
      barColors =      [ "rgba(255, 0, 0, 0.6)", "rgba(204,255,0,0.6)", "rgba(0, 255, 102, 0.6)", "rgba(0, 102, 255, 0.6)", "rgba(204, 0, 255, 0.6)" ],
      barColorsLight = [ "rgba(255, 0, 0, 0.4)", "rgba(204,255,0,0.4)", "rgba(0, 255, 102, 0.4)", "rgba(0, 102, 255, 0.4)", "rgba(204, 0, 255, 0.4)" ],
      lineChartData = {
        labels : [],
        scaleBeginAtZero: true,
        datasets : [{
          label: "Total über Zeit",
          fillColor : "rgba(151,187,220,0.4)",
          strokeColor : "rgb(151,187,220)",
          pointColor : "rgb(151,187,220)",
          pointStrokeColor : "#fff",
          pointHighlightFill : "#fff",
          pointHighlightStroke : "rgb(151,187,220)",
          data : []
        }]
      },
      pieData = function() {
        var data = [];
        for( var i = 0; i < nrOfEntries; i++ ) {
          data.push({
            value: 0,
            label: "",
            color: pieColors[i],
            highlight: pieColorsLight[i]
          });
        }
        return data;
      }(),
      barData,
      barDataTemplate = {
        labels : [],
        datasets : [{
          fillColor : barColors,
          strokeColor : "rgba(151,187,220,0.8)",
          highlightFill : barColorsLight,
          highlightStroke : "rgba(151,187,220,1)",
          data : []
        }]
      };

  Chart.defaults.global.animation = false;
  Chart.defaults.global.animationSteps = 30;
  Chart.defaults.global.animationEasing = "easeInOutQuart";
  Chart.defaults.global.scaleOverride = true;
  Chart.defaults.global.scaleSteps = 5;
  Chart.defaults.global.scaleStepWidth = 20;
  Chart.defaults.global.scaleStartValue = 0;
  Chart.defaults.global.scaleFontSize = 16;

  //First month was November
  var getMonthName = function( lqbIndex ) { return monthNames[ (lqbIndex-1) % 12 ]; };

  var createCharts = function() {
    _.each( months, function( m ){
      var pieTitleHTML = '
'+ getMonthName( m.id ) +'
',
          pieChartHTML = '
<canvas height="150" width="150" class="piechart" id="piechart_' + m.id + '"></canvas>
',
          pieLegendHTML = '

';

      $("#pieChartTable").append('
' + pieTitleHTML + '

' + pieChartHTML +'	' + pieLegendHTML + '
')

      $( '
'+ getMonthName( m.id ) +'
' ).insertBefore( "#insertBarChart" );
      $( '
<canvas height="300" width="600" class="barchart" id="barchart_' + m.id + '"></canvas>
' ).insertBefore( "#insertBarChart" );
    });
  };

  var updatePieLegend = function( monthIndex, index, text, value ){
    var node = $("#pieLegend_"+ monthIndex +" li")[index];
    $(node).children(".color").css("border-color", pieColors[index] );
    $(node).children(".text").html( text + ' (' + value + '%)' );
  };

  var drawCharts = function() {
    var ctx = $("#chart-area1")[0].getContext("2d");
    lineChart = new Chart(ctx).Line( lineChartData );

    var i = 0;
    _.each( months, function( m ) {
      var tempPieCTX = $("#piechart_"+ (m.id) )[0].getContext("2d"),
          tempPie = new Chart(tempPieCTX).Pie( pieData[i].data, {
            animationEasing: "easeInOutQuart",
            animationSteps: 30
          });
      _.each( pieData[i].data, function(dataPoint, relIndex){
        updatePieLegend( m.id, relIndex, dataPoint.label, dataPoint.value );
      });
      pieCharts.push(tempPie);

      var tempBarCTX = $("#barchart_"+ (m.id) )[0].getContext("2d"),
          tempBarData = _.extend( barDataTemplate, { labels: bardata[i].labels } );

      tempBarData.datasets[0].data = bardata[i].values;

      var tempBar = new Chart(tempBarCTX).Bar(tempBarData, {
            animationEasing: "easeInOutQuart",
            animationSteps: 30
          });
      barCharts.push(tempBar);
      i++;
    });
  };

  var getData = function() {
    $.ajax({
      url: "php/getData.php",
      type: "POST",
      dataType : 'json',
      success: function( data ){

        _.each(data, function(val, key) {
          if ( key.indexOf("_t") <0 ) return;
          var group = key.substr(key.lastIndexOf("_t")+2),
              month = _.find( months, function( m ) {
                return m.id === parseInt( group );
              });

          if ( !month ) { // create new month if not found yet
            month = {
              id: parseInt( group ),
              words: [],
              values: [],
              weights: [],
              result: 0
            };
            months.push( month );
          }

          // put into correct array
          if ( key.indexOf( "Zufriedenheit" ) >= 0 ) {
            month.values.push({
              id: key.substr( key.indexOf("_t"+group) -1, 1),
              val: val ? val.trim() : ""
            });
          } else if ( key.indexOf( "Gewichtung" ) >= 0 ) {
            month.weights.push({
              id: key.substr( key.indexOf("_t"+group) -1, 1),
              val: val
            })
          } else if ( key.indexOf( "Aspekt" ) >= 0 ) {
            month.words.push({
              id: key.substr( key.indexOf( "Aspekt_" ) + 7, 1),
              val: val
            })
          } else if ( key.toLowerCase().indexOf( "seiqol" ) >= 0 ) {
            month.result = val;
          }
        });

        // Remove months with no result, insufficient data, or empty words.
        // Careful: First month is different, as there wasn't a Stichwort yet.
        months = _.reject( months, function(m) {
          return !m.result ||
                 m.words.length !== 5 ||
                 m.values.length !== 5 ||
                 m.weights.length !== 5 ||
                 _.any( m.words, function(w){ return _.isEmpty( w.val.trim() ); });
        });

        // limit it to the last 6 months
        months = _.last( months, 6 );

        _.each( months, function(m) {
          // LINECHART
          if ( m.result && parseInt( m.result ) ) {
            lineChartData.labels.push( getMonthName( m.id ) );
            lineChartData.datasets[0].data.push(  parseInt( m.result ) );
          }

          // PIE
          totalPieData.push({
            id: m.id,
            name: getMonthName( m.id ),
            data: []
          });

          // BARCHART
          totalBarData.push({
            id: m.id,
            name: getMonthName( m.id ),
            labels: [],
            values: [],
            weights: []
          });
          _.each( m.words, function(w) {
            _.last( totalBarData ).labels.push( w.val );
          });
          _.each( m.values, function(v) {
            _.last( totalBarData ).values.push( v.val );
          });
          _.each( m.weights, function(w, index) {
            _.last( totalBarData ).weights.push( w.val );

            _.last( totalPieData ).data.push({
              label: _.last( totalBarData ).labels[ index ],
              value: w.val
            });
          });

        });

        createCharts();

        bardata = totalBarData;
        pieData = totalPieData;

        drawCharts();

        window.print();
      }
    }).fail(function( data ) {});
  };

  getData();
});
<commit_msg>prevent too long bar chart labels<commit_after>$(document).ready(function () {
  var nrOfEntries = 5,
      lineChart,
      pieCharts = [],
      barCharts = [],
      monthNames = [ "November", "Dezember", "Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober" ],
      months = [],
      totalBarData = [],
      totalPieData = [],
      pieColors =      [ "#F00", "#CF0", "#0F6", "#06F", "#C0F" ],
      pieColorsLight = [ "rgba(255, 0, 0, 0.75)", "rgba(204,255,0,0.75)", "rgba(0, 255, 102, 0.75)", "rgba(0, 102, 255, 0.75)", "rgba(204, 0, 255, 0.75)" ],
      barColors =      [ "rgba(255, 0, 0, 0.6)", "rgba(204,255,0,0.6)", "rgba(0, 255, 102, 0.6)", "rgba(0, 102, 255, 0.6)", "rgba(204, 0, 255, 0.6)" ],
      barColorsLight = [ "rgba(255, 0, 0, 0.4)", "rgba(204,255,0,0.4)", "rgba(0, 255, 102, 0.4)", "rgba(0, 102, 255, 0.4)", "rgba(204, 0, 255, 0.4)" ],
      lineChartData = {
        labels : [],
        scaleBeginAtZero: true,
        datasets : [{
          label: "Total über Zeit",
          fillColor : "rgba(151,187,220,0.4)",
          strokeColor : "rgb(151,187,220)",
          pointColor : "rgb(151,187,220)",
          pointStrokeColor : "#fff",
          pointHighlightFill : "#fff",
          pointHighlightStroke : "rgb(151,187,220)",
          data : []
        }]
      },
      pieData = function() {
        var data = [];
        for( var i = 0; i < nrOfEntries; i++ ) {
          data.push({
            value: 0,
            label: "",
            color: pieColors[i],
            highlight: pieColorsLight[i]
          });
        }
        return data;
      }(),
      barData,
      barDataTemplate = {
        labels : [],
        datasets : [{
          fillColor : barColors,
          strokeColor : "rgba(151,187,220,0.8)",
          highlightFill : barColorsLight,
          highlightStroke : "rgba(151,187,220,1)",
          data : []
        }]
      };

  Chart.defaults.global.animation = false;
  Chart.defaults.global.animationSteps = 30;
  Chart.defaults.global.animationEasing = "easeInOutQuart";
  Chart.defaults.global.scaleOverride = true;
  Chart.defaults.global.scaleSteps = 5;
  Chart.defaults.global.scaleStepWidth = 20;
  Chart.defaults.global.scaleStartValue = 0;
  Chart.defaults.global.scaleFontSize = 16;

  //First month was November
  var getMonthName = function( lqbIndex ) { return monthNames[ (lqbIndex-1) % 12 ]; };

  var createCharts = function() {
    _.each( months, function( m ){
      var pieTitleHTML = '
'+ getMonthName( m.id ) +'
',
          pieChartHTML = '
<canvas height="150" width="150" class="piechart" id="piechart_' + m.id + '"></canvas>
',
          pieLegendHTML = '

';

      $("#pieChartTable").append('
' + pieTitleHTML + '

' + pieChartHTML +'	' + pieLegendHTML + '
')

      $( '
'+ getMonthName( m.id ) +'
' ).insertBefore( "#insertBarChart" );
      $( '
<canvas height="300" width="600" class="barchart" id="barchart_' + m.id + '"></canvas>
' ).insertBefore( "#insertBarChart" );
    });
  };

  var updatePieLegend = function( monthIndex, index, text, value ){
    var node = $("#pieLegend_"+ monthIndex +" li")[index];
    $(node).children(".color").css("border-color", pieColors[index] );
    $(node).children(".text").html( text + ' (' + value + '%)' );
  };

  var drawCharts = function() {
    var ctx = $("#chart-area1")[0].getContext("2d");
    lineChart = new Chart(ctx).Line( lineChartData );

    var i = 0;
    _.each( months, function( m ) {
      var tempPieCTX = $("#piechart_"+ (m.id) )[0].getContext("2d"),
          tempPie = new Chart(tempPieCTX).Pie( pieData[i].data, {
            animationEasing: "easeInOutQuart",
            animationSteps: 30
          });
      _.each( pieData[i].data, function(dataPoint, relIndex){
        updatePieLegend( m.id, relIndex, dataPoint.label, dataPoint.value );
      });
      pieCharts.push(tempPie);

      var tempBarCTX = $("#barchart_"+ (m.id) )[0].getContext("2d"),
          tempBarData = _.extend( barDataTemplate, { labels: bardata[i].labels } );

      tempBarData.datasets[0].data = bardata[i].values;

      _.each( tempBarData.labels, function(val, index){
        tempBarData.labels[index] = val.length > 15 ? val.substr( 0, 12 ) + "..." : val;
      } );

      var tempBar = new Chart(tempBarCTX).Bar(tempBarData, {
            animationEasing: "easeInOutQuart",
            animationSteps: 30
          });
      barCharts.push(tempBar);
      i++;
    });
  };

  var getData = function() {
    $.ajax({
      url: "php/getData.php",
      type: "POST",
      dataType : 'json',
      success: function( data ){

        _.each(data, function(val, key) {
          if ( key.indexOf("_t") <0 ) return;
          var group = key.substr(key.lastIndexOf("_t")+2),
              month = _.find( months, function( m ) {
                return m.id === parseInt( group );
              });

          if ( !month ) { // create new month if not found yet
            month = {
              id: parseInt( group ),
              words: [],
              values: [],
              weights: [],
              result: 0
            };
            months.push( month );
          }

          // put into correct array
          if ( key.indexOf( "Zufriedenheit" ) >= 0 ) {
            month.values.push({
              id: key.substr( key.indexOf("_t"+group) -1, 1),
              val: val ? val.trim() : ""
            });
          } else if ( key.indexOf( "Gewichtung" ) >= 0 ) {
            month.weights.push({
              id: key.substr( key.indexOf("_t"+group) -1, 1),
              val: val
            })
          } else if ( key.indexOf( "Aspekt" ) >= 0 ) {
            month.words.push({
              id: key.substr( key.indexOf( "Aspekt_" ) + 7, 1),
              val: val
            })
          } else if ( key.toLowerCase().indexOf( "seiqol" ) >= 0 ) {
            month.result = val;
          }
        });

        // Remove months with no result, insufficient data, or empty words.
        // Careful: First month is different, as there wasn't a Stichwort yet.
        months = _.reject( months, function(m) {
          return !m.result ||
                 m.words.length !== 5 ||
                 m.values.length !== 5 ||
                 m.weights.length !== 5 ||
                 _.any( m.words, function(w){ return _.isEmpty( w.val.trim() ); });
        });

        // limit it to the last 6 months
        months = _.last( months, 6 );

        _.each( months, function(m) {
          // LINECHART
          if ( m.result && parseInt( m.result ) ) {
            lineChartData.labels.push( getMonthName( m.id ) );
            lineChartData.datasets[0].data.push(  parseInt( m.result ) );
          }

          // PIE
          totalPieData.push({
            id: m.id,
            name: getMonthName( m.id ),
            data: []
          });

          // BARCHART
          totalBarData.push({
            id: m.id,
            name: getMonthName( m.id ),
            labels: [],
            values: [],
            weights: []
          });
          _.each( m.words, function(w) {
            _.last( totalBarData ).labels.push( w.val );
          });
          _.each( m.values, function(v) {
            _.last( totalBarData ).values.push( v.val );
          });
          _.each( m.weights, function(w, index) {
            _.last( totalBarData ).weights.push( w.val );

            _.last( totalPieData ).data.push({
              label: _.last( totalBarData ).labels[ index ],
              value: w.val
            });
          });

        });

        createCharts();

        bardata = totalBarData;
        pieData = totalPieData;

        drawCharts();

        window.print();
      }
    }).fail(function( data ) {});
  };

  getData();
});
<|endoftext|>


<commit_before>var today = new Date();

function listOverdues () {
  var overdue_array = [];
  for (var i = 0; i < contact_array.length; i++) {
    contact_array[i].details.next
  }
}
<commit_msg>hello world test<commit_after>var today = new Date();

function listOverdues () {
  var overdue_array = [];
  for (var i = 0; i < contact_array.length; i++) {
    contact_array[i].details.next
  }
}

hello world;
<|endoftext|>


<commit_before>var playerStatus;
(function () {
    var options = {
        "player": {
            "url": "uppod/uppod.swf",
            "width": 280,
            "height": 37,
            "version": "9.0.115.0",
            "style": "uppod/audio154-647.txt"
        }
    };
    var channels = [
        {
            "id": "za-oblakami-relax",
            "comment": "За облаками Relax",
            "style": "uppod/audio154-647.txt",
            "url": "http://195.88.63.114:8000/relax",
            "bgcolor": "079ed7",
            "blockStyle": "dark",
            "site": "http://www.zaoblakami.ru"
        },
        {
            "id": "lite-sound-session",
            "comment": "Light sound session",
            "style": "uppod/audio154-808.txt",
            "url": "http://www.litesoundsession.com:8000/lite",
            "bgcolor": "388600",
            "blockStyle": "dark",
            "site": "http://www.litesoundsession.com"
        },
        {
            "id": "relax-fm",
            "comment": "Relax FM",
            "style": "uppod/audio154-809.txt",
            "url": "http://eu4.101.ru:8000/v13_1",
            "bgcolor": "ffdc8b",
            "blockStyle": "light",
            "site": "www.relax-fm.ru"
        },
        {
            "id": "sanfm-relax",
            "style": "uppod/audio154-810.txt",
            "comment": "SanFM Relax",
            "url": "http://sanfm.ru:8000/relax",
            "bgcolor": "bfe253",
            "blockStyle": "light",
            "site": "http://sanfm.ru/relax/"
        },
        {
            "id": "radio-tunes-relaxation",
            "comment": "RadioTunes Relaxation",
            "style": "uppod/audio154-811.txt",
            "url": "http://pub5.radiotunes.com/radiotunes_relaxation_aacplus?type=.flv",
            "bgcolor": "005caa",
            "blockStyle": "dark",
            "site": "http://www.radiotunes.com/relaxation"
        },
        {
            "id": "relax-ua",
            "comment": "Relax (UA)",
            "style": "uppod/audio154-812.txt",
            "url": "http://stream.radiorelax.com.ua/Relax",
            "bgcolor": "white",
            "blockStyle": "white",
            "site": "http://www.radiorelax.com.ua"
        }
    ];

    channels.forEach(function(el) {
        $('
'
                    + '

'
                    + '

'
                    + '

'
                    + '
' + el.site + '
'
                + '
')
            .on("click", function(e) {
                if (e.target.tagName != "OBJECT") uppodSend($(this).data('player-id'), 'toggle');
            })
            .appendTo($('#wrapper'));

        var flashvars = {
            "uid": el.id,
            "file": el.url,
            "comment": el.comment,
            "st": el.style || options.player.style
        };
        var params = {
            "id": el.id,
            "bgcolor": el.bgcolor,
            "allowScriptAccess": "always"
        };
        new swfobject.embedSWF(options.player.url, el.id, options.player.width, options.player.height, options.player.version, false, flashvars, params);
    });

    var display = function (playerId, text) {
        var b = $('#' + playerId).parent().find('.display');
        b.text(text);
    };

    playerStatus = function (playerId, status) {
        var firstChar = document.title.substring(0, 1);
        switch (status) {
            case "play":
                display(playerId, "\u25b8");
                if (firstChar == "\u25b8") return;
                if (firstChar == "\u28e4") document.title = document.title.substring(2);
                document.title = "\u25b8 " + document.title;
                break;
            case "stop":
                display(playerId, "");
                if (firstChar == "\u25b8" || firstChar == "\u28e4") document.title = document.title.substring(2);
                break;
            case "pause":
                display(playerId, "\u28e4");
                if (firstChar == "\u28e4") return;
                if (firstChar == "\u25b8") document.title = document.title.substring(2);
                document.title = "\u28e4 " + document.title;
                break;
        }
    };
})();

<commit_msg>Radio Relax (UA) stream url fix<commit_after>var playerStatus;
(function () {
    var options = {
        "player": {
            "url": "uppod/uppod.swf",
            "width": 280,
            "height": 37,
            "version": "9.0.115.0",
            "style": "uppod/audio154-647.txt"
        }
    };
    var channels = [
        {
            "id": "za-oblakami-relax",
            "comment": "За облаками Relax",
            "style": "uppod/audio154-647.txt",
            "url": "http://195.88.63.114:8000/relax",
            "bgcolor": "079ed7",
            "blockStyle": "dark",
            "site": "http://www.zaoblakami.ru"
        },
        {
            "id": "lite-sound-session",
            "comment": "Light sound session",
            "style": "uppod/audio154-808.txt",
            "url": "http://www.litesoundsession.com:8000/lite",
            "bgcolor": "388600",
            "blockStyle": "dark",
            "site": "http://www.litesoundsession.com"
        },
        {
            "id": "relax-fm",
            "comment": "Relax FM",
            "style": "uppod/audio154-809.txt",
            "url": "http://eu4.101.ru:8000/v13_1",
            "bgcolor": "ffdc8b",
            "blockStyle": "light",
            "site": "www.relax-fm.ru"
        },
        {
            "id": "sanfm-relax",
            "style": "uppod/audio154-810.txt",
            "comment": "SanFM Relax",
            "url": "http://sanfm.ru:8000/relax",
            "bgcolor": "bfe253",
            "blockStyle": "light",
            "site": "http://sanfm.ru/relax/"
        },
        {
            "id": "radio-tunes-relaxation",
            "comment": "RadioTunes Relaxation",
            "style": "uppod/audio154-811.txt",
            "url": "http://pub5.radiotunes.com/radiotunes_relaxation_aacplus?type=.flv",
            "bgcolor": "005caa",
            "blockStyle": "dark",
            "site": "http://www.radiotunes.com/relaxation"
        },
        {
            "id": "relax-ua",
            "comment": "Relax (UA)",
            "style": "uppod/audio154-812.txt",
            "url": "http://online-radiorelax2.tavrmedia.ua/RadioRelax_Instrumental",
            "bgcolor": "white",
            "blockStyle": "white",
            "site": "http://www.radiorelax.com.ua"
        }
    ];

    channels.forEach(function(el) {
        $('
'
                    + '

'
                    + '

'
                    + '

'
                    + '
' + el.site + '
'
                + '
')
            .on("click", function(e) {
                if (e.target.tagName != "OBJECT") uppodSend($(this).data('player-id'), 'toggle');
            })
            .appendTo($('#wrapper'));

        var flashvars = {
            "uid": el.id,
            "file": el.url,
            "comment": el.comment,
            "st": el.style || options.player.style
        };
        var params = {
            "id": el.id,
            "bgcolor": el.bgcolor,
            "allowScriptAccess": "always"
        };
        new swfobject.embedSWF(options.player.url, el.id, options.player.width, options.player.height, options.player.version, false, flashvars, params);
    });

    var display = function (playerId, text) {
        var b = $('#' + playerId).parent().find('.display');
        b.text(text);
    };

    playerStatus = function (playerId, status) {
        var firstChar = document.title.substring(0, 1);
        switch (status) {
            case "play":
                display(playerId, "\u25b8");
                if (firstChar == "\u25b8") return;
                if (firstChar == "\u28e4") document.title = document.title.substring(2);
                document.title = "\u25b8 " + document.title;
                break;
            case "stop":
                display(playerId, "");
                if (firstChar == "\u25b8" || firstChar == "\u28e4") document.title = document.title.substring(2);
                break;
            case "pause":
                display(playerId, "\u28e4");
                if (firstChar == "\u28e4") return;
                if (firstChar == "\u25b8") document.title = document.title.substring(2);
                document.title = "\u28e4 " + document.title;
                break;
        }
    };
})();

<|endoftext|>