// FreshAds v0.1
// Tag-Driven Advertising
// (Part of FreshTags system)
// www.greg-hill.id.au 2006
// This work is licensed under a Creative Commons Attribution-ShareAlike 2.1 Australia License.
// URL: http://ghill.customer.netspace.net.au/freshtags/
// Requires: 	del_user (delicious user account)
//			ads (tag for advertising URLs)
//			doFreshAds (a callback function for dealing with FreshAds)

// NB: currently implemented for amazon.com associates program
// http://associates.amazon.com/gp/associates/join

if(typeof(FreshAds) == 'undefined') 
	FreshAds = []; 							// if missing, create null

function loadFreshAds()
{

// Get list of all candidate ads from delicious

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "http://del.icio.us/feeds/json/"+del_user+"/"+ads+"?callback=doFreshAds";
document.getElementsByTagName("head")[0].appendChild(script);

return;
}

function listAds(adsObj)
{

alert("in listAds");

// Pick best ad, given current tags

// Match each ad's tags against the current tags. For each match, push the ad onto the newAds object.
// The same ad will appear as many times as its tags match the current tags.
// More matching tags -> more chance of getting picked.


var t, re, count = adsObj.length;
var newAdsObj=[];

if (count==0)									// if no ads, just finish
{
	alert('count==0');
	return;
}

if (!curr_tags)
	curr_ad = adPick(adsObj);						// if no current tags, just pick from all
else
{
	for(var i=0; i<count; i++)						// scroll through all the ads
	{
		adTags = adsObj[i].t;
		for(var j=0; j<adTags.length; j++)				// scroll through all the tags for each ad
		{
			t = adTags[j];
			re = new RegExp('(^|\\+)'+t+'(\\+|$)');
			if(curr_tags.search(re)>-1)				// tag matches one in current tags
				newAdsObj.push(adsObj[i]);
		}				
	}
	
	curr_ad = adPick(newAdsObj);

	if (!curr_ad)								// if nothing, try anything
		curr_ad = adPick(adsObj);
}

if (!curr_ad)
{
	alert('!curr_ad');
	return;									// if no ads, just finish
}


// Generate HTML

var outputHTML;

var srcHTML = '<iframe src="URL" style="NOTES" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>';

var url=curr_ad.u;
var notes=curr_ad.n;

if (!url)
	return;									// if no URL, just finish

var re_u = /URL/;
var re_n = /NOTES/;

outputHTML = srcHTML.replace(re_u,url);					// replace dummy labels with ad values
outputHTML = outputHTML.replace(re_n, notes);

FreshAds.url = curr_ad.u;							// load up global variable
FreshAds.descr = curr_ad.d;
FreshAds.tags = curr_ad.t;
FreshAds.notes = curr_ad.n;

alert("listAds: output: "+outputHTML);

return outputHTML;
}

function adPick(obj)
{
var r, c = obj.length;

if (c==0)										// if no ads, just finish
	return;

r = Math.floor(Math.random()*c);

return obj[r];

}