// BJAX Google NPR Audio example user script
// version 0.1 ALPHA!
// 2008-07-17
// Copyright (c) 2008, Demian Perry
// Released under the GPL license
// http://www.gnu.org/copyleft/gpl.html
//
// --------------------------------------------------------------------
//
// This is a Greasemonkey user script.
//
// To install, you need Greasemonkey: http://greasemonkey.mozdev.org/
// Then restart Firefox and revisit this script.
// Under Tools, there will be a new menu item to "Install User Script".
// Accept the default configuration and install.
//
// To uninstall, go to Tools/Manage User Scripts,
// select "BJAX Google NPR audio", and click Uninstall.
//
// --------------------------------------------------------------------
//
// ==UserScript==
// @name          Audio Search Boxx
// @namespace     http://www.npr.org/
// @description   Adds NPR audio to your Google results, and allows you to play directly from the search page.
// @include       http://www.google.com/*
// ==/UserScript==

//work with google ads
var gSidebar = document.getElementById('mbEnd');
var gTopbar = document.getElementById('tads');
var gTpal = document.getElementById('tpal');
//if(gSidebar != null){gSidebar.innerHTML = "";}
//if(gTopbar != null){gTopbar.innerHTML = "";}
//if(gTpal != null){gTpal.innerHTML = "";}

//these variables allow an npr graphic designer to tweak the results so they fit in the added div (maybe dynamic based on search engine?)
numberResults = 7;
charLength = 40;

// This parses the url to return the search terms.  It's like Get in PHP:
var searchText = String(document.location).split("&q=")[1].split("&")[0];

function addEventHandler(target, eventName, eventHandler)
{
	if (target.addEventListener)
		target.addEventListener(eventName, eventHandler, false);
	else if (target.attachEvent)
		target.attachEvent("on" + eventName, eventHandler);
}

if (typeof GM_xmlhttpRequest != 'function') {
	// do nothing
} else {
	if (window == top) {



// This is the Ajax request for grabbing articles from NPR's XML search
		GM_xmlhttpRequest({
		    method:'GET',
		    url:'http://api.npr.org/query?fields=title,audio,image&sort=date_asc&output=RSS&apiKey=MDAxNzY0NjcwMDEyMTU1NDcyNDVkOWNiNQ001&searchTerm=' + searchText.replace(/\+/g, "%20"),
			onload:function(response){
				var searchBox = document.getElementById('search_box');
					// convert string to XML object

//alert (response.responseText);
					var xmlobject = (new DOMParser()).parseFromString(response.responseText, "text/xml");
					var searchArray = xmlobject.getElementsByTagName('item');




					var c = searchArray.length;
//alert (c);
					if(c>numberResults){c=numberResults;}
					var searchResults = "";
					for(i=1;i<c;i++){
						var link = searchArray[i].getElementsByTagName('link')[0].firstChild.nodeValue;
						var title = searchArray[i].getElementsByTagName('title')[0].firstChild.nodeValue;
						var description = searchArray[i].getElementsByTagName('description')[0].firstChild.nodeValue;
						var pubDate = searchArray[i].getElementsByTagName('pubDate')[0].firstChild.nodeValue;
						if(searchArray[i].getElementsByTagName('mp3')[0]){var audio = searchArray[i].getElementsByTagName('mp3')[0].firstChild.nodeValue;} else {var audio = link;}
						if(title.length>charLength){var title = title.slice(0,charLength) + '...';}
						var newLine = '<tr>'+
							'<td>'+
								'<span style="cursor: pointer;" '+
								'id="audioLink' + i + '">'+
								'&nbsp;'+
								'</span></td>'+
								'<td><a href="'+
								audio +
								'" title="'+
								description +
								'">'+
								title +
							'</a></td></tr>';
						var searchResults = searchResults + newLine;
						//searchBox.innerHTML = searchResults;
						//audioScrape(i,link);
					}
		//var topImage = "http://upload.wikimedia.org/wikipedia/commons/4/4e/Vista-arts.png";
		//var topImage = "http://media.npr.org/images/npr_news_123x20.gif";
		//var topImage = "http://media.npr.org/programs/asc/archives/20071122/images/collage.jpg";
		if(searchArray[0].getElementsByTagName('mp3')[0]){var topLink = searchArray[0].getElementsByTagName('mp3')[0].firstChild.nodeValue;} else {var topLink = searchArray[0].getElementsByTagName('link')[0].firstChild.nodeValue;}
		if(searchArray[0].getElementsByTagName('image')[0]){if(searchArray[0].getElementsByTagName('image')[0].getAttribute("type") == "primary"){var topImage = searchArray[0].getElementsByTagName('image')[0].getAttribute("src");} else {var topImage = 'http://upload.wikimedia.org/wikipedia/commons/4/4e/Vista-arts.png';}} else {var topImage = 'http://upload.wikimedia.org/wikipedia/commons/4/4e/Vista-arts.png';}
		var topTitle = searchArray[0].getElementsByTagName('title')[0].firstChild.nodeValue;
		var topDesc = searchArray[0].getElementsByTagName('description')[0].firstChild.nodeValue;
		if(topDesc.length>150){var topDesc = topDesc.slice(0,150) + '... <a href="' + topLink + '">MORE</a>&raquo';}
		//var topDesc = searchArray[0].getElementsByTagName('pubDate')[0].firstChild.nodeValue + " ";
		var mybox = document.createElement("div");
		mybox.innerHTML = '<div id="bjax_box" style="margin: 0 auto 0 auto; ' +
		    'float:right; width:280px; opacity: .75; filter: alpha(opacity=75); z-index:100; ' +
		    'margin: 5px; padding: 5px; overflow: hidden; height: 300px; ' +
		    'font-size: 8pt; font-weight: bold; font-family: arial, sans-serif; background-color: #C7E19E; ' +
		    'color: #000000;" > ' +
		    '<table><tr><td valign="top">' +
		    '<a href="' + topLink + '"><img id="alogo" width=128 style="border:none; cursor:pointer" target="_blank" src="' + topImage + '"></a>' +
		    '</td><td style="font-size: 12px; font-weight: bold; font-family: arial" valign="top"><a href="' + topLink + '">' + topTitle + '</a><span style="font-size: 10px; font-weight:normal;"><br>' + topDesc + '</span>' +
		    '</td></tr></table>' +
		    '</span><br> &nbsp; More results from NPR:<br><table id="search_box" style="font-size:12px; font-family:arial">' + searchResults + '</table>' +
		    '<span id="test_box">&nbsp;</span>' +
		    '</div>';

	if(gSidebar != null){
		document.body.insertBefore(mybox, document.getElementById('mbEnd'));
		document.getElementById('mbEnd').style.clear = 'both';
	} else {
		mybox.style.position = 'absolute';
		mybox.style.right = '10px';
		mybox.style.top = '200px';
		mybox.style.width = '300px';
		document.body.insertBefore(mybox, document.body.firstChild);
	}
			}
		});
	}

}


//this just links the sound graphic to our hourly newscast.
//addEventHandler(document.getElementById('alogo'), "click", function() {window.open("http://www.npr.org/templates/dmg/dmg_em.php?id=1&type=4&date=&au=1&pid=33542123&random=0026171655&guid=00028F5DEE9D06C16195071961626364&upf=Win32&splayer=sp&mtype=WM&ssid=&topicName=News&subtopicName=Newscast&prgCode=&hubId=&thingId=&tableModifier=&mswmext=.asx","_popMedia","width=-1,height=-1",true);window.focus();}, true);