<commit_before>function midiMessageReceived( ev ) {
    var cmd = ev.data[0] >> 4;
    var channel = ev.data[0] & 0xf;
    var noteNumber = ev.data[1];
    var velocity = 0;
    if (ev.data.length > 2)
      velocity = ev.data[2];

    if ( cmd==8 || ((cmd==9)&&(velocity==0)) ) { // with MIDI, note on with velocity zero is the same as note off
      // note off
      if (channel!=9)
        noteOff( noteNumber );
    } else if (cmd == 9) {
      // note on
      console.log("Note on - channel: " + channel + " note: " + noteNumber + " velocity: " + velocity );
      if (channel == 9)
        playDrum(noteNumber, velocity);
      else
        noteOn( noteNumber, velocity);
    } else if (cmd == 11) {
      controller( noteNumber, velocity);
    } else if ((ev.data.length == 6) &&
      (ev.data[0] == 0xf0) &&
      (ev.data[1] == 0x7f) &&
      (ev.data[3] == 0x06) &&
      (ev.data[5] == 0xf7) ) { // MIDI Machine Control (MMC) message
      switch (ev.data[4]) {
        case 0x01: // stop
          handleStop();
          break;
        case 0x02: // start
          handlePlay();
          break;
      }
    } else {
      console.log("unrecognized message");
    }
}

function nonControllrMidiMessageReceived( ev ) {
  var cmd = ev.data[0] >> 4;
  var channel = ev.data[0] & 0xf;
  var noteNumber = ev.data[1];
  var velocity = 0;
  if (ev.data.length > 2)
    velocity = ev.data[2];

  if ((cmd==9)&&(velocity!=0)) {
    // note on
    console.log("Note on - channel: " + channel + " note: " + noteNumber + " velocity: " + velocity );
    playDrum(noteNumber, velocity);
  }
}

var selectMIDIIn = null;
var selectMIDIOut = null;
var midiAccess = null;
var midiIn = null;
var midiOut = null;
var outputIsLivid = false;

function changeMIDIIn( ev ) {
  if (midiIn)
    midiIn.onmidimessage = null;
  var id = ev.target[ev.target.selectedIndex].value;
  if ((typeof(midiAccess.inputs) == "function"))   //Old Skool MIDI inputs() code
    midiIn = midiAccess.inputs()[ev.target.selectedIndex];
  else
    midiIn = midiAccess.inputs.get(id);
  if (midiIn)
    midiIn.onmidimessage = midiMessageReceived;
}

function changeMIDIOut( ev ) {
  var id = ev.target[ev.target.selectedIndex].value;

  if ((typeof(midiAccess.outputs) == "function"))   //Old Skool MIDI outputs() code
    midiOut = midiAccess.outputs()[ev.target.selectedIndex];
  else
    midiOut = midiAccess.outputs.get(id);

  outputIsLivid = midiOut.name.indexOf("Controls") != -1;
  if (outputIsLivid) {
    updateActiveInstruments();
    // light up the play button
    midiOut.send( [0x90, 3, 32] );
    // turn off the stop button
    midiOut.send( [0x80, 7, 1] );
  }
}

function onMIDIInit( midi ) {
  midiAccess = midi;
  selectMIDIIn=document.getElementById("midiIn");
  selectMIDIOut=document.getElementById("midiOut");

  // clear the MIDI input select
  selectMIDIIn.options.length = 0;
  selectMIDIOut.options.length = 0;

  if ((typeof(midiAccess.inputs) == "function")) {  //Old Skool MIDI inputs() code
    var list=midiAccess.inputs();

    for (var i=0; i<list.length; i++) {
      var str=list[i].name.toString();
      if (!midiIn && (str.indexOf("Controls") != -1)) {
        selectMIDIIn.appendChild(new Option(list[i].name,list[i].id,true,true));
        midiIn = list[i];
      } else
        selectMIDIIn.appendChild(new Option(list[i].name,list[i].id,false,false));
    }
    if (!midiIn)
      midiIn = list[0];
    midiIn.onmidimessage = midiMessageReceived;

    list=midiAccess.outputs();

    for (var i=0; i<list.length; i++) {
      var str=list[i].name.toString();
      if (!midiOut && (str.indexOf("Controls") != -1)) {
        selectMIDIOut.appendChild(new Option(list[i].name,list[i].id,true,true));
        midiOut = list[i];
      } else
        selectMIDIOut.appendChild(new Option(list[i].name,list[i].id,false,false));
    }
    if (!midiOut)
      midiOut = list[0];
  } else {  // new MIDIMap implementation:
    var inputs=midiAccess.inputs.values();
    for ( var input = inputs.next(); input && !input.done; input = inputs.next()) {
      input = input.value;
      var str=input.name.toString();
      var preferred = !midiIn && (str.indexOf("Controls") != -1);

      selectMIDIIn.appendChild(new Option(input.name,input.id,preferred,preferred));
      if (preferred) {
        midiIn = input;
        midiIn.onmidimessage = midiMessageReceived;
      }
    }
    if (!midiIn)
      midiIn = midiAccess.inputs.values().next().value;

    var outputs=midiAccess.outputs.values();
    for ( var output = outputs.next(); output && !output.done; output = outputs.next()) {
      output = output.value;
      var str=output.name.toString();
      var preferred = !midiOut && (str.indexOf("Controls") != -1);

      selectMIDIOut.appendChild(new Option(output.name,output.id,preferred,preferred));
      if (preferred) {
        midiOut = output;
        outputIsLivid = true;
      }
    }
    if (!midiOut)
      midiOut = midiAccess.outputs.values().next().value;
  }
  selectMIDIIn.onchange = changeMIDIIn;
  selectMIDIOut.onchange = changeMIDIOut;

  setActiveInstrument( 0 );
  updateActiveInstruments();

  if (outputIsLivid) {
    // light up the play button
    midiOut.send( [0x90, 3, 32] );
    // turn off the stop button
    midiOut.send( [0x80, 7, 1] );
  }
}

function showBeat(index) {
  if (midiOut && outputIsLivid)
    midiOut.send( [0x90, 16 + index, ((index%4)==0) ? 0x03 : 0x07]);
}

function hideBeat(index) {
  if (midiOut && outputIsLivid)
    midiOut.send( [0x80, 16 + index, 0x00] );
}

function onMIDISystemError( msg ) {
  console.log( "Error encountered:" + msg );
}
//init: start up MIDI
window.addEventListener('load', function() {
  navigator.requestMIDIAccess().then( onMIDIInit, onMIDISystemError );
});

var currentlyActiveInstrument = 0;

function keyForInstrument(index) {
    if (index <3)
      return index;
    else
      return index+1;
}

function colorForIntrument(index) {
  if (index<0 || index>6)
    return 0;

  if (index == 1)
    return 64;
  else
    return Math.pow(2,index);
}

var instrumentActive = [true,true,true,true,true,true];

function updateActiveInstruments() {
  if (!midiOut || !(outputIsLivid))
    return;

  for (var i=0;i<6; i++)
    if (instrumentActive[i])
      midiOut.send( [0x90, keyForInstrument(i)+8, colorForIntrument(i)] );
    else
      midiOut.send( [0x80, keyForInstrument(i)+8, 0x00] );
 }

function setActiveInstrument(index) {
  //turn off the last lit-up instrument
  if (midiOut&&outputIsLivid)
    midiOut.send( [0x80, keyForInstrument(currentlyActiveInstrument), 0x00] );

  currentlyActiveInstrument = index;

  // turn on the new instrument button
  if (midiOut&&outputIsLivid)
    midiOut.send( [0x90, keyForInstrument(index), colorForIntrument(index)] );

  var notes = theBeat.rhythm1;

  switch (currentlyActiveInstrument) {
      case 0: notes = theBeat.rhythm1; break;
      case 1: notes = theBeat.rhythm2; break;
      case 2: notes = theBeat.rhythm3; break;
      case 3: notes = theBeat.rhythm4; break;
      case 4: notes = theBeat.rhythm5; break;
      case 5: notes = theBeat.rhythm6; break;
  }

  for (var beat=0; beat<16; beat++)
    showCorrectNote( beat, notes[beat] );
}

function showCorrectNote( index, note ) {
  // note==0 -> off
  // note==1 -> light hit
  // note==2 -> loud hit

  if (midiOut && outputIsLivid)
    midiOut.send( [0x90, 32 + index, note * 32] );
}

function toggleBeat(rhythmIndex) {
    var notes = theBeat.rhythm1;

    switch (currentlyActiveInstrument) {
        case 0: notes = theBeat.rhythm1; break;
        case 1: notes = theBeat.rhythm2; break;
        case 2: notes = theBeat.rhythm3; break;
        case 3: notes = theBeat.rhythm4; break;
        case 4: notes = theBeat.rhythm5; break;
        case 5: notes = theBeat.rhythm6; break;
    }

    notes[rhythmIndex] = (notes[rhythmIndex] + 1) % 3;

    drawNote(notes[rhythmIndex], rhythmIndex, currentlyActiveInstrument);

    showCorrectNote( rhythmIndex, notes[rhythmIndex] );

/* // not sure if we want to play notes when toggling on MIDI device
    var note = notes[rhythmIndex];

    if (note) {
        switch(instrumentIndex) {
        case 0:  // Kick
          playNote(currentKit.kickBuffer, false, 0,0,-2, 0.5 * theBeat.effectMix, volumes[note] * 1.0, kickPitch, 0);
          break;

        case 1:  // Snare
          playNote(currentKit.snareBuffer, false, 0,0,-2, theBeat.effectMix, volumes[note] * 0.6, snarePitch, 0);
          break;

        case 2:  // Hihat
          // Pan the hihat according to sequence position.
          playNote(currentKit.hihatBuffer, true, 0.5*rhythmIndex - 4, 0, -1.0, theBeat.effectMix, volumes[note] * 0.7, hihatPitch, 0);
          break;

        case 3:  // Tom 1
          playNote(currentKit.tom1, false, 0,0,-2, theBeat.effectMix, volumes[note] * 0.6, tom1Pitch, 0);
          break;

        case 4:  // Tom 2
          playNote(currentKit.tom2, false, 0,0,-2, theBeat.effectMix, volumes[note] * 0.6, tom2Pitch, 0);
          break;

        case 5:  // Tom 3
          playNote(currentKit.tom3, false, 0,0,-2, theBeat.effectMix, volumes[note] * 0.6, tom3Pitch, 0);
          break;
        }
    }
*/

}

function noteOn( noteNumber, velocity) {
  if (noteNumber < 16) {  // 4x4 grid
    switch (noteNumber) {
      case 0:
      case 1:
      case 2:
        setActiveInstrument( noteNumber );
        return;
      case 4:
      case 5:
      case 6:
        setActiveInstrument( noteNumber-1 );
        return;

      case 12:
      case 13:
      case 14:
        noteNumber--; // adjust number and fall through
      case 8:
      case 9:
      case 10:
        instrumentActive[noteNumber-8] = !instrumentActive[noteNumber-8];
        updateActiveInstruments();
        break;

      case 3:  // start playback
        handlePlay();
        return;
      case 7:  // stop playback
        handleStop();
        return;
    }
  } else if ((noteNumber>=32) && (noteNumber<48))  // bottom row - beats
    toggleBeat(noteNumber-32);
}

