var afsNarrowAdsAllocation = 4;
var afsSponsoredText = '';
var afsTemplate = 'standard';
var afsConfigId = null;
var afsFrameSrc = '';
var afsAnalyticsPrefix = '';
var afsCssClass = 'afs_default';
//This might seem nuts at first glance, but this set of JS allows us a lot of flexibility in how AFS is integrated (whim-based dev ;-))
//wide ads are the ones used in results list, narrow ads are on rhs panel
var wideAFSAds = [];
var restoreWideAFSAds = [];
var narrowAFSAds = [];
var spliceIndex = 0;	//wide ads are allocated from unused narrow ads
//afs ads are loaded in an iframe so that they can be refreshed on ajax reloads (the integration is via a script include)
var afsLoaded = false;
var afsInsertionQueue = [];
var firstNarrowAd = ''; //the top narrow ad is handled separately to the narrow ads array so it is always available
var firstWideAd = ''; //ditto
//calls for afs ads are wrapped by this prototype:
var afsInsertionRequest = function(insertionPoint, adType) {
	this.insertionPoint = insertionPoint;
	this.adType = adType;
	this.hasContent = false;
	this.adContent = null;
	this.insertionAt = 'top';
	this.getAdContent = function() {
		if (this.adType == 'n') {
			this.adContent = createNextNarrowAFS();
		} else if (this.adType == 'first_n') {
			if (typeof firstNarrowAd != 'undefined' && firstNarrowAd != '') {
				this.adContent = narrowAdHTML(firstNarrowAd);
			}
		} else if (this.adType == 'w') {
			this.adContent = createNextWideAFS();
		} else if (this.adType == 'all_n') {
			this.adContent = displayAllNarrowAFS();
		} else if (this.adType == 'release_n') {
			releaseNarrowAd();
		} else if (this.adType == 'no_results_last_w') {
			this.adContent = '<li class="google_afs_wide no_results_google_afs_wide">' + createNextWideAFS() + '</li>';
			this.insertionAt = 'bottom';
		} else if (this.adType == 'no_results_first_w') {
			this.adContent = '<li class="google_afs_wide no_results_google_afs_wide">' + createNextWideAFS() + '</li>';
		} else if (this.adType == 'first_w') {
			if (typeof firstWideAd != 'undefined' && firstWideAd != '') {
				this.adContent = wideAdHTML(firstWideAd);
				this.insertionAt = 'replace';
			}
		} else if (this.adType == 'last_w') {
			this.adContent = '<li class="google_afs_wide">' + createNextWideAFS() + '</li>';
			this.insertionAt = 'bottom';
		}
		if (this.adContent != null && this.adContent != '') {
			this.hasContent = true;
		}
	}
}

function reloadAFSFrame() {
	if (AFS_DEBUG) $('afs_debug').innerHTML = '';
	if (AFS_DEBUG) $('afs_debug').insert(afsFrameSrc + '<br>');
	if (afsFrameSrc != '') {
		wideAFSAds = [];
		restoreWideAFSAds = [];
		narrowAFSAds = [];
		spliceIndex = 0;
		afsLoaded = false;
		afsInsertionQueue = [];
		$(google_afs_integration).location = afsFrameSrc;
	}
}

//This is the manager for inserting ads. It either responds to the ad insertion call, or queues it
function manageAfsAds(afsInsertionRequest) {
	if (AFS_DEBUG) $('afs_debug').insert('manageAfsAds afsLoaded = ' + afsLoaded + '<br>'); //debugging
	if (afsLoaded) {
		//can deal with the ad insertion request immediately
		insertAfsAd(afsInsertionRequest);
	} else {
		//add the request to the queue to be resolved once the afs frame loads
		afsInsertionQueue.push(afsInsertionRequest);
		if (AFS_DEBUG) $('afs_debug').insert('manageAfsAds ad pushed to queue = ' + afsInsertionRequest.adType + '<br>'); //debugging
	}
}

