AudioPlayer.setup("/radio/script/podcast-player/player.swf", {width: 290} );

// When the DOM is ready, run this function...
window.addEvent('domready', function() {
	// Find all URLs with .xml extension and establish this function for each
	// $$(".storyBody")[0].getElements('a[href$=.xml]').each(function(lnk, k){
	$$(".storyBody")[0].getElements('a[class=podcast-expand]').each(function(lnk, k){
		f = new Element("div");
		f.inject(lnk, "before");
		//lnk.set("text", "");
		var root = XML.rootFromFile(lnk.getProperty("href"));
		var h = XML.rootToHashes(root);
		// h[0] is most likely a reference to the rss tag in www.domain.tld/xml-file.xml
		// and children[0] is a reference to the channel tag that is the only child of rss
		var channel = h[0].children[0];
		var item, title, description, link;
		var counter = 0;
		var ids = Array();

		// Check all of the 2nd level tags in the XML
		for ( i=0; i < channel.children.length; i++ ) {
			// Podcasts have the item tag as a child of the channel tag
			if ( channel.children[i].tag == "item" ) {
				item = channel.children[i];
				title = "";
				description = "";
				link = "";

				// Each child of the item tag is scanned and the info we want is extracted
				for ( j=0; j < item.children.length; j++ ) {
					switch ( item.children[j].tag ) {
						case "title":
							title = item.children[j].children[0].text;
							break;
						case "description":
							description = item.children[j].children[0].text;
							break;
						case "link":
							link = item.children[j].children[0].text;
							break;
					}
				}

				// Create the elements to be injected
				h4 = new Element("h4", {text:title});
				h4.inject(f);
				p = new Element("p", {text:description});
				p.inject(f);
				a = new Element("a", {text:"Listen", href:link, id:"mp3_audio_link_" + k + "_" + i});
				p = new Element("p");
				a.inject(p);
				p.inject(f);
				/* At this stage we should have the following structure:
					<div> (f)
						<h4></h4> (h4)
						<p></p> (p)
						<p><a></a></p> (p)(a)
					</div>
				*/
				ids.push({id:a.getProperty("id"), soundFile:link, titles:title});
				AudioPlayer.embed(a.getProperty("id"), {soundFile:link, titles:title});
				counter++;
			}

			if ( counter > 7 ) {
				break;
			}
		}
//alert("Pause!!!...");
		for ( i = 0; i < ids.length; i++ ) {
			AudioPlayer.embed(ids[i].id, {soundFile:ids[i].soundFile, titles:ids[i].titles});
//alert('id: '+ids[i].id+'\nsoundFile: '+ids[i].soundFile+'\ntitles: '+ids[i].titles);
		}
	});
});