function noteOff( noteNumber ) {

}

var filterEngaged = false;

function controller(number, data) {
  switch (number) {
    case 4:  // Tempo
      theBeat.tempo = kMinTempo + data;
      document.getElementById('tempo').innerHTML = theBeat.tempo;
      return;
    case 8:  // Effect level
      sliderSetValue( 'effect_thumb', data/127);
      updateControls();
      return;
    case 12:  // Kick pitch
      sliderSetValue( 'kick_thumb', data/127);
      updateControls();
      return;
    case 16:  // Snare pitch
      sliderSetValue( 'snare_thumb', data/127);
      updateControls();
      return;
    case 20:  // Hi-hat pitch
      sliderSetValue( 'hihat_thumb', data/127);
      updateControls();
      return;
    case 24:  // Tom1 pitch
      sliderSetValue( 'tom1_thumb', data/127);
      updateControls();
      return;
    case 28:  // Tom2 pitch
      sliderSetValue( 'tom2_thumb', data/127);
      updateControls();
      return;
    case 32:  // Tom3 pitch
      sliderSetValue( 'tom3_thumb', data/127);
      updateControls();
      return;

    case 48:  // Filter cutoff
      if ( !filterEngaged && data<127)
        return;
      filterEngaged = true;
      setFilterCutoff( data/127.0 );
      // echo back out - this lights up the control
      if (midiOut&&outputIsLivid)
        midiOut.send( [11<<4, 48, data] );
      return;

    case 51:  // Filter Q
      setFilterQ( data * 20.0/127.0 );
      // echo back out - this lights up the control
      if (midiOut&&outputIsLivid)
        midiOut.send( [11<<4, 48, data] );
      return;

  }
}<commit_msg>Patch for input.<commit_after>function midiMessageReceived( ev ) {
    var cmd = ev.data[0] >> 4;
    var channel = ev.data[0] & 0xf;
    var noteNumber = ev.data[1];
    var velocity = 0;
    if (ev.data.length > 2)
      velocity = ev.data[2];

    if ( cmd==8 || ((cmd==9)&&(velocity==0)) ) { // with MIDI, note on with velocity zero is the same as note off
      // note off
      if (channel!=9)
        noteOff( noteNumber );
    } else if (cmd == 9) {
      // note on
      console.log("Note on - channel: " + channel + " note: " + noteNumber + " velocity: " + velocity );
      if ((channel == 9)||(channel==1))
        playDrum(noteNumber, velocity);
      else
        noteOn( noteNumber, velocity);
    } else if (cmd == 11) {
      console.log("controller: channel: " + channel + " controller: " + noteNumber + " value: " + velocity );
      controller( noteNumber, velocity);
    } else if ((ev.data.length == 6) &&
      (ev.data[0] == 0xf0) &&
      (ev.data[1] == 0x7f) &&
      (ev.data[3] == 0x06) &&
      (ev.data[5] == 0xf7) ) { // MIDI Machine Control (MMC) message
      switch (ev.data[4]) {
        case 0x01: // stop
          handleStop();
          break;
        case 0x02: // start
          handlePlay();
          break;
      }
    } else {
      console.log("unrecognized message");
    }
}

function nonControllrMidiMessageReceived( ev ) {
  var cmd = ev.data[0] >> 4;
  var channel = ev.data[0] & 0xf;
  var noteNumber = ev.data[1];
  var velocity = 0;
  if (ev.data.length > 2)
    velocity = ev.data[2];

  if ((cmd==9)&&(velocity!=0)) {
    // note on
    console.log("Note on - channel: " + channel + " note: " + noteNumber + " velocity: " + velocity );
    playDrum(noteNumber, velocity);
  }
}

var selectMIDIIn = null;
var selectMIDIOut = null;
var midiAccess = null;
var midiIn = null;
var midiOut = null;
var outputIsLivid = false;

function changeMIDIIn( ev ) {
  if (midiIn)
    midiIn.onmidimessage = null;
  var id = ev.target[ev.target.selectedIndex].value;
  if ((typeof(midiAccess.inputs) == "function"))   //Old Skool MIDI inputs() code
    midiIn = midiAccess.inputs()[ev.target.selectedIndex];
  else
    midiIn = midiAccess.inputs.get(id);
  if (midiIn)
    midiIn.onmidimessage = midiMessageReceived;
}

function changeMIDIOut( ev ) {
  var id = ev.target[ev.target.selectedIndex].value;

  if ((typeof(midiAccess.outputs) == "function"))   //Old Skool MIDI outputs() code
    midiOut = midiAccess.outputs()[ev.target.selectedIndex];
  else
    midiOut = midiAccess.outputs.get(id);

  outputIsLivid = midiOut.name.indexOf("Controls") != -1;
  if (outputIsLivid) {
    updateActiveInstruments();
    // light up the play button
    midiOut.send( [0x90, 3, 32] );
    // turn off the stop button
    midiOut.send( [0x80, 7, 1] );
  }
}

function onMIDIInit( midi ) {
  midiAccess = midi;
  selectMIDIIn=document.getElementById("midiIn");
  selectMIDIOut=document.getElementById("midiOut");

  // clear the MIDI input select
  selectMIDIIn.options.length = 0;
  selectMIDIOut.options.length = 0;

  if ((typeof(midiAccess.inputs) == "function")) {  //Old Skool MIDI inputs() code
    var list=midiAccess.inputs();

    for (var i=0; i<list.length; i++) {
      var str=list[i].name.toString();
      if (!midiIn && (str.indexOf("Controls") != -1)) {
        selectMIDIIn.appendChild(new Option(list[i].name,list[i].id,true,true));
        midiIn = list[i];
      } else
        selectMIDIIn.appendChild(new Option(list[i].name,list[i].id,false,false));
    }
    if (!midiIn)
      midiIn = list[0];
    midiIn.onmidimessage = midiMessageReceived;

    list=midiAccess.outputs();

    for (var i=0; i<list.length; i++) {
      var str=list[i].name.toString();
      if (!midiOut && (str.indexOf("Controls") != -1)) {
        selectMIDIOut.appendChild(new Option(list[i].name,list[i].id,true,true));
        midiOut = list[i];
      } else
        selectMIDIOut.appendChild(new Option(list[i].name,list[i].id,false,false));
    }
    if (!midiOut)
      midiOut = list[0];
  } else {  // new MIDIMap implementation:
    var inputs=midiAccess.inputs.values();
    for ( var input = inputs.next(); input && !input.done; input = inputs.next()) {
      input = input.value;
      var str=input.name.toString();
      var preferred = !midiIn && (str.indexOf("Controls") != -1);

      selectMIDIIn.appendChild(new Option(input.name,input.id,preferred,preferred));
      if (preferred) {
        midiIn = input;
        midiIn.onmidimessage = midiMessageReceived;
      }
    }
    if (!midiIn) {
      midiIn = midiAccess.inputs.values().next().value;
      midiIn.onmidimessage = midiMessageReceived;
    }

    var outputs=midiAccess.outputs.values();
    for ( var output = outputs.next(); output && !output.done; output = outputs.next()) {
      output = output.value;
      var str=output.name.toString();
      var preferred = !midiOut && (str.indexOf("Controls") != -1);

      selectMIDIOut.appendChild(new Option(output.name,output.id,preferred,preferred));
      if (preferred) {
        midiOut = output;
        outputIsLivid = true;
      }
    }
    if (!midiOut)
      midiOut = midiAccess.outputs.values().next().value;
  }
  selectMIDIIn.onchange = changeMIDIIn;
  selectMIDIOut.onchange = changeMIDIOut;

  setActiveInstrument( 0 );
  updateActiveInstruments();

  if (outputIsLivid) {
    // light up the play button
    midiOut.send( [0x90, 3, 32] );
    // turn off the stop button
    midiOut.send( [0x80, 7, 1] );
  }
}

function showBeat(index) {
  if (midiOut && outputIsLivid)
    midiOut.send( [0x90, 16 + index, ((index%4)==0) ? 0x03 : 0x07]);
}

function hideBeat(index) {
  if (midiOut && outputIsLivid)
    midiOut.send( [0x80, 16 + index, 0x00] );
}

function onMIDISystemError( msg ) {
  console.log( "Error encountered:" + msg );
}
//init: start up MIDI
window.addEventListener('load', function() {
  navigator.requestMIDIAccess().then( onMIDIInit, onMIDISystemError );
});

var currentlyActiveInstrument = 0;

function keyForInstrument(index) {
    if (index <3)
      return index;
    else
      return index+1;
}

function colorForIntrument(index) {
  if (index<0 || index>6)
    return 0;

  if (index == 1)
    return 64;
  else
    return Math.pow(2,index);
}

var instrumentActive = [true,true,true,true,true,true];

function updateActiveInstruments() {
  if (!midiOut || !(outputIsLivid))
    return;

  for (var i=0;i<6; i++)
    if (instrumentActive[i])
      midiOut.send( [0x90, keyForInstrument(i)+8, colorForIntrument(i)] );
    else
      midiOut.send( [0x80, keyForInstrument(i)+8, 0x00] );
 }

function setActiveInstrument(index) {
  //turn off the last lit-up instrument
  if (midiOut&&outputIsLivid)
    midiOut.send( [0x80, keyForInstrument(currentlyActiveInstrument), 0x00] );

  currentlyActiveInstrument = index;

  // turn on the new instrument button
  if (midiOut&&outputIsLivid)
    midiOut.send( [0x90, keyForInstrument(index), colorForIntrument(index)] );

  var notes = theBeat.rhythm1;

  switch (currentlyActiveInstrument) {
      case 0: notes = theBeat.rhythm1; break;
      case 1: notes = theBeat.rhythm2; break;
      case 2: notes = theBeat.rhythm3; break;
      case 3: notes = theBeat.rhythm4; break;
      case 4: notes = theBeat.rhythm5; break;
      case 5: notes = theBeat.rhythm6; break;
  }

  for (var beat=0; beat<16; beat++)
    showCorrectNote( beat, notes[beat] );
}

function showCorrectNote( index, note ) {
  // note==0 -> off
  // note==1 -> light hit
  // note==2 -> loud hit

  if (midiOut && outputIsLivid)
    midiOut.send( [0x90, 32 + index, note * 32] );
}