function insertAfsAd(afsInsertionRequest) {
	afsInsertionRequest.getAdContent();
	if (afsInsertionRequest.hasContent && $(afsInsertionRequest.insertionPoint)) {
		if (afsInsertionRequest.insertionAt == 'top') {
			Element.insert(afsInsertionRequest.insertionPoint, {top: afsInsertionRequest.adContent});
		} else if (afsInsertionRequest.insertionAt == 'bottom') {
			Element.insert(afsInsertionRequest.insertionPoint, {bottom: afsInsertionRequest.adContent});
		} else {
			$(afsInsertionRequest.insertionPoint).innerHTML = '';
			Element.insert(afsInsertionRequest.insertionPoint, {top: afsInsertionRequest.adContent});
		}
		if (AFS_DEBUG) $('afs_debug').insert('inserting Ad ' + afsInsertionRequest.adType + ': ' + afsInsertionRequest.insertionPoint + '(' + wideAFSAds.length + ':' + narrowAFSAds.length + ' left)<br>'); //debugging
	} else if (afsInsertionRequest.adType != 'release_n' && $(afsInsertionRequest.insertionPoint)) {
		if (AFS_DEBUG) $('afs_debug').insert('removing insertion point ' + afsInsertionRequest.insertionPoint + '<br>'); //debugging
		Element.remove(afsInsertionRequest.insertionPoint);
	} else if (!$(afsInsertionRequest.insertionPoint)) {
		if (AFS_DEBUG) $('afs_debug').insert('unable to resolve insertion point ' + afsInsertionRequest.insertionPoint + '<br>'); //debugging
	}
}

//called from the ifrmae, shows the afs query in debug mode
function showTermUsed(afsQuery) {
	if (AFS_DEBUG) $('afs_debug').insert('<br>query term: <br>' + afsQuery + '<br>'); //debugging
}

//called from the ifrmae, shows the afs fetch number in debug mode
function showNoFetched(afsAllocation) {
	if (AFS_DEBUG) $('afs_debug').insert('<br>no of ads fetched: <br>' + afsAllocation + '<br>'); //debugging
}

//called from the iframe, it sets the afsLoaded status and clears the queue
function setAfsLoaded(aFSAds) {
	afsLoaded = true;
	if (AFS_DEBUG) $('afs_debug').insert('setAfsLoaded<br>'); //debugging
	if (AFS_DEBUG) $('afs_debug').insert('aFSAds = ' + aFSAds.length + '<br><br>'); //debugging
	if (AFS_DEBUG) aFSAds.each(function(ad) {
		$('afs_debug').insert('<b>' + ad.line1 + '</b><br><br>'); //debugging
	});
	if (aFSAds.length > 0 && !Settings.MAP_VIEW) {
		wideAFSAds = $A(aFSAds.slice(0, 2));
		if (AFS_DEBUG) $('afs_debug').insert('wideAFSAds = ' + wideAFSAds.length + '<br>'); //debugging
		narrowAFSAds = $A(aFSAds.slice(2, afsNarrowAdsAllocation));
		firstNarrowAd = narrowAFSAds.shift(); //this gets handled a special case due to ticket 5569, subsequent to rotation being switched off, see results.rjs
		firstWideAd = wideAFSAds.shift(); //ditto
		if (AFS_DEBUG) $('afs_debug').insert('narrowAFSAds = ' + narrowAFSAds.length + '<br>'); //debugging
		if (aFSAds.length > 5) {
			wideAFSAds.push(aFSAds.slice(afsNarrowAdsAllocation, aFSAds.length));
		}
		wideAFSAds = wideAFSAds.flatten();
		if (AFS_DEBUG) $('afs_debug').insert('wideAFSAds after reallocation = ' + wideAFSAds.length + '<br>'); //debugging
	} else if (aFSAds.length > 0) {
		wideAFSAds = $A();
		narrowAFSAds = $A(aFSAds.slice(0, afsNarrowAdsAllocation));
		firstNarrowAd = narrowAFSAds.shift(); //this gets handled a special case due to ticket 5569, subsequent to rotation being switched off, see results.rjs
		if (AFS_DEBUG) $('afs_debug').insert('narrowAFSAds = ' + narrowAFSAds.length + '<br>'); //debugging
		if (AFS_DEBUG) $('afs_debug').insert('wideAFSAds = ' + wideAFSAds.length + '<br>'); //debugging
	}
	restoreWideAFSAds = wideAFSAds.clone();
	spliceIndex = 0;
	processRemainingAfsQueue();
}

