var idCount =0;
var curId=-1;
function trace(t){alert(t);}
function scanNode(n,f)
{
	for(var i=0;i<n.childNodes.length;i++)
	{
		if (canScan(n.childNodes[i].nodeName))
			scanNode(n.childNodes[i],f);
			
		if(/^H[1-5]$/.test(n.childNodes[i].nodeName))
		{
			if(n.childNodes[i].className.toString().indexOf(f)>-1)
			{
				var perma = getPermaLink(n.childNodes[i]);
				n.childNodes[i].parentNode.insertBefore(createiSpeechNode(perma),n.childNodes[i].nextSibling);
			}
		}
	}
	
}
function getPermaLink(n)
{
	if (n.firstChild.nodeName=="A")
		return n.firstChild.href;
	else
		return n.firstChild.nextSibling.href;
}

function createiSpeechNode(p)
{
	var s= document.createElement("span");
	var im=document.createElement("img");
	im.src="http://www.ispeech.org/images/listen.gif";	
	im.alt="Listen to this post. Powered by iSpeech.org";
	im.title="Listen to this post. Powered by iSpeech.org";
	idCount+=1;
	var id=idCount;
	im.onclick=function(){showPlayer(im,p,id);};
	im.style.border="none";
	im.style.margin="0px";
	im.style.cursor="pointer";
	im.width="77";
	im.height="18";	

	var iframe= document.createElement("iframe");
	iframe.style.border="none";
	iframe.frameBorder="0";
	iframe.width="0";
	iframe.height="0";
	iframe.id = "ispeech_iframe_" + id.toString();
	
	s.appendChild(im);
	s.appendChild(document.createElement("br"));
	s.appendChild(iframe);
	return s;
}
function ge(e){return document.getElementById(e);}
function showPlayer(im,p,id)
{
	if(curId!=id)
	{
		if(curId!=-1)
			closeAllPlayers();
		curId=id;
		var ifr = ge("ispeech_iframe_" + id.toString());
		ifr.src="http://ws.ispeech.org/redirect.php?u=" + escape(p);
		ifr.style.width="204px";
		ifr.style.height="56px";
	}
	else
		closeAllPlayers();
}
function closeAllPlayers()
{
	for(var i = 1;i<=idCount;i++)
	{
		var ifr = ge("ispeech_iframe_" + i.toString());
		ifr.src="about:blank";
		ifr.style.width="0px";
		ifr.style.height="0px";
	}
	curId=-1;
}
function canScan(v)
{
	switch(v.toString().toUpperCase())
	{
		case "DIV":
		return true;
		break;
	}
	return false;
}

function startUp()
{
	scanNode(document.body,'post-title');	
	document.write('<a href="http://www.ispeech.org/podcasts/?url='+ escape(location.href) +'">View Podcast</a>');
}

// stuff
window.onload+=startUp();
// more stuff