function toggleBeat(rhythmIndex) {
    var notes = theBeat.rhythm1;

    switch (currentlyActiveInstrument) {
        case 0: notes = theBeat.rhythm1; break;
        case 1: notes = theBeat.rhythm2; break;
        case 2: notes = theBeat.rhythm3; break;
        case 3: notes = theBeat.rhythm4; break;
        case 4: notes = theBeat.rhythm5; break;
        case 5: notes = theBeat.rhythm6; break;
    }

    notes[rhythmIndex] = (notes[rhythmIndex] + 1) % 3;

    drawNote(notes[rhythmIndex], rhythmIndex, currentlyActiveInstrument);

    showCorrectNote( rhythmIndex, notes[rhythmIndex] );

/* // not sure if we want to play notes when toggling on MIDI device
    var note = notes[rhythmIndex];

    if (note) {
        switch(instrumentIndex) {
        case 0:  // Kick
          playNote(currentKit.kickBuffer, false, 0,0,-2, 0.5 * theBeat.effectMix, volumes[note] * 1.0, kickPitch, 0);
          break;

        case 1:  // Snare
          playNote(currentKit.snareBuffer, false, 0,0,-2, theBeat.effectMix, volumes[note] * 0.6, snarePitch, 0);
          break;

        case 2:  // Hihat
          // Pan the hihat according to sequence position.
          playNote(currentKit.hihatBuffer, true, 0.5*rhythmIndex - 4, 0, -1.0, theBeat.effectMix, volumes[note] * 0.7, hihatPitch, 0);
          break;

        case 3:  // Tom 1
          playNote(currentKit.tom1, false, 0,0,-2, theBeat.effectMix, volumes[note] * 0.6, tom1Pitch, 0);
          break;

        case 4:  // Tom 2
          playNote(currentKit.tom2, false, 0,0,-2, theBeat.effectMix, volumes[note] * 0.6, tom2Pitch, 0);
          break;

        case 5:  // Tom 3
          playNote(currentKit.tom3, false, 0,0,-2, theBeat.effectMix, volumes[note] * 0.6, tom3Pitch, 0);
          break;
        }
    }
*/

}

function noteOn( noteNumber, velocity) {
  if (noteNumber < 16) {  // 4x4 grid
    switch (noteNumber) {
      case 0:
      case 1:
      case 2:
        setActiveInstrument( noteNumber );
        return;
      case 4:
      case 5:
      case 6:
        setActiveInstrument( noteNumber-1 );
        return;

      case 12:
      case 13:
      case 14:
        noteNumber--; // adjust number and fall through
      case 8:
      case 9:
      case 10:
        instrumentActive[noteNumber-8] = !instrumentActive[noteNumber-8];
        updateActiveInstruments();
        break;

      case 3:  // start playback
        handlePlay();
        return;
      case 7:  // stop playback
        handleStop();
        return;
    }
  } else if ((noteNumber>=32) && (noteNumber<48))  // bottom row - beats
    toggleBeat(noteNumber-32);
}

function noteOff( noteNumber ) {

}

var filterEngaged = false;

function controller(number, data) {
  switch (number) {
    case 1:
    case 4:  // Tempo
      theBeat.tempo = kMinTempo + data;
      document.getElementById('tempo').innerHTML = theBeat.tempo;
      return;
    case 8:  // Effect level
      sliderSetValue( 'effect_thumb', data/127);
      updateControls();
      return;
    case 12:  // Kick pitch
      sliderSetValue( 'kick_thumb', data/127);
      updateControls();
      return;
    case 16:  // Snare pitch
      sliderSetValue( 'snare_thumb', data/127);
      updateControls();
      return;
    case 20:  // Hi-hat pitch
      sliderSetValue( 'hihat_thumb', data/127);
      updateControls();
      return;
    case 24:  // Tom1 pitch
      sliderSetValue( 'tom1_thumb', data/127);
      updateControls();
      return;
    case 28:  // Tom2 pitch
      sliderSetValue( 'tom2_thumb', data/127);
      updateControls();
      return;
    case 32:  // Tom3 pitch
      sliderSetValue( 'tom3_thumb', data/127);
      updateControls();
      return;

    case 2:
    case 48:  // Filter cutoff
      if ( !filterEngaged && data<127)
        return;
      filterEngaged = true;
      setFilterCutoff( data/127.0 );
      // echo back out - this lights up the control
      if (midiOut&&outputIsLivid)
        midiOut.send( [11<<4, 48, data] );
      return;

    case 3:
    case 51:  // Filter Q
      setFilterQ( data * 20.0/127.0 );
      // echo back out - this lights up the control
      if (midiOut&&outputIsLivid)
        midiOut.send( [11<<4, 48, data] );
      return;

  }
}<|endoftext|>


<commit_before>jQuery(document).ready(function($){
    $(".saiselect").saiSelect({
        placeholder: 'mySelect'
    });
});<commit_msg>master<commit_after>jQuery(document).ready(function($){
    $(".saiselect").saiSelect();
});<|endoftext|>


<commit_before>/*** NAVI ***/
var x = 0, y = 0;

var heartShape = new THREE.Shape();
heartShape.moveTo( x + 5, y + 5 );
heartShape.bezierCurveTo( x + 5, y + 5, x + 4, y, x, y );
heartShape.bezierCurveTo( x - 6, y, x - 6, y + 7,x - 6, y + 7 );
heartShape.bezierCurveTo( x - 6, y + 11, x - 3, y + 15.4, x + 5, y + 19 );

var wing_g = new THREE.ShapeGeometry( heartShape );
var wing_m = new THREE.MeshBasicMaterial( { color: 0xD8EDED } );
var wing = new THREE.Mesh( wing_g, wing_m ) ;
var wing2 = new THREE.Mesh( wing_g, wing_m ) ;

wing.scale.set(.01, .01, .01);
//wing.rotation.x = 1.37;
wing.rotation.x = 1.50; //flip
wing.rotation.y = -0.5; //roll
wing.rotation.z = 5.0; //around
//wing.rotation.z = -1.0;
wing.position.y = 0.06;
wing.position.x = -0.3;

wing2.scale.set(.01, .01, .01);
wing2.rotation.x = 1.37;
wing2.rotation.z = 2.28;
wing2.position.x = 0.30;

var spriteMaterial = new THREE.SpriteMaterial({
  map: loader.load( 'https://sjcobb.github.io/lake-hylia/assets/navi/glow.png' ),
  useScreenCoordinates: false,
  //alignment: THREE.SpriteAlignment.center,
  color: 0x0000ff,
  transparent: false,
  blending: THREE.AdditiveBlending
});
var sprite = new THREE.Sprite( spriteMaterial );
sprite.scale.set(0.7, 0.7, 1.0);

var navi_g = new THREE.SphereGeometry(0.15, 20, 20);
var navi_m = new THREE.MeshPhongMaterial({color: 0xD8EDED, transparent: true, opacity: 0.7, shininess: 30});

navi = new THREE.Mesh( navi_g, navi_m);
navi.add(sprite);
navi.add(wing);
navi.add(wing2);
navi.rotation.x = 0;
navi.rotation.y = 0.5;
navi.rotation.z = 0.3;
scene.add(navi);

var navi_sound = new THREE.PositionalAudio( listener );
audioLoader.load( 'https://sjcobb.github.io/lake-hylia/assets/navi/OOT_Navi_Listen1.wav', function( buffer ) {
  navi_sound.setBuffer( buffer );
  navi_sound.setRefDistance( 0.03 );
  navi_sound.setVolume(100);
  //navi_sound.setLoop(true);
  //navi_sound.play();
});
navi.add( navi_sound );

var rdm_shift = 0;
setInterval(function() {
  rdm_shift = Math.random();
}, 3000);

setTimeout(function() {
  navi_sound.play();
  setInterval(function() {
    navi_sound.play();
  }, 27000);
}, 6000);

function renderNavi() {
  var navi_shiftx = camera.position.x - 1.3 - rdm_shift;
  var navi_shifty = camera.position.y + 2 - rdm_shift;
  navi.position.set(navi_shiftx, navi_shifty, camera.position.z - 4);
}<commit_msg>change assets to https<commit_after>/*** NAVI ***/
var x = 0, y = 0;

var heartShape = new THREE.Shape();
heartShape.moveTo( x + 5, y + 5 );
heartShape.bezierCurveTo( x + 5, y + 5, x + 4, y, x, y );
heartShape.bezierCurveTo( x - 6, y, x - 6, y + 7,x - 6, y + 7 );
heartShape.bezierCurveTo( x - 6, y + 11, x - 3, y + 15.4, x + 5, y + 19 );

var wing_g = new THREE.ShapeGeometry( heartShape );
var wing_m = new THREE.MeshBasicMaterial( { color: 0xD8EDED } );
var wing = new THREE.Mesh( wing_g, wing_m ) ;
var wing2 = new THREE.Mesh( wing_g, wing_m ) ;

wing.scale.set(.01, .01, .01);
//wing.rotation.x = 1.37;
wing.rotation.x = 1.50; //flip
wing.rotation.y = -0.5; //roll
wing.rotation.z = 5.0; //around
//wing.rotation.z = -1.0;
wing.position.y = 0.06;
wing.position.x = -0.3;

wing2.scale.set(.01, .01, .01);
wing2.rotation.x = 1.37;
wing2.rotation.z = 2.28;
wing2.position.x = 0.30;

var spriteMaterial = new THREE.SpriteMaterial({
  map: loader.load( 'https://lost-woods.com/assets/navi/glow.png' ),
  useScreenCoordinates: false,
  //alignment: THREE.SpriteAlignment.center,
  color: 0x0000ff,
  transparent: false,
  blending: THREE.AdditiveBlending
});
var sprite = new THREE.Sprite( spriteMaterial );
sprite.scale.set(0.7, 0.7, 1.0);

var navi_g = new THREE.SphereGeometry(0.15, 20, 20);
var navi_m = new THREE.MeshPhongMaterial({color: 0xD8EDED, transparent: true, opacity: 0.7, shininess: 30});

navi = new THREE.Mesh( navi_g, navi_m);
navi.add(sprite);
navi.add(wing);
navi.add(wing2);
navi.rotation.x = 0;
navi.rotation.y = 0.5;
navi.rotation.z = 0.3;
scene.add(navi);

var navi_sound = new THREE.PositionalAudio( listener );
audioLoader.load( 'https://lost-woods.com/assets/navi/OOT_Navi_Listen1.wav', function( buffer ) {
  navi_sound.setBuffer( buffer );
  navi_sound.setRefDistance( 0.03 );
  navi_sound.setVolume(100);
  //navi_sound.setLoop(true);
  //navi_sound.play();
});
navi.add( navi_sound );

var rdm_shift = 0;
setInterval(function() {
  rdm_shift = Math.random();
}, 3000);

setTimeout(function() {
  navi_sound.play();
  setInterval(function() {
    navi_sound.play();
  }, 27000);
}, 6000);

function renderNavi() {
  var navi_shiftx = camera.position.x - 1.3 - rdm_shift;
  var navi_shifty = camera.position.y + 2 - rdm_shift;
  navi.position.set(navi_shiftx, navi_shifty, camera.position.z - 4);
}<|endoftext|>


<commit_before>'use strict';

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

