﻿//JavaScript Metronome by Raymond May Jr
//http://rnamusic.com
//http://pianowithraymond.com
//Released to the Public Domain

var bpm = 120;
var rate = 60000/bpm;
var nextBeat = rate;
var nextMainBeat = rate;
var signature = 1;
var go = 1;
var sound = 0;
var t;

//timer object by Diego of fyneworks
//http://fyneworks.blogspot.com/2007/04/javascript-timer.html
var timer =
{
    time: 0,
    now: function(){ return (new Date()).getTime(); },
    start: function(){ this.time = this.now(); },
    since: function(){ return this.now()-this.time; }
}

function startMetro()
{
    nextBeat = rate;
    nextMainBeat = rate;
    timer.start();
    metro();
}

function stopMetro()
{
    clearTimeout(t);
    document.getElementById('beatIndicator').style.display = "block";
}

function metro()
{
    time = timer.since();
    if(time >= nextBeat)
    {
        if(time >= nextMainBeat & signature != 1)
        {
            document.getElementById('beatIndicator').style.display = "block";
            PlaySound('beat1');
            nextMainBeat = nextBeat + (signature*rate);
            nextBeat = nextBeat + rate;
        }
        else
        {
            document.getElementById('beatIndicator').style.display = "block";
            if(sound == 0)
            {
                PlaySound('beat1');
                sound = 1;
            }
            else if(sound == 1)
            {
                PlaySound('beat1');
                sound = 2;
            }
            else if(sound == 2)
            {
                PlaySound('beat1');
                sound = 3;
            }
            else if(sound == 3)
            {
                PlaySound('beat1');
                sound = 0;
            }
            nextBeat = nextBeat + rate;
        }
    }
    else if(time >= (nextBeat - (.5*rate)))
    {
        document.getElementById('beatIndicator').style.display = "none";
    }
    t=setTimeout("metro()",5);
}

function bpmUp(amt)
{
    bpm = bpm + amt;
    rateChange(bpm);
    currentBpm();
}

function bpmDown(amt)
{
    if((bpm - amt) >= 1)
    {
        bpm = bpm - amt;
        rateChange(bpm);
        currentBpm();
    }
}


function rateChange(newBpm)
{
    rate = 60000/newBpm;
}


function PlaySound(soundobj) 
{
    var thissound=document.getElementById(soundobj);
    thissound.Play();
    alert("sound");
}
function StopSound(soundobj) 
{
    var thissound=document.getElementById(soundobj);
    thissound.Stop();
}

function currentBpm()
{
    try
    {
        document.getElementById('bpm').value=bpm;
    }
    catch(err)
    {
        // do nothing
    }
}

function currentSig()
{
    try
    {
        document.getElementById('sig').value=(signature + "/4");
    }
    catch(err)
    {
        // do nothing
    }
}

