// script to count beats per minute on user keypress
// copyright (C) 2006 by Gardner Patton, All rights reserved
// modified May 14, 2008 to get rid of allbpm slash count 
//          which was intrepreted wrong
// variables
secs2  = 0; // previous time in seconds
count  = 0; // count of key presses
allBpm = 0; // total summary of beats per minute
avgBpm = 0; // average of beats per minute for all trials
bpm    = 0; // value of beats per minute this trial
ns     = (navigator.appName == 'Netscape'); // check browser type
ie     = (navigator.appName == 'Microsoft Internet Explorer');

// function to reset values
function gcpreset() {
// initialize 
document.BEATSPERMINUTE.AVG.value = "";// set output vars to blank
document.BEATSPERMINUTE.NOW.value = "";
document.BEATSPERMINUTE.HIT.value = "";
document.BEATSPERMINUTE.ACG.value = "";
document.BEATSPERMINUTE.NCG.value = "";
count = 0; // set count to 0
} // end gcpreset function

// function to execute on key press
function bpmCounter(e) {
// Check browser and set vars
if (ns) clearBpm = e.which;
else if (ie) clearBpm = event.button;
//
timeSeconds = new Date;       // get the current time 
secs = timeSeconds.getTime(); // pull off the time in seconds value
if (count == 0) {
gcpreset()       // set output values to blank
secs2 = secs; // save current value of seconds
allBpm = 0;   // total beat per minutes count
avgBpm = 0;   // avg beats per minute is allBpm divided by count
bpm = 0;      // current beats per minute
count++;      // up the key press count
} // end count = 0
else {
// do when not count = 0
oldBpm = bpm; // save the old beats per minute
// calculate the new beat per minute value using 2 time stamps
bpm = (1 / ((secs - secs2) / 1000)) * 60;
bpmChg = (Math.round((bpm - oldBpm) * 10)) / 10;
count++; // up the count
allBpm = allBpm + bpm;
oldAvg = avgBpm; // get old average and add this one div by intervals
avgBpm = allBpm / (count - 1) ; // subtract 1 from count for intervals
avgChg = (Math.round((avgBpm - oldAvg) * 10)) / 10;
secs2 = secs; // save new value of time in seconds
if (bpmChg >= 0) { PbpmChg = "+" + bpmChg } else { PbpmChg = bpmChg }
if (avgChg >= 0) { PavgChg = "+" + avgChg } else { PavgChg = avgChg }
// write out the results for viewing
document.BEATSPERMINUTE.AVG.value = (Math.round(avgBpm * 1)) / 1;
document.BEATSPERMINUTE.ACG.value = PavgChg;
document.BEATSPERMINUTE.NOW.value = (Math.round(bpm * 1)) / 1;
document.BEATSPERMINUTE.NCG.value = PbpmChg;
document.BEATSPERMINUTE.HIT.value = (count) ;  // key presses
} // end else count not zero
return true; // always return true
} // end of function bpmCounter

document.onkeydown = bpmCounter;