const Exchange = require ('./base/Exchange');
const { ExchangeError } = require ('./base/errors');

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

module.exports = class nova extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'nova',
            'name': 'Novaexchange',
            'countries': [ 'TZ' ], // Tanzania
            'rateLimit': 2000,
            'version': 'v2',
            'has': {
                'CORS': false,
                'createMarketOrder': false,
                'createDepositAddress': true,
                'fetchDepositAddress': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/30518571-78ca0bca-9b8a-11e7-8840-64b83a4a94b2.jpg',
                'api': 'https://novaexchange.com/remote',
                'www': 'https://novaexchange.com',
                'doc': 'https://novaexchange.com/remote/faq',
            },
            'api': {
                'public': {
                    'get': [
                        'markets/',
                        'markets/{basecurrency}/',
                        'market/info/{pair}/',
                        'market/orderhistory/{pair}/',
                        'market/openorders/{pair}/buy/',
                        'market/openorders/{pair}/sell/',
                        'market/openorders/{pair}/both/',
                        'market/openorders/{pair}/{ordertype}/',
                    ],
                },
                'private': {
                    'post': [
                        'getbalances/',
                        'getbalance/{currency}/',
                        'getdeposits/',
                        'getwithdrawals/',
                        'getnewdepositaddress/{currency}/',
                        'getdepositaddress/{currency}/',
                        'myopenorders/',
                        'myopenorders_market/{pair}/',
                        'cancelorder/{orderid}/',
                        'withdraw/{currency}/',
                        'trade/{pair}/',
                        'tradehistory/',
                        'getdeposithistory/',
                        'getwithdrawalhistory/',
                        'walletstatus/',
                        'walletstatus/{currency}/',
                    ],
                },
            },
        });
    }

    async fetchMarkets (params = {}) {
        let response = await this.publicGetMarkets ();
        let markets = response['markets'];
        let result = [];
        for (let i = 0; i < markets.length; i++) {
            let market = markets[i];
            let id = market['marketname'];
            let [ quote, base ] = id.split ('_');
            let symbol = base + '/' + quote;
            let active = true;
            if (market['disabled'])
                active = false;
            result.push ({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'active': active,
                'info': market,
            });
        }
        return result;
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let orderbook = await this.publicGetMarketOpenordersPairBoth (this.extend ({
            'pair': this.marketId (symbol),
        }, params));
        return this.parseOrderBook (orderbook, undefined, 'buyorders', 'sellorders', 'price', 'amount');
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        let response = await this.publicGetMarketInfoPair (this.extend ({
            'pair': this.marketId (symbol),
        }, params));
        let ticker = response['markets'][0];
        let timestamp = this.milliseconds ();
        let last = this.safeFloat (ticker, 'last_price');
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': this.safeFloat (ticker, 'high24h'),
            'low': this.safeFloat (ticker, 'low24h'),
            'bid': this.safeFloat (ticker, 'bid'),
            'bidVolume': undefined,
            'ask': this.safeFloat (ticker, 'ask'),
            'askVolume': undefined,
            'vwap': undefined,
            'open': undefined,
            'close': last,
            'last': last,
            'previousClose': undefined,
            'change': undefined,
            'percentage': this.safeFloat (ticker, 'change24h'),
            'average': undefined,
            'baseVolume': undefined,
            'quoteVolume': this.safeFloat (ticker, 'volume24h'),
            'info': ticker,
        };
    }

    parseTrade (trade, market) {
        let timestamp = trade['unix_t_datestamp'] * 1000;
        return {
            'info': trade,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': market['symbol'],
            'id': undefined,
            'order': undefined,
            'type': undefined,
            'side': trade['tradetype'].toLowerCase (),
            'price': this.safeFloat (trade, 'price'),
            'amount': this.safeFloat (trade, 'amount'),
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetMarketOrderhistoryPair (this.extend ({
            'pair': market['id'],
        }, params));
        return this.parseTrades (response['items'], market, since, limit);
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let response = await this.privatePostGetbalances ();
        let balances = response['balances'];
        let result = { 'info': response };
        for (let b = 0; b < balances.length; b++) {
            let balance = balances[b];
            let currency = balance['currency'];
            let lockbox = parseFloat (balance['amount_lockbox']);
            let trades = parseFloat (balance['amount_trades']);
            let account = {
                'free': parseFloat (balance['amount']),
                'used': this.sum (lockbox, trades),
                'total': parseFloat (balance['amount_total']),
            };
            result[currency] = account;
        }
        return this.parseBalance (result);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        if (type === 'market')
            throw new ExchangeError (this.id + ' allows limit orders only');
        await this.loadMarkets ();
        amount = amount.toString ();
        price = price.toString ();
        let market = this.market (symbol);
        let order = {
            'tradetype': side.toUpperCase (),
            'tradeamount': amount,
            'tradeprice': price,
            'tradebase': 1,
            'pair': market['id'],
        };
        let response = await this.privatePostTradePair (this.extend (order, params));
        let orderid = undefined;
        const tradeitems = this.safeValue (response, 'tradeitems');
        if (tradeitems !== undefined) {
            for (let i = 0; i < tradeitems.length; i++) {
                if (this.safeString (tradeitems[i], 'type') === 'created') {
                    orderid = this.safeString (tradeitems[i], 'orderid');
                }
            }
        }
        return {
            'info': response,
            'id': orderid,
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        return await this.privatePostCancelorder (this.extend ({
            'orderid': id,
        }, params));
    }

    async createDepositAddress (code, params = {}) {
        await this.loadMarkets ();
        const currency = this.currency (code);
        let response = await this.privatePostGetnewdepositaddressCurrency (this.extend ({
            'currency': currency,
        }, params));
        const address = this.safeString (response, 'address');
        this.checkAddress (address);
        const tag = this.safeString (response, 'tag');
        return {
            'currency': code,
            'address': address,
            'tag': tag,
            'info': response,
        };
    }

    async fetchDepositAddress (code, params = {}) {
        await this.loadMarkets ();
        const currency = this.currency (code);
        let response = await this.privatePostGetdepositaddressCurrency (this.extend ({
            'currency': currency,
        }, params));
        const address = this.safeString (response, 'address');
        this.checkAddress (address);
        const tag = this.safeString (response, 'tag');
        return {
            'currency': code,
            'address': address,
            'tag': tag,
            'info': response,
        };
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'] + '/' + this.version + '/';
        if (api === 'private')
            url += api + '/';
        url += this.implodeParams (path, params);
        let query = this.omit (params, this.extractParams (path));
        if (api === 'public') {
            if (Object.keys (query).length)
                url += '?' + this.urlencode (query);
        } else {
            this.checkRequiredCredentials ();
            let nonce = this.nonce ().toString ();
            url += '?' + this.urlencode ({ 'nonce': nonce });
            let signature = this.hmac (this.encode (url), this.encode (this.secret), 'sha512', 'base64');
            body = this.urlencode (this.extend ({
                'apikey': this.apiKey,
                'signature': signature,
            }, query));
            headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
            };
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let response = await this.fetch2 (path, api, method, params, headers, body);
        if ('status' in response)
            if (response['status'] !== 'success')
                throw new ExchangeError (this.id + ' ' + this.json (response));
        return response;
    }
};
<commit_msg>Update nova.js<commit_after>'use strict';

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

const Exchange = require ('./base/Exchange');
const { ExchangeError } = require ('./base/errors');

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

module.exports = class nova extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'nova',
            'name': 'Novaexchange',
            'countries': [ 'TZ' ], // Tanzania
            'rateLimit': 2000,
            'version': 'v2',
            'has': {
                'CORS': false,
                'createMarketOrder': false,
                'createDepositAddress': true,
                'fetchDepositAddress': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/30518571-78ca0bca-9b8a-11e7-8840-64b83a4a94b2.jpg',
                'api': 'https://novaexchange.com/remote',
                'www': 'https://novaexchange.com',
                'doc': 'https://novaexchange.com/remote/faq',
            },
            'api': {
                'public': {
                    'get': [
                        'markets/',
                        'markets/{basecurrency}/',
                        'market/info/{pair}/',
                        'market/orderhistory/{pair}/',
                        'market/openorders/{pair}/buy/',
                        'market/openorders/{pair}/sell/',
                        'market/openorders/{pair}/both/',
                        'market/openorders/{pair}/{ordertype}/',
                    ],
                },
                'private': {
                    'post': [
                        'getbalances/',
                        'getbalance/{currency}/',
                        'getdeposits/',
                        'getwithdrawals/',
                        'getnewdepositaddress/{currency}/',
                        'getdepositaddress/{currency}/',
                        'myopenorders/',
                        'myopenorders_market/{pair}/',
                        'cancelorder/{orderid}/',
                        'withdraw/{currency}/',
                        'trade/{pair}/',
                        'tradehistory/',
                        'getdeposithistory/',
                        'getwithdrawalhistory/',
                        'walletstatus/',
                        'walletstatus/{currency}/',
                    ],
                },
            },
        });
    }

    async fetchMarkets (params = {}) {
        let response = await this.publicGetMarkets ();
        let markets = response['markets'];
        let result = [];
        for (let i = 0; i < markets.length; i++) {
            let market = markets[i];
            let id = market['marketname'];
            let [ quote, base ] = id.split ('_');
            let symbol = base + '/' + quote;
            let active = true;
            if (market['disabled'])
                active = false;
            result.push ({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'active': active,
                'info': market,
            });
        }
        return result;
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let orderbook = await this.publicGetMarketOpenordersPairBoth (this.extend ({
            'pair': this.marketId (symbol),
        }, params));
        return this.parseOrderBook (orderbook, undefined, 'buyorders', 'sellorders', 'price', 'amount');
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        let response = await this.publicGetMarketInfoPair (this.extend ({
            'pair': this.marketId (symbol),
        }, params));
        let ticker = response['markets'][0];
        let timestamp = this.milliseconds ();
        let last = this.safeFloat (ticker, 'last_price');
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': this.safeFloat (ticker, 'high24h'),
            'low': this.safeFloat (ticker, 'low24h'),
            'bid': this.safeFloat (ticker, 'bid'),
            'bidVolume': undefined,
            'ask': this.safeFloat (ticker, 'ask'),
            'askVolume': undefined,
            'vwap': undefined,
            'open': undefined,
            'close': last,
            'last': last,
            'previousClose': undefined,
            'change': undefined,
            'percentage': this.safeFloat (ticker, 'change24h'),
            'average': undefined,
            'baseVolume': undefined,
            'quoteVolume': this.safeFloat (ticker, 'volume24h'),
            'info': ticker,
        };
    }

    parseTrade (trade, market) {
        let timestamp = trade['unix_t_datestamp'] * 1000;
        return {
            'info': trade,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': market['symbol'],
            'id': undefined,
            'order': undefined,
            'type': undefined,
            'side': trade['tradetype'].toLowerCase (),
            'price': this.safeFloat (trade, 'price'),
            'amount': this.safeFloat (trade, 'amount'),
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetMarketOrderhistoryPair (this.extend ({
            'pair': market['id'],
        }, params));
        return this.parseTrades (response['items'], market, since, limit);
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let response = await this.privatePostGetbalances ();
        let balances = response['balances'];
        let result = { 'info': response };
        for (let b = 0; b < balances.length; b++) {
            let balance = balances[b];
            let currency = balance['currency'];
            let lockbox = parseFloat (balance['amount_lockbox']);
            let trades = parseFloat (balance['amount_trades']);
            let account = {
                'free': parseFloat (balance['amount']),
                'used': this.sum (lockbox, trades),
                'total': parseFloat (balance['amount_total']),
            };
            result[currency] = account;
        }
        return this.parseBalance (result);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        if (type === 'market')
            throw new ExchangeError (this.id + ' allows limit orders only');
        await this.loadMarkets ();
        amount = amount.toString ();
        price = price.toString ();
        let market = this.market (symbol);
        let order = {
            'tradetype': side.toUpperCase (),
            'tradeamount': amount,
            'tradeprice': price,
            'tradebase': 1,
            'pair': market['id'],
        };
        let response = await this.privatePostTradePair (this.extend (order, params));
        let orderid = undefined;
        const tradeitems = this.safeValue (response, 'tradeitems');
        if (tradeitems !== undefined) {
            for (let i = 0; i < tradeitems.length; i++) {
                if (this.safeString (tradeitems[i], 'type') === 'created') {
                    orderid = this.safeString (tradeitems[i], 'orderid');
                }
            }
        }
        return {
            'info': response,
            'id': orderid,
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        return await this.privatePostCancelorder (this.extend ({
            'orderid': id,
        }, params));
    }

    async createDepositAddress (code, params = {}) {
        await this.loadMarkets ();
        const currency = this.currency (code);
        let response = await this.privatePostGetnewdepositaddressCurrency (this.extend ({
            'currency': currency,
        }, params));
        const address = this.safeString (response, 'address');
        this.checkAddress (address);
        const tag = this.safeString (response, 'tag');
        return {
            'currency': code,
            'address': address,
            'tag': tag,
            'info': response,
        };
    }

    async fetchDepositAddress (code, params = {}) {
        await this.loadMarkets ();
        const currency = this.currency (code);
        let response = await this.privatePostGetdepositaddressCurrency (this.extend ({
            'currency': currency,
        }, params));
        const address = this.safeString (response, 'address');
        this.checkAddress (address);
        const tag = this.safeString (response, 'tag');
        return {
            'currency': code,
            'address': address,
            'tag': tag,
            'info': response,
        };
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'] + '/' + this.version + '/';
        if (api === 'private')
            url += api + '/';
        url += this.implodeParams (path, params);
        let query = this.omit (params, this.extractParams (path));
        if (api === 'public') {
            if (Object.keys (query).length)
                url += '?' + this.urlencode (query);
        } else {
            this.checkRequiredCredentials ();
            let nonce = this.nonce ().toString ();
            url += '?' + this.urlencode ({ 'nonce': nonce });
            let signature = this.hmac (this.encode (url), this.encode (this.secret), 'sha512', 'base64');
            body = this.urlencode (this.extend ({
                'apikey': this.apiKey,
                'signature': signature,
            }, query));
            headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
            };
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let response = await this.fetch2 (path, api, method, params, headers, body);
        if ('status' in response)
            if (response['status'] !== 'success')
                throw new ExchangeError (this.id + ' ' + this.json (response));
        return response;
    }
};
<|endoftext|>


<commit_before>var _fparam = __expr.match(/^([^ ]+) ?/);
var fparam = (isArray(_fparam) && _fparam.length > 0) ? _fparam[1] : "";
var params = processExpr(" ");
var ojob_shouldRun = true;
var ojob_args = {};
var nocolor = false;

if (Object.keys(params).length == 1 && Object.keys(params)[0] == "") ojob_showHelp();

// Check parameters
if (isDef(params["-h"]) && params["-h"] == "") {
	delete params["-h"];
	ojob_showHelp();
}

if (isDef(params["-compile"]) && params["-compile"] == "") {
	delete params["-compile"];
	ojob_compile();
}

if (isDef(params["-tojson"]) && params["-tojson"] == "") {
	delete params["-tojson"];
	ojob_tojson();
}

if (isDef(params["-jobs"]) && params["-jobs"] == "") {
	delete params["-jobs"];
	ojob_jobs();
}

if (isDef(params["-todo"]) && params["-todo"] == "") {
	delete params["-todo"];
	ojob_todo();
}

if (isDef(params["-deps"]) && params["-deps"] == "") {
	delete params["-deps"];
	ojob_draw();
}

if (isDef(params["-nocolor"]) && params["-nocolor"] == "") {
	nocolor = true;
}

if (isDef(params["-jobhelp"]) && params["-jobhelp"] == "") {
	delete params["-jobhelp"];
	ojob_jobhelp();
}

//if ($from(Object.keys(params)).starts("-").any()) {
//	$from(Object.keys(params)).starts("-").select(function(r) {
//		ojob_args[r.replace(/^-/, "")] = params[r];
//		delete params[r];
//	});
//}

if (Object.keys(params).length >= 1 && ojob_shouldRun) {
	ojob_runFile();
}

function ojob_showHelp() {
	print("Usage: ojob aYamlFile.yaml/json [options]\n");
	print("  -compile       Compile all includes and current file into a single yaml output.");
	print("  -tojson        Outputs all includes and current file into a single json output.");
	print("  -jobs          List all jobs available.");
	print("  -todo          List the final todo list.");
	print("  -deps          Draws a list of dependencies of todo jobs on a file.");
	print("  -jobhelp (job) Display any available help information for a job.");
	print("");
	print("(version " + af.getVersion() + ", " + Packages.openaf.AFCmdBase.LICENSE +")");
	ojob_shouldRun = false;
}

function ojob__getFile() {
	/*var ks = Object.keys(params);
	if (ks.length >= 1) {
		var f = ks[0];
		delete params[f];
		print(f);
		return f; */
	if (isDef(fparam)) {
		return fparam;
	} else {
		printErr("Didn't recognize the aYamlFile.yaml\n");
		ojob_showHelp();
		return undefined;
	}
}

function ojob_compile() {
	var file = ojob__getFile();

	if (isDef(file)) {
		print(af.toYAML(ow.loadOJob().previewFile(file)));
	}
	ojob_shouldRun = false;
}

function ojob_tojson() {
	var file = ojob__getFile();

	if (isDef(file)) {
		sprint(ow.loadOJob().previewFile(file));
	}
	ojob_shouldRun = false;
}

function ojob_jobs() {
	var file = ojob__getFile();

	if (isDef(file)) {
		print(af.toYAML($stream(ow.loadOJob().previewFile(file).jobs).map("name").distinct().toArray().sort()));
	}
	ojob_shouldRun = false;
}

function ojob_draw() {
	var file = ojob__getFile();
	ow.loadOJob();

	var oj = ow.oJob.previewFile(file);

	function getDeps(aJobName) {
		var j = $from(oj.jobs).equals("name", aJobName).first();

		if (isUnDef(j)) return undefined;

		if (isDef(j.deps)) {
			return j.deps;
		} else {
			return [];
		}
	}

	function getPaths(aJobName, res) {
		var j = $from(oj.jobs).equals("name", aJobName).first();

		if (isUnDef(res)) res = {
			from: [],
			to  : []
		};

		if (isUnDef(j)) return res;

		res = {
			to  : res.to.concat(j.to),
			from: res.from.concat(j.from)
		};

		res = getPaths(j.from, res);
		res = getPaths(j.to, res);

		return res;
	}

	function getPath(aJobName) {
		var msg = "";

		var deps = getDeps(aJobName);
		if (isUnDef(deps)) {
			msg += "!!NOT FOUND!!";
		} else {
			for(var i in deps) {
				var dep = (isDef(deps[i].name)) ? deps[i].name : deps[i];
				msg += " :" + dep;
				var r = getPath(dep);
				if (r.length > 0) {
					msg += " (" + r + ")";
				}
			}

		}

		return msg;
	}

	if (oj.ojob.sequential) {
		print("Sequential dependencies are enabled.\n");
	}

	ansiStart();
	print(ansiColor("bold,underline", "\nDependencies:"));
	oj.todo.map(function(v) {
		var nn = (isDef(v.name) ? v.name : v);
		printnl("[" + ansiColor("bold", nn) + "]");
		var deps = getDeps(nn);
		print(getPath(nn));
	});

	print(ansiColor("bold,underline", "\nPaths:"));
	oj.todo.map(function(v) {
		var nn = (isDef(v.name) ? v.name : v);
		var paths = getPaths(nn);
		var msg = "";
		for (var i in paths.from) {
			msg += (isDef(paths.from[i]) ? paths.from[i] + " -> " : "");
		}
		msg += "[" + ansiColor("bold", nn) + "]";
		for (var i in paths.to) {
			msg += (isDef(paths.to[i]) ? " -> " + paths.to[i] : "");
		}
		print(msg);
	});
	ansiStop();

	ojob_shouldRun = false;
}

function ojob_jobhelp() {
	var file = ojob__getFile();

	//var ks = Object.keys(params);
	var job = String(__expr).replace(/.+-jobhelp */i, "");
        params = [];
	if (job != "") {
		params = [];
	} else {
		/*printErr("Didn't recognize the job to try to obtain help from.\n");
		ojob_showHelp();
		return undefined;*/
		job = "help";
	}

	if (isDef(file)) {
		var hh = $from(ow.loadOJob().previewFile(file).jobs).equals("name", job).select({"name":"n/a", "help": "n/a"})[0];
		if (isDef(hh)) {
			print(hh.name);
			print(repeat(hh.name.length, '-'));
			print("");
			if (isString(hh.help))
				print(hh.help);
			else {
				print(hh.help.text + "\n");
				if (isDef(hh.help.expects)) {
					print("Expects:");
          				tprint("{{#each expects}}   {{name}} - {{#if required}}(required) {{/if}}{{{desc}}}\n{{/each}}\n", hh.help);
				}
				if (isDef(hh.help.returns)) {
         				print("Returns:");
          				tprint("{{#each returns}}   {{name}} - {{#if required}}(required) {{/if}}{{{desc}}}\n{{/each}}\n", hh.help);
				}
			}
		} else {
                   	printErr("Didn't find job help for '" + job + "'.");
                        return undefined;
                }
	}
	ojob_shouldRun = false;
}

function ojob_todo() {
	var file = ojob__getFile();

	if (isDef(file)) {
		var l = ow.loadOJob().previewFile(file).todo;
		var r = [];
		for(var i in l) {
			if (isObject(l[i]))
				r.push(l[i].name);
			else
				r.push(l[i]);
		}
		print(af.toYAML(r));
	}
	ojob_shouldRun = false;
}

function ojob_runFile() {
	if (ojob_shouldRun) {
		var file = ojob__getFile();

		//__expr = $from(params).select(function(r) { var rr={}; var kk = Object.keys(r)[0]; return kk+"="+r[kk]; }).join(" ");
		__expr = "";
		for(var ii in params) {
			__expr += ii + "=" + params[ii].replace(/ /g, "\\ ") + " ";
		}

		if (isDef(file)) {
			oJobRunFile(file, ojob_args, void 0, (nocolor) ? { conAnsi: false } : void 0);
		}
	}
}
<commit_msg>ojob params<commit_after>var _fparam = __expr.match(/^([^ ]+) ?/);
var fparam = (isArray(_fparam) && _fparam.length > 0) ? _fparam[1] : "";
var params = processExpr(" ");
var ojob_shouldRun = true;
var ojob_args = {};
var nocolor = false;

if (Object.keys(params).length == 1 && Object.keys(params)[0] == "") ojob_showHelp();

// Check parameters
if (isDef(params["-h"]) && params["-h"] == "") {
	delete params["-h"];
	ojob_showHelp();
}

if (isDef(params["-compile"]) && params["-compile"] == "") {
	delete params["-compile"];
	ojob_compile();
}

if (isDef(params["-tojson"]) && params["-tojson"] == "") {
	delete params["-tojson"];
	ojob_tojson();
}

if (isDef(params["-jobs"]) && params["-jobs"] == "") {
	delete params["-jobs"];
	ojob_jobs();
}

if (isDef(params["-todo"]) && params["-todo"] == "") {
	delete params["-todo"];
	ojob_todo();
}

if (isDef(params["-deps"]) && params["-deps"] == "") {
	delete params["-deps"];
	ojob_draw();
}

if (isDef(params["-nocolor"]) && params["-nocolor"] == "") {
	nocolor = true;
}

if (isDef(params["-jobhelp"]) && params["-jobhelp"] == "") {
	delete params["-jobhelp"];
	ojob_jobhelp();
}

//if ($from(Object.keys(params)).starts("-").any()) {
//	$from(Object.keys(params)).starts("-").select(function(r) {
//		ojob_args[r.replace(/^-/, "")] = params[r];
//		delete params[r];
//	});
//}

if (Object.keys(params).length >= 1 && ojob_shouldRun) {
	ojob_runFile();
}

function ojob_showHelp() {
	print("Usage: ojob aYamlFile.yaml/json [options]\n");
	print("  -compile       Compile all includes and current file into a single yaml output.");
	print("  -tojson        Outputs all includes and current file into a single json output.");
	print("  -jobs          List all jobs available.");
	print("  -todo          List the final todo list.");
	print("  -deps          Draws a list of dependencies of todo jobs on a file.");
	print("  -jobhelp (job) Display any available help information for a job.");
	print("");
	print("(version " + af.getVersion() + ", " + Packages.openaf.AFCmdBase.LICENSE +")");
	ojob_shouldRun = false;
}

function ojob__getFile() {
	/*var ks = Object.keys(params);
	if (ks.length >= 1) {
		var f = ks[0];
		delete params[f];
		print(f);
		return f; */
	if (isDef(fparam)) {
		return fparam;
	} else {
		printErr("Didn't recognize the aYamlFile.yaml\n");
		ojob_showHelp();
		return undefined;
	}
}

function ojob_compile() {
	var file = ojob__getFile();

	if (isDef(file)) {
		print(af.toYAML(ow.loadOJob().previewFile(file)));
	}
	ojob_shouldRun = false;
}

function ojob_tojson() {
	var file = ojob__getFile();

	if (isDef(file)) {
		sprint(ow.loadOJob().previewFile(file));
	}
	ojob_shouldRun = false;
}

function ojob_jobs() {
	var file = ojob__getFile();

	if (isDef(file)) {
		print(af.toYAML($stream(ow.loadOJob().previewFile(file).jobs).map("name").distinct().toArray().sort()));
	}
	ojob_shouldRun = false;
}

function ojob_draw() {
	var file = ojob__getFile();
	ow.loadOJob();

	var oj = ow.oJob.previewFile(file);

	function getDeps(aJobName) {
		var j = $from(oj.jobs).equals("name", aJobName).first();

		if (isUnDef(j)) return undefined;

		if (isDef(j.deps)) {
			return j.deps;
		} else {
			return [];
		}
	}

	function getPaths(aJobName, res) {
		var j = $from(oj.jobs).equals("name", aJobName).first();

		if (isUnDef(res)) res = {
			from: [],
			to  : []
		};

		if (isUnDef(j)) return res;

		res = {
			to  : res.to.concat(j.to),
			from: res.from.concat(j.from)
		};

		res = getPaths(j.from, res);
		res = getPaths(j.to, res);

		return res;
	}

	function getPath(aJobName) {
		var msg = "";

		var deps = getDeps(aJobName);
		if (isUnDef(deps)) {
			msg += "!!NOT FOUND!!";
		} else {
			for(var i in deps) {
				var dep = (isDef(deps[i].name)) ? deps[i].name : deps[i];
				msg += " :" + dep;
				var r = getPath(dep);
				if (r.length > 0) {
					msg += " (" + r + ")";
				}
			}

		}

		return msg;
	}

	if (oj.ojob.sequential) {
		print("Sequential dependencies are enabled.\n");
	}

	ansiStart();
	print(ansiColor("bold,underline", "\nDependencies:"));
	oj.todo.map(function(v) {
		var nn = (isDef(v.name) ? v.name : v);
		printnl("[" + ansiColor("bold", nn) + "]");
		var deps = getDeps(nn);
		print(getPath(nn));
	});

	print(ansiColor("bold,underline", "\nPaths:"));
	oj.todo.map(function(v) {
		var nn = (isDef(v.name) ? v.name : v);
		var paths = getPaths(nn);
		var msg = "";
		for (var i in paths.from) {
			msg += (isDef(paths.from[i]) ? paths.from[i] + " -> " : "");
		}
		msg += "[" + ansiColor("bold", nn) + "]";
		for (var i in paths.to) {
			msg += (isDef(paths.to[i]) ? " -> " + paths.to[i] : "");
		}
		print(msg);
	});
	ansiStop();

	ojob_shouldRun = false;
}

function ojob_jobhelp() {
	var file = ojob__getFile();

	//var ks = Object.keys(params);
	var job = String(__expr).replace(/.+-jobhelp */i, "");
        params = [];
	if (job != "") {
		params = [];
	} else {
		/*printErr("Didn't recognize the job to try to obtain help from.\n");
		ojob_showHelp();
		return undefined;*/
		job = "help";
	}

	if (isDef(file)) {
		var hh = $from(ow.loadOJob().previewFile(file).jobs).equals("name", job).select({"name":"n/a", "help": "n/a"})[0];
		if (isDef(hh)) {
			print(hh.name);
			print(repeat(hh.name.length, '-'));
			print("");
			if (isString(hh.help))
				print(hh.help);
			else {
				print(hh.help.text + "\n");
				if (isDef(hh.help.expects)) {
					print("Expects:");
          				tprint("{{#each expects}}   {{name}} - {{#if required}}(required) {{/if}}{{{desc}}}\n{{/each}}\n", hh.help);
				}
				if (isDef(hh.help.returns)) {
         				print("Returns:");
          				tprint("{{#each returns}}   {{name}} - {{#if required}}(required) {{/if}}{{{desc}}}\n{{/each}}\n", hh.help);
				}
			}
		} else {
                   	printErr("Didn't find job help for '" + job + "'.");
                        return undefined;
                }
	}
	ojob_shouldRun = false;
}

function ojob_todo() {
	var file = ojob__getFile();

	if (isDef(file)) {
		var l = ow.loadOJob().previewFile(file).todo;
		var r = [];
		for(var i in l) {
			if (isObject(l[i]))
				r.push(l[i].name);
			else
				r.push(l[i]);
		}
		print(af.toYAML(r));
	}
	ojob_shouldRun = false;
}

function ojob_runFile() {
	if (ojob_shouldRun) {
		var file = ojob__getFile();

		//__expr = $from(params).select(function(r) { var rr={}; var kk = Object.keys(r)[0]; return kk+"="+r[kk]; }).join(" ");
		//__expr = "";
		//for(var ii in params) {
		//	__expr += ii + "=" + params[ii].replace(/ /g, "\\ ") + " ";
		//}

		if (isDef(file)) {
			oJobRunFile(file, ojob_args, void 0, (nocolor) ? { conAnsi: false } : void 0);
		}
	}
}
<|endoftext|>


<commit_before>var HSIndicator = (function(url){

    var callbacks = {
        onOpen : [],
        onClose : [],
        error : [],
        retry : []
    },

    timer = undefined;

    function resolve() {
        jQuery.ajax({
            type : 'GET',
            url : url, //TODO test w/o "HSIndicator" for fun and profit.
            beforeSend : function() {
                callbacks.retry.forEach(function(what) { what(); });
            }
        }).done(function(data) {
            if(data.state.open) {
                callbacks.onOpen.forEach(function(what) { what(); });
            }
            else {
                callbacks.onClose.forEach(function(what) { what(); });
            }
        }).fail(function(err) {
            callbacks.error.forEach(function(what) { what(err); });
        });
        return this;
    };

    function onOpen(callback) {
        callbacks.onOpen.push(callback);
        return this;
    };

    function onClose(callback) {
        callbacks.onClose.push(callback);
        return this;
    };

    function error(callback) {
        callbacks.error.push(callback);
        return this;
    };

    function retry(callback) {
        callbacks.retry.push(callback);
        return this;
    };

    function start(timeout) {
        if(isStarted()) {
            stop();
        }
        timer = setInterval(resolve, timeout);
        return this;
    };

    function stop() {
        if(timer) {
            clearInterval(timer);
            timer = undefined;
        }
        return this;
    };

    function isStarted() {
        return (timer) ? true : false;
    }

    return {
        onOpen : onOpen,
        onClose : onClose,
        error : error,
        retry : retry,
        start : start,
        stop : stop
    };

});
<commit_msg>Removed superfluous comment.<commit_after>var HSIndicator = (function(url){

    var callbacks = {
        onOpen : [],
        onClose : [],
        error : [],
        retry : []
    },

    timer = undefined;

    function resolve() {
        jQuery.ajax({
            type : 'GET',
            url : url,
            beforeSend : function() {
                callbacks.retry.forEach(function(what) { what(); });
            }
        }).done(function(data) {
            if(data.state.open) {
                callbacks.onOpen.forEach(function(what) { what(); });
            }
            else {
                callbacks.onClose.forEach(function(what) { what(); });
            }
        }).fail(function(err) {
            callbacks.error.forEach(function(what) { what(err); });
        });
        return this;
    };

    function onOpen(callback) {
        callbacks.onOpen.push(callback);
        return this;
    };

    function onClose(callback) {
        callbacks.onClose.push(callback);
        return this;
    };

    function error(callback) {
        callbacks.error.push(callback);
        return this;
    };

    function retry(callback) {
        callbacks.retry.push(callback);
        return this;
    };

    function start(timeout) {
        if(isStarted()) {
            stop();
        }
        timer = setInterval(resolve, timeout);
        return this;
    };

    function stop() {
        if(timer) {
            clearInterval(timer);
            timer = undefined;
        }
        return this;
    };

    function isStarted() {
        return (timer) ? true : false;
    }

    return {
        onOpen : onOpen,
        onClose : onClose,
        error : error,
        retry : retry,
        start : start,
        stop : stop
    };

});
<|endoftext|>


<commit_before>function draw(){
    buffer.clearRect(
      0,
      0,
      width,
      height
    );

    // add 2 randomly placed drops
    var loop_counter = 1;
    do{
        drops.push([
          Math.floor(Math.random() * width),// x
          -99,// y
          2,// width
          7// height
        ]);
    }while(loop_counter--);

    loop_counter = drops.length - 1;
    buffer.fillStyle = '#aaf';
    do{
        if(drops[loop_counter][1] > height){
            // remove drop that reached bottom of screen
            drops.splice(
              loop_counter,
              1
            );

        }else{
            // update drop position
            drops[loop_counter][1] += Math.random() * 9 + 9;

            // draw drop
            buffer.fillRect(
              drops[loop_counter][0],
              drops[loop_counter][1],
              drops[loop_counter][2],
              drops[loop_counter][3]
            );
        }
    }while(loop_counter--);

    canvas.clearRect(
      0,
      0,
      width,
      height
    );
    canvas.drawImage(
      document.getElementById('buffer'),
      0,
      0
    );
}

function resize(){
    height = window.innerHeight;
    document.getElementById('buffer').height = height;
    document.getElementById('canvas').height = height;

    width = window.innerWidth;
    document.getElementById('buffer').width = width;
    document.getElementById('canvas').width = width;
}

var buffer = document.getElementById('buffer').getContext('2d');
var canvas = document.getElementById('canvas').getContext('2d');
var drops = [];
var height = 0;
var width = 0;

resize();
window.onresize = resize;

setInterval(
  'draw()',
  30
);
<commit_msg>improved formatting and clarity<commit_after>function draw(){
    buffer.clearRect(
      0,
      0,
      width,
      height
    );

    // aAd 2 randomly placed drops.
    var loop_counter = 1;
    do{
        drops.push([
          Math.floor(Math.random() * width),// X
          -99,// Y
          2,// Width
          7,// Height
        ]);
    }while(loop_counter--);

    loop_counter = drops.length - 1;
    buffer.fillStyle = '#aaf';
    do{
        if(drops[loop_counter][1] > height){
            // Remove drop that reached bottom of screen.
            drops.splice(
              loop_counter,
              1
            );

        }else{
            // Update drop position.
            drops[loop_counter][1] += Math.random() * 9 + 9;

            // Draw drop.
            buffer.fillRect(
              drops[loop_counter][0],
              drops[loop_counter][1],
              drops[loop_counter][2],
              drops[loop_counter][3]
            );
        }
    }while(loop_counter--);

    canvas.clearRect(
      0,
      0,
      width,
      height
    );
    canvas.drawImage(
      document.getElementById('buffer'),
      0,
      0
    );
}

function resize(){
    height = window.innerHeight;
    document.getElementById('buffer').height = height;
    document.getElementById('canvas').height = height;

    width = window.innerWidth;
    document.getElementById('buffer').width = width;
    document.getElementById('canvas').width = width;
}

var buffer = document.getElementById('buffer').getContext('2d');
var canvas = document.getElementById('canvas').getContext('2d');
var drops = [];
var height = 0;
var width = 0;

resize();
window.onresize = resize;

setInterval(
  'draw()',
  30
);
<|endoftext|>


<commit_before>var callbackBuffer = {};
var letterNumber = 0;
var letter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var number = 1;
var senderTimer = null;

var SendBuffer = (function(){
  function SendBuffer(){
	  this.buffer = [];
  }

  SendBuffer.prototype.send = function(msg){
	  this.buffer.push(msg);
  };

  SendBuffer.prototype.flush = function(){
	if(senderTimer != null){
		clearTimeout(senderTimer);
	}
	if(this.buffer.length != 0){
		post("?ajax=true", {"message" : this.buffer.join("\r\n")}, function(){
			if(sendType == "AJAX"){
				senderTimer = setTimeout(function(){
					get("?ajax=true");
				}, 2500);
			}
		});
		this.buffer = [];
	}
  };

  return SendBuffer;
})();

var sendBuffer = new SendBuffer();

function prefix(){
	if(letterNumber >= letter.length){
		letterNumber=0;
	}
	var n = number.toString();
	number++;
	if(n.length == 5){
		return letter.charAt(letterNumber)+n;
	}else if(n.length == 4){
		return letter.charAt(letterNumber)+"0"+n;
	}else if(n.length == 3){
		return letter.charAt(letterNumber)+"00"+n;
	}else if(n.length == 2){
		return letter.charAt(letterNumber)+"000"+n;
	}else if(n.length == 1){
		return letter.charAt(letterNumber)+"0000"+n;
	}

	number = 1;
	letterNumber++;
	return prefix();
}

function post(url, data, callback){
	return ajax(url, data, callback);
}

function get(url){
	if(senderTimer != null){
		clearTimeout(senderTimer);
	}
	return ajax(url, undefined, function(){
		senderTimer = setTimeout(function(){get("?ajax=true")}, 2500);
	});
}

function ajax(url, data, callback){
	var a = new XMLHttpRequest();
	var method = typeof data == "undefined" ? "GET" : "POST";
    a.open(method, url, true);
	if(method == "GET"){
		a.send()
	}else{
		a.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		function render(d){
			var parts = [];
			for(key in d){
				parts.push(encodeURIComponent(key)+"="+encodeURIComponent(d[key]));
			}

			return parts.join("&");
		};
		a.send(render(data));
	}
    a.onreadystatechange = function(){
		if(this.readyState == 4 && this.status == 200){
			var parts = this.responseText.split("\r\n");
			for(var i=0;i<parts.length;i++){
				//controle if this is login message
				if(parts[i] == "LOGIN: REQUID"){
					location.assign("?login=false&page=login.html&defender=enabled");
					return;
				}
				onIncomming(parts[i]);
			}

			if(typeof callback !== "undefined"){
				callback();
			}
		}
	}
}

function send(msg, callback){
	if(typeof callback !== "undefined"){
		var p = prefix();
		msg = p+"!"+msg;
		callbackBuffer[p] = callback;
	}

	if(sendType == "AJAX"){
		sendBuffer.send(msg);
	}
}

var MessageParser  = (function(){
	function MessageParser(msg){
		this.data = {};
		var first = msg.substr(0, msg.indexOf(": ")).split(" ");
		if(first[0].indexOf("!") != -1){
			var parts = first[0].split("!");
			this.data["prefix"] = parts[0];
			first[0] = parts[1];
		}

                //some respons from the server has a user nick (never username)
                if(first[0].indexOf("@") != -1){
                        parts = first[0].split("@");
                        this.data["nick"] = parts[0];
                        first[0] = parts[1];
                }

		this.data["command"] = first[0];
		this.data["channel"] = first.length <= 1 ? null : first[1];
		this.data["message"] = msg.substr(msg.indexOf(": ")+2);
	}

	MessageParser.prototype.hasPrefix = function(){
		return typeof this.data["prefix"] !== "undefined";
	};

	MessageParser.prototype.prefix = function(){
		return this.data["prefix"];
	};

        MessageParser.prototype.nick = function(){
                return this.data["nick"];
        };

	MessageParser.prototype.command = function(){
		return this.data["command"];
	};

	MessageParser.prototype.channel = function(){
		return this.data["channel"];
	};

        MessageParser.prototype.hasChannel = function(){
                return this.channel() != null;
        };

	MessageParser.prototype.message = function(){
		return this.data["message"];
	};

	return MessageParser;
})();

function onIncomming(msg){
	msg = new MessageParser(msg);
	if(msg.hasPrefix() && typeof callbackBuffer[msg.prefix()] !== "undefined"){
		var buffer = callbackBuffer[msg.prefix()];
		delete callbackBuffer[msg.prefix()];
		buffer(msg);
	}else{
		if(msg.hasChannel()){
                   var found = renderPage(function(page){
                      if(msg.channel() == page.title()){
                           page.write(msg);
                           return true;
                      }
                      return false;
                   });
                }
	}
}
<commit_msg>Update send.js<commit_after>var callbackBuffer = {};
var letterNumber = 0;
var letter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var number = 1;
var senderTimer = null;

var SendBuffer = (function(){
  function SendBuffer(){
	  this.buffer = [];
  }

  SendBuffer.prototype.send = function(msg){
	  this.buffer.push(msg);
  };

  SendBuffer.prototype.flush = function(){
	if(senderTimer != null){
		clearTimeout(senderTimer);
	}
	if(this.buffer.length != 0){
		post("?ajax=true", {"message" : this.buffer.join("\r\n")}, function(){
			if(sendType == "AJAX"){
				senderTimer = setTimeout(function(){
					get("?ajax=true");
				}, 2500);
			}
		});
		this.buffer = [];
	}
  };

  return SendBuffer;
})();

var sendBuffer = new SendBuffer();

function prefix(){
	if(letterNumber >= letter.length){
		letterNumber=0;
	}
	var n = number.toString();
	number++;
	if(n.length == 5){
		return letter.charAt(letterNumber)+n;
	}else if(n.length == 4){
		return letter.charAt(letterNumber)+"0"+n;
	}else if(n.length == 3){
		return letter.charAt(letterNumber)+"00"+n;
	}else if(n.length == 2){
		return letter.charAt(letterNumber)+"000"+n;
	}else if(n.length == 1){
		return letter.charAt(letterNumber)+"0000"+n;
	}

	number = 1;
	letterNumber++;
	return prefix();
}

function post(url, data, callback){
	return ajax(url, data, callback);
}

function get(url){
	if(senderTimer != null){
		clearTimeout(senderTimer);
	}
	return ajax(url, undefined, function(){
		senderTimer = setTimeout(function(){get("?ajax=true")}, 2500);
	});
}

function ajax(url, data, callback){
	var a = new XMLHttpRequest();
	var method = typeof data == "undefined" ? "GET" : "POST";
    a.open(method, url, true);
	if(method == "GET"){
		a.send()
	}else{
		a.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		function render(d){
			var parts = [];
			for(key in d){
				parts.push(encodeURIComponent(key)+"="+encodeURIComponent(d[key]));
			}

			return parts.join("&");
		};
		a.send(render(data));
	}
    a.onreadystatechange = function(){
		if(this.readyState == 4 && this.status == 200){
			var parts = this.responseText.split("\r\n");
			for(var i=0;i<parts.length;i++){
				//controle if this is login message
				if(parts[i] == "LOGIN: REQUID"){
					location.assign("?login=false&page=login.html&defender=enabled");
					return;
				}
				onIncomming(parts[i]);
			}

			if(typeof callback !== "undefined"){
				callback();
			}
		}
	}
}

function send(msg, callback){
	if(typeof callback !== "undefined"){
		var p = prefix();
		msg = p+"!"+msg;
		callbackBuffer[p] = callback;
	}

	if(sendType == "AJAX"){
		sendBuffer.send(msg);
	}
}

var MessageParser  = (function(){
	function MessageParser(msg){
		this.data = {};
		var first = msg.substr(0, msg.indexOf(": ")).split(" ");
		if(first[0].indexOf("!") != -1){
			var parts = first[0].split("!");
			this.data["prefix"] = parts[0];
			first[0] = parts[1];
		}

                //some respons from the server has a user nick (never username)
                if(first[0].indexOf("@") != -1){
                        parts = first[0].split("@");
                        this.data["nick"] = parts[0];
                        first[0] = parts[1];
                }

		this.data["command"] = first[0];
		this.data["channel"] = first.length <= 1 ? null : first[1];
		this.data["message"] = msg.substr(msg.indexOf(": ")+2);
	}

	MessageParser.prototype.hasPrefix = function(){
		return typeof this.data["prefix"] !== "undefined";
	};

	MessageParser.prototype.prefix = function(){
		return this.data["prefix"];
	};

        MessageParser.prototype.nick = function(){
                return this.data["nick"];
        };

	MessageParser.prototype.command = function(){
		return this.data["command"];
	};

	MessageParser.prototype.channel = function(){
		return this.data["channel"];
	};

        MessageParser.prototype.hasChannel = function(){
                return this.channel() != null;
        };

	MessageParser.prototype.message = function(){
		return this.data["message"];
	};

	return MessageParser;
})();

function onIncomming(msg){
	msg = new MessageParser(msg);
	if(msg.hasPrefix() && typeof callbackBuffer[msg.prefix()] !== "undefined"){
		var buffer = callbackBuffer[msg.prefix()];
		delete callbackBuffer[msg.prefix()];
		buffer(msg);
	}else{
		if(msg.hasChannel()){
                   var found = renderPage(function(page){
                      if(msg.channel() == page.title()){
                           page.write(msg);
                           return true;
                      }
                      return false;
                   });
                }else{
                   switch(msg.command()){
                      case "NICK":
                        onNick(msg);
                      break;
                   }
                }
	}
}

function onNick(msg){
     //if the old nick this user update 'myNick'
     if(msg.nick() == myNick){
        myNick = msg.message();
     }

     for(var i=0;i<channelBuffer.length;i++){
        channelBuffer[i].updateNick(msg.nick(), msg.message());
     }
}
<|endoftext|>


<commit_before>$(function() {
  // track outbound links
  $('a[href^=http]').on('click', function(e) {
    ga('send', 'event', 'outbound-click', 'click', e.target.href);
  });
});

$(function() {
  url = window.location.href
  $(".page-share.facebook").on("click", function(e) {
    e.preventDefault();
    window.open("https://www.facebook.com/sharer/sharer.php?u="+url,
      "share", "width=600, height=400, scrollbars=no");
      ga('send', 'social', 'facebook', 'share', url);
  });

  $(".page-share.twitter").on("click", function(e) {
    e.preventDefault();
    window.open("https://twitter.com/intent/tweet?&url="+url,
      "share", "width=600, height=400, scrollbars=no");
      ga('send', 'social', 'twitter', 'share', url);
  });

  $(".page-share.linkedin").on("click", function(e) {
    e.preventDefault();
    window.open("https://www.linkedin.com/shareArticle?mini=true&source=OpenUp&url="+url,
      "share", "width=600, height=400, scrollbars=no");
      ga('send', 'social', 'linkedin', 'share', url);
  });

  $(".page-share.email").on("click", function(e) {
    e.preventDefault();
    var emailTitle = encodeURIComponent(document.title).replace(/&/g, '%26');
    window.location = 'mailto:?subject=' + emailTitle + '&body=I saw this OpenUp article and thought it might interest you: ' + url;
    ga('send', 'social', 'email', 'share', url);
  });
});<commit_msg>Update site.js<commit_after>$(function() {
  // track outbound links
  $('a[href^=http]').on('click', function(e) {
    ga('send', 'event', 'outbound-click', 'click', e.target.href);
  });
});

$(function() {
  url = window.location.href;
  $(".page-share.facebook").on("click", function(e) {
    e.preventDefault();
    window.open("https://www.facebook.com/sharer/sharer.php?u="+url,
      "share", "width=600, height=400, scrollbars=no");
      ga('send', 'social', 'facebook', 'share', url);
  });

  $(".page-share.twitter").on("click", function(e) {
    e.preventDefault();
    window.open("https://twitter.com/intent/tweet?&url="+url,
      "share", "width=600, height=400, scrollbars=no");
      ga('send', 'social', 'twitter', 'share', url);
  });

  $(".page-share.linkedin").on("click", function(e) {
    e.preventDefault();
    window.open("https://www.linkedin.com/shareArticle?mini=true&source=OpenUp&url="+url,
      "share", "width=600, height=400, scrollbars=no");
      ga('send', 'social', 'linkedin', 'share', url);
  });

  $(".page-share.email").on("click", function(e) {
    e.preventDefault();
    var emailTitle = encodeURIComponent(document.title).replace(/&/g, '%26');
    window.location = 'mailto:?subject=' + emailTitle + '&body=I saw this OpenUp article and thought it might interest you: ' + url;
    ga('send', 'social', 'email', 'share', url);
  });
});
<|endoftext|>


<commit_before>(function($){
	$(function(){

		$('.button-collapse').sideNav();
		$('.datepicker').pickadate({
			selectMonths: true,
			selectYears: 2
		});

	}); // end of document ready
})(jQuery); // end of jQuery name space<commit_msg>added support for select fields<commit_after>(function($){
	$(function(){

		$('.button-collapse').sideNav();
		$('.datepicker').pickadate({
			selectMonths: true,
			selectYears: 2
		});

	}); // end of document ready
})(jQuery); // end of jQuery name space