//finishes anything in the ad queue that couldn't be resolved whilst the iframe was loading
function processRemainingAfsQueue() {
	if (AFS_DEBUG) $('afs_debug').insert('processRemainingAfsQueue<br>'); //debugging
	afsInsertionQueue.each(function(afsInsertionRequest) {
		insertAfsAd(afsInsertionRequest);
	});
	afsInsertionQueue.clear();
}

function displayNoResultsAfs() {
	manageAfsAds(new afsInsertionRequest('results_container', 'no_results_first_w'));
	manageAfsAds(new afsInsertionRequest('results_container', 'no_results_last_w'));
}

function removeWideAds() {
	$$('.google_afs_wide').each(function(elemt) {
		if (elemt.id != 'google_afs_first_wide') {
			elemt.remove();
		}
	});
}

function removeNoResultsWideAd() {
	$$('.no_results_google_afs_wide').each(function(elemt) {
		elemt.remove();
	});
}

//puts an unused narrow ad from the rhs collection into the pool for the results (ad order has to be preserved)
function releaseNarrowAd() {
	if (narrowAFSAds.length > 0) {
		released = narrowAFSAds.shift();
		wideAFSAds.splice(spliceIndex, 0, released);
		restoreWideAFSAds = wideAFSAds.clone();
		if (AFS_DEBUG) $('afs_debug').insert('releaseNarrowAd (' + wideAFSAds.length + ':' + narrowAFSAds.length + ' left)<br>'); //debugging
		spliceIndex++;
	}
}

function displayAllNarrowAFS() {
	var narrowAds = '';
	//render each narrow ad
	narrowAFSAds.each(function(ad, index) {
		narrowAds += narrowAdHTML(ad);
	});
	return narrowAds;
}

function createNextNarrowAFS() {
	var narrowAd = '';
	if (narrowAFSAds.length > 0) {
		narrowAd += narrowAdHTML(narrowAFSAds[0]);
		released = narrowAFSAds.shift(); //pop the ad from narrowAds:
	}
	return narrowAd;
}

function createNextWideAFS() {
	var wideAd = ''; 
	if (wideAFSAds.length > 0) {
		wideAd += wideAdHTML(wideAFSAds.shift());
	} else {
		//resets the ads for infinite scroll
		wideAFSAds = restoreWideAFSAds.clone();
		if (wideAFSAds.length > 0) {
			wideAd += wideAdHTML(wideAFSAds.shift());
		}
	}
	return wideAd;
}

function wideAdHTML(ad) {
	if (afsTemplate == 'standard') {
		html = '<p class="sponsored_link">' + afsSponsoredText + '</p><a class="image" target="_blank" onmouseout="window.status=\'\'; return true;" onmouseover="window.status=\'go to ' + ad.visible_url + '\'; return true;" href="' + ad.url + '" ' + afsPageTrackerLink(afsAnalyticsPrefix + 'Wide', ad.n) + '></a>' +
		'<div class="snapshot"><a target="_blank" href="' + ad.url + '" title="' + ad.visible_url + '" onmouseout="window.status=\'\'; return true;" onmouseover="window.status=\'go to ' + ad.visible_url + '\'; return true;" ' + afsPageTrackerLink(afsAnalyticsPrefix + 'Wide', ad.n) + '>' +
		'<p class="line1">' + ad.line1 + '</p></a>' +
		'<p class="line2">' + ad.line2 + ' ' + ad.line3 + '</p></div>' +
		'<p class="line3"><a target="_blank" onmouseout="window.status=\'\'; return true;" onmouseover="window.status=\'go to ' + ad.visible_url + '\'; return true;" href="' + ad.url + '" title="' + ad.visible_url + '" ' + afsPageTrackerLink(afsAnalyticsPrefix + 'Wide', ad.n) + '>' + ad.visible_url + '</a></p>';
	} else {
		html = wideIrelandAdHTML(ad);
	}
	return html;
}

