/*
 * @(#) bpm.js		(c)2005 jon r. luini, chime interactive
 *
 * see http://www.chime.com/ for contact info/use permissions
 * note: this requires chime_request.js to be loaded already
 */

/*
 * these bpm-related functions call php scripts that do the
 * needed SQL updates and then return the new average bpm.
 * we take that output and shove it into a hidden element
 * to extract and parse and keep track of for updating or
 * unloading later
 */

var BPM_ID = "bpm_info";	// the id that holds our bpm info
var BPM_UPDATE = "userscripts/bpm_update.php";
var myBPM = undefined;		// my bpm, if set
var bpmUpdateTime = 0;
var now = new Date();
var bpmLoadTime = parseInt (now.getTime() / 1000, 10);

/*
 * setBPM() - send a new bpm value to the nav flash. if we've already
 *   set a BPM, then we update with the difference (delta) instead
 */
function setBPM (newBPM)
{
    var url;

    if ( pageIsLoaded == false || ! window.document || ! window.document.nav_swf )
	return;

    if ( myBPM != undefined )
    {
	// no change? that's easy!
	if ( myBPM == newBPM )
	    return;

	delta_bpm = newBPM - myBPM;
	url = BPM_UPDATE + "?bpm_mode=update&bpm=" + newBPM
	    + "&bpm_delta=" + delta_bpm
	    + "&loaded=" + bpmLoadTime
	    + "&last_update=" + bpmUpdateTime;
    }
    else
    {
	url = BPM_UPDATE + "?bpm_mode=add&bpm=" + newBPM;
    }

    sndReq (BPM_ID, url, bpmLoaded, newBPM);
}

/*
 * unsetBPM() - if we've set a bpm, call php to unset it
 */
function unsetBPM ()
{
    var url;

    if ( myBPM == undefined )
	return;

    url = BPM_UPDATE + "?bpm_mode=remove&bpm=" + myBPM;

    sndReq (BPM_ID, url, bpmRemoved);
}

function bpmRemoved ()
{
    myBPM = undefined;
}

/*
 * bpmLoaded() - this is called after a bpm change completes
 */
function bpmLoaded (url, targetId, newBPM)
{
    var obj = myGetElementById (targetId);
    var text;
    var re;

    if ( ! obj ) return;	// this shouldn't happen, but better to be safe!

    text = obj.innerHTML;

    if ( text == "" ) return;

    // strip away bpm=number to just the number
    re = new RegExp("bpm=", "");
    text = text.replace (re, "");
    if ( ! isNaN (text) )
    {
	var avg_bpm = parseInt (text, 10);
	var now = new Date();

	if ( pageIsLoaded == true || window.document )
	{
	    if ( window.document.nav_swf )
	    {
		try { window.document.nav_swf.SetVariable ("_root.bpm_avg", avg_bpm); }
		catch (e) { }   
	    }
	    if ( window.document.bpm_swf )
	    {
		try { window.document.bpm_swf.SetVariable ("_root.bpm_avg", avg_bpm); }
		catch (e) { }
	    }
	}

	myBPM = newBPM;

	// convert getTime from milliseconds to seconds
	bpmUpdateTime = parseInt (now.getTime() / 1000, 10);
    }
}