$(document).ready(function() {
    $('select').material_select();
});<|endoftext|>


<commit_before>var findme_map = L.map('findme-map').setView([37.7, -97.3], 3);
var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmAttrib='Map data © OpenStreetMap contributors';
var osm = new L.TileLayer(osmUrl, {minZoom: 2, maxZoom: 18, attribution: osmAttrib});
osm.addTo(findme_map);

var findme_marker = L.marker([0,0], {draggable:true});
findme_marker.addTo(findme_map);
findme_marker.setOpacity(0);

$("#category").select2({
    placeholder: "Select a category",
    minimumInputLength: 3,
    ajax: {
        url: "categories.json",
        id: function(obj) { return obj; },
        results: function(data, page) { return { results: data }; }
    },
    formatResult: function (data) {
        return "
" + data + "
";
    },
    formatSelection: function (data) {
        return data;
    }
});

$("#findme").click(function() {
    $("#couldnt-find").hide();

    var address_to_find = $("#address").val();

    if (address_to_find.length === 0) {
        return;
    }

    var qwarg = {
        'format': 'json',
        'q': address_to_find
    };
    var url = "http://nominatim.openstreetmap.org/search?" + $.param(qwarg);
    console.log("Nominatim URL is " + url);

    $("#findme h4").text("Searching...");
    $("#findme").addClass("loading");
    $.getJSON(url, function(data) {
        if (data.length > 0) {
            var chosen_place = data[0];
            console.log(chosen_place);

            var bounds = new L.LatLngBounds([+chosen_place.boundingbox[0], +chosen_place.boundingbox[2]],
                                            [+chosen_place.boundingbox[1], +chosen_place.boundingbox[3]]);
            findme_map.fitBounds(bounds);

            findme_marker.setOpacity(1);
            findme_marker.setLatLng([chosen_place.lat, chosen_place.lon]);

            $("#instructions").text("We found it! Click and drag the marker to sit on your business.");

            $("#findme h4").text("Done!");
            $("#findme").removeClass("loading");
            $("#findme").unbind('click').click(function() {
                $("#address-step").hide();
                $("#collect-data-step").show();
            });
        } else {
            console.log("No data found :(");
            $("#couldnt-find").show();
            $("#findme h4").text("Find Me!");
            $("#findme").removeClass("loading");
        }
    });
});