function narrowAdHTML(ad) {
	if (afsTemplate == 'standard') {
		html = '<ul class="google_afs_narrow ' + afsCssClass + '"><p class="sponsored_link">' + afsSponsoredText + '</p>';   //narrow ad unit html text
		html += '<li class="google_afs_narrow last">';
		html += '<div class="snapshot"><a target="_blank" onmouseout="window.status=\'\'; return true;" onmouseover="window.status=\'go to ' + ad.visible_url + '\'; return true;" href="' + ad.url + '" title="' + ad.visible_url + '" ' + afsPageTrackerLink(afsAnalyticsPrefix + 'Narrow', ad.n) + '>' +
		'<p class="line1">' + ad.line1 + '</p></a>' +
		'<p class="line2">' + ad.line2 + ' ' + ad.line3 + '</p></div>' +
		'<p class="line3"><a target="_blank" onmouseout="window.status=\'\'; return true;" onmouseover="window.status=\'go to ' + ad.visible_url + '\'; return true;" href="' + ad.url + '" title="' + ad.visible_url + '" ' + afsPageTrackerLink(afsAnalyticsPrefix + 'Narrow', ad.n) + '>' + ad.visible_url + '</a></p></li>';
		html += '</ul>';
	} else {
		html = narrowIrelandAdHTML(ad);
	}
	return html;
}

function wideIrelandAdHTML(ad) {
	html = '<p class="ie_sponsored_link"><a target="_blank" href="https://www.google.com/adsense/support/bin/request.py?contact=afs_violation">' + afsSponsoredText + '</a></p><a class="image"></a>' +
	'<div class="snapshot"><a target="_blank" href="' + ad.url + '" title="' + ad.visible_url + '" onmouseout="window.status=\'\'; return true;" onmouseover="window.status=\'go to ' + ad.visible_url + '\'; return true;" ' + afsPageTrackerLink(afsAnalyticsPrefix + 'Wide', ad.n) + '>' +
	'<p class="line1">' + ad.line1 + '</p></a>' +
	'<p class="line2">' + ad.line2 + ' ' + ad.line3 + '</p></div>' +
	'<p class="line3"><a target="_blank" onmouseout="window.status=\'\'; return true;" onmouseover="window.status=\'go to ' + ad.visible_url + '\'; return true;" href="' + ad.url + '" title="' + ad.visible_url + '" ' + afsPageTrackerLink(afsAnalyticsPrefix + 'Wide', ad.n) + '>' + ad.visible_url + '</a></p>';
	return html;
}

function narrowIrelandAdHTML(ad) {
	html = '<ul class="google_afs_narrow google_afs_narrow_ie ' + afsCssClass + '"><p class="ie_sponsored_link"><a target="_blank" href="https://www.google.com/adsense/support/bin/request.py?contact=afs_violation">' + afsSponsoredText + '</a></p>';   //narrow ad unit html text
	html += '<li class="google_afs_narrow last">';
	html += '<div class="snapshot"><a target="_blank" onmouseout="window.status=\'\'; return true;" onmouseover="window.status=\'go to ' + ad.visible_url + '\'; return true;" href="' + ad.url + '" title="' + ad.visible_url + '" ' + afsPageTrackerLink(afsAnalyticsPrefix + 'Narrow', ad.n) + '>' +
	'<p class="line1">' + ad.line1 + '</p></a>' +
	'<p class="line2">' + ad.line2 + ' ' + ad.line3 + '</p></div>' +
	'<p class="line3"><a target="_blank" onmouseout="window.status=\'\'; return true;" onmouseover="window.status=\'go to ' + ad.visible_url + '\'; return true;" href="' + ad.url + '" title="' + ad.visible_url + '" ' + afsPageTrackerLink(afsAnalyticsPrefix + 'Narrow', ad.n) + '>' + ad.visible_url + '</a></p></li>';
	html += '</ul>';
	return html;
}

function afsPageTrackerLink(scope, adNo) {
	return "onclick=\"pageTracker._trackEvent(\'AFS\', \'" + scope + ":ad_no_" + adNo + "\');\"";
}

