var debug = false;

// global flag
var isIE = false;

// global request and XML document objects
var req;
var ref = '';

var check_itunesstate = '';
var check_nowplaying = '';
var check_oldsongs = '';
var check_comments = '';
var check_updateinfo = '';

// Retry after this length of time
// if a non-200 response is received
// 
// Still haven't worked out how to deal with
// no response from the server at all. Tried timeouts
// which call req.abort() and clearing the timeout
// when a response is received but so far it always
// produces errors. At the moment, if we do get no
// response then the whole thing just stops since
// no further request is sent.
var retryAfter = 30000;

function loadXMLDoc(url, method, data, processReq)
{
	d = new Date();
	ref = "" + d.getTime();
	
	url += '?r=' + ref;

	// branch for native XMLHttpRequest object
	if (window.XMLHttpRequest)
	{
		req = new XMLHttpRequest();
		req.onreadystatechange = processReq;
		req.open(method, url, true);
		req.send(data);
	}
	// branch for IE/Windows ActiveX version
	else if (window.ActiveXObject)
	{
		// IE-5 Mac supports the ActiveXObject
		// but it is broken.
		if ( navigator.platform != 'MacPPC' )
		{
			isIE = true;
			// Apparently this might be necessary instead depending
			// on what Windoze components are installed. Could use
			// try-catch to try both (which also avoids the check
			// for IE5-Mac since it supports neither object) but
			// try-catch errors on older browsers even if it
			// isn't executed (so I'm told).
			//     req = new ActiveXObject("Msxml2.XMLHTTP");
			req = new ActiveXObject("Microsoft.XMLHTTP");
			if (req)
			{
				req.onreadystatechange = processReq;
				req.open(method, url, true);
				if ( data == null )
					req.send();
				else
					req.send(data);
			}
		}
	}
}

// handle onreadystatechange event of req object
function processReqChange()
{
	// only if req shows "loaded"
	if (req.readyState == 4)
	{
		// only if "OK"
		if (req.status == 200)
		{
			myref = tagValue('yourref');
			if ( myref == ref )
			{
				// The check tags are used to check if things
				// have changed. If they haven't then we don't
				// bother updating the page. Speeds it up.
				// *** Checks disabled for the moment
				// *** since they stopped working with
				// *** Firefox 2. Updates always done.
				check = getCheckTag('check_itunesstate');
				if ( check != check_itunesstate || true )
				{
					check_itunesstate = check;
					updateDiv('npinfoh', 'itunesstate');
				}
				check = getCheckTag('check_nowplaying');
				if ( check != check_nowplaying || true )
				{
					check_nowplaying = check;
					updateDiv('npinfo', 'nowplaying');
				}
				check = getCheckTag('check_oldsongs');
				if ( check != check_oldsongs || true )
				{
					check_oldsongs = check;
					updateDiv('osinfo', 'oldsongs');
				}
				/*
				check = getCheckTag('check_comments');
				if ( check != check_comments || true )
				{
					check_comments = check;
					updateDiv('npcomments', 'comments');
				}
				*/
				check = getCheckTag('check_updateinfo');
				if ( check != check_updateinfo || true )
				{
					check_updateinfo = check;
					updateDiv('npupdate', 'updateinfo');
				}
				
				i = req.responseXML.getElementsByTagName("refresh");
				if ( i )
				{
				
					// get text, accounting for possible
					// whitespace (carriage return) text nodes 
					if (i[0].childNodes.length > 1)
						var refreshAfter = i[0].childNodes[1].nodeValue;
					else
						var refreshAfter = i[0].firstChild.nodeValue;
					// refreshAfter = 0+refreshAfter;  // turn value into an integer
					if ( debug )
						updateAfter(5000);
					else
						updateAfter(refreshAfter*1000);
				}
			}
			else
				updateAfter(retryAfter); // bad ref
		}
		else
		{
			// If we get any other response try again in 30 seconds
			if ( debug )
				updateAfter(5000);
			else
				updateAfter(retryAfter);
			// alert("There was a problem retrieving the XML data:\n" + req.statusText);
		}
	}
}


// Start a timeout to get an update
// after t ms
function updateAfter(t)
{
	setTimeout( "loadXMLDoc('getupdate', 'GET', null, processReqChange)", t )
}

function updateDiv(div, tag)
{
	v = tagValue(tag);
	if ( v )
	{
		divnode = document.getElementById(div);
		if ( divnode )
			divnode.innerHTML = v;
	}
}

// Returns the value of a tag in the response.
// If tag not found returns the time.
// Used to check the values of the check tags
function getCheckTag(tag)
{
	v = tagValue(tag);
	if (v)
		return v;
	d = new Date();
	return d.getTime();
}

// return value of tag in response
// return null if not found
function tagValue(tag)
{
	i = req.responseXML.getElementsByTagName(tag);
	if ( i )
	{
		if ( i[0].childNodes.length > 1 )
			tagval = i[0].childNodes[1].nodeValue;
		else
			tagval = i[0].firstChild.nodeValue;
		return tagval;
	}
	return null;
}

function initAutoUpdate( initRefresh )
{
	// initRefresh is in seconds
	if ( debug )
		initRefresh = 5;  // debugging - update every 5s
	updateAfter(initRefresh*1000);
}