$("#collect-data-done").click(function() {
    $("#collect-data-step").hide();
    $("#confirm-step").show();
});<commit_msg>A piss-poor autocomplete search behavior.<commit_after>var findme_map = L.map('findme-map').setView([37.7, -97.3], 3);
var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmAttrib='Map data © OpenStreetMap contributors';
var osm = new L.TileLayer(osmUrl, {minZoom: 2, maxZoom: 18, attribution: osmAttrib});
osm.addTo(findme_map);

var findme_marker = L.marker([0,0], {draggable:true});
findme_marker.addTo(findme_map);
findme_marker.setOpacity(0);

var category_data = [];

$.ajax('./categories.json').success(function(data){
    category_data = data;
});

$("#category").select2({
    query: function (query) {
        var data = {results: []}, i;

        for (i = 0; i < category_data.length; i++) {
            if (query.term.length === 0 || category_data[i].toLowerCase().indexOf(query.term.toLowerCase()) >= 0) {
                data.results.push({id: category_data[i], text: category_data[i]});
            }
        }

        query.callback(data);
    }
});

$("#findme").click(function() {
    $("#couldnt-find").hide();

    var address_to_find = $("#address").val();

    if (address_to_find.length === 0) {
        return;
    }

    var qwarg = {
        'format': 'json',
        'q': address_to_find
    };
    var url = "http://nominatim.openstreetmap.org/search?" + $.param(qwarg);
    console.log("Nominatim URL is " + url);

    $("#findme h4").text("Searching...");
    $("#findme").addClass("loading");
    $.getJSON(url, function(data) {
        if (data.length > 0) {
            var chosen_place = data[0];
            console.log(chosen_place);

            var bounds = new L.LatLngBounds([+chosen_place.boundingbox[0], +chosen_place.boundingbox[2]],
                                            [+chosen_place.boundingbox[1], +chosen_place.boundingbox[3]]);
            findme_map.fitBounds(bounds);

            findme_marker.setOpacity(1);
            findme_marker.setLatLng([chosen_place.lat, chosen_place.lon]);

            $("#instructions").text("We found it! Click and drag the marker to sit on your business.");

            $("#findme h4").text("Done!");
            $("#findme").removeClass("loading");
            $("#findme").unbind('click').click(function() {
                $("#address-step").hide();
                $("#collect-data-step").show();
            });
        } else {
            console.log("No data found :(");
            $("#couldnt-find").show();
            $("#findme h4").text("Find Me!");
            $("#findme").removeClass("loading");
        }
    });
});

$("#collect-data-done").click(function() {
    $("#collect-data-step").hide();
    $("#confirm-step").show();
});<|endoftext|>