//
// J.Whelan
// 2007-02-01
// Client-side ad delivery
// --------------------------------------------------------------------------------------

var digErrors	= new Array();

// Map Special Case Rendering Scenarios --
//	key:	InsertionType [String]
//	value:  renderFunctionName [with NO PARENTHESES]
//
// EXAMPLE: digRenderMap["MediumRectangle"] = renderMediumRectangle;
//
var digRenderMap = new Array();
// digRenderMap["SponsoredByLogoHeader"]	= digRenderReturnCreativeText;
// digRenderMap["Banner"]					= render;


function digGetAd(insertionType, forceCreativeReturn) {
	try {
		forceCreativeReturn = (String(forceCreativeReturn) == "true") ? true : false;
		var adDataContainerObj = null;

		if (digAdData != null && digAdData[insertionType] != null) { adDataContainerObj = digAdData[insertionType]; }
		if (adDataContainerObj == null) { adDataContainerObj = new digAdDataContainer(insertionType, null); } // empty ad

		return digRender(adDataContainerObj, forceCreativeReturn);
	}
	catch(e) {
		// Capture error for the console
		digErrors[digErrors.length] = "Issue inserting " + ((insertionType == null || insertionType == "") ? "an unknown insertion type" : insertionType ) + " [ " + e.description + " ]";
	}
}

// WDIG_render(adDataContainerObj) function:
// Has the ability to return a string to accommodate the case when digGetAd() is called
// to return the creative text instead of writing it directly to the DOM.
// *** This may be useful in special case rendering scenarios.
function digRender(adDataContainerObj, forceCreativeReturn) {
	if (adDataContainerObj != null) {
		if (adDataContainerObj.creative.text != null) {
			// Check for special rendering scenarios
			var renderFunc = digRenderDefault;										  // <-- Default Rendering
			if (digRenderMap != null) {
				// Prevent recursive reference with *arguments.callee* comparison check
				if (digRenderMap[adDataContainerObj.insertionType]!=null && digRenderMap[adDataContainerObj.insertionType]!=arguments.callee) {
					renderFunc = digRenderMap[adDataContainerObj.insertionType];		// <-- Special Case Rendering
				}
			}
			return renderFunc.apply(this, arguments);								   // <-- Execute Assigned Rendering Function
		}
		else { // Render empty ad
			if (!forceCreativeReturn) {
				document.write("<!-- NO AD DATA FOUND FOR INSERTION TYPE: " + adDataContainerObj.insertionType + " -->");
			}
		}
	}
	else { throw new Error("Cannot render null adDataContainerObj"); }
	return "";
}

function digRenderDefault(adDataContainerObj, forceCreativeReturn) {
	if (forceCreativeReturn) {
		return adDataContainerObj.creative.text;
	}
	document.write(adDataContainerObj.creative.text);
}

// Generate the DynamicCSAd request with the url parameter.
function digRequestAds(csarUrl, includeHost, cntCodes) {
	adRequestUrl = digGenerateCSARUrl(csarUrl, includeHost, cntCodes, document.location.href);

	// Write the CSAR request url
	document.write("<scr"+"ipt type=\"text/javascript\" src=\"" + adRequestUrl + "\"></scr"+"ipt>");
}

function digGenerateCSARUrl(csarUrl, includeHost, cntCodes, docUrl) {
	if (docUrl == null) {
		docUrl = document.location.href;
	}

	if (csarUrl != null) {
		var adRequestUrl = csarUrl;

		if (includeHost != null && !includeHost) {
			// Get the request path from the document url and strip off the scheme and host name
			var index = docUrl.indexOf("://");
			var pageRequestUrl = "/";

			if (index > 0) {
				pageRequestUrl = docUrl.substring(index+3);

				index = pageRequestUrl.indexOf("/");
				if (index < 0) {
					pageRequestUrl = "/";
				}
				else {
					pageRequestUrl = pageRequestUrl.substring(index);

					// Filter the url
					pageRequestUrl = pageRequestUrl.replace(/\</g,"%3c").replace(/>/g,"%3e").replace(/\"/g,"%22");
				}

				// Append request url parameter
				if (pageRequestUrl.length > 0) {
					adRequestUrl += "&url=";
					adRequestUrl += pageRequestUrl;
				}
			}
		}

		if (cntCodes != null && cntCodes.length > 0) {
			adRequestUrl += "&cnt_codes=";
			adRequestUrl += cntCodes;
		}
	}
	else {
		throw new Error("CSAR url must be specified");
	}

	return adRequestUrl;
}

// Special Case Rendering Functions -----------------------------------------------------
//
//	Special Case functions must make sure to handle the forceCreativeReturn
//	parameter behavior as the caller would expect it to function.

function digRenderReturnCreativeText(adDataContainerObj) {
	return digRenderDefault(adDataContainerObj, true);
}

// DEBUG CONSOLE ------------------------------------------------------------------------
//
//	  Displays a pop-up window that dispalys the information of the ads that
//	  were returned.

function digShowDebugConsole() {
	var doc = window.open('','adsDebug','width=' + window.screen.availWidth*0.85 + ', height=' + window.screen.availHeight*0.85 + ', statusbar, resizable, scrollbars', true).document;
	doc.open();

	doc.writeln('<html><head><title>Client-side Ad Serving Console</title></head>\n<body bgcolor="#fffecc">');
	doc.write('<PRE><h3>Client-side Ad Serving Console</h3>');

	if (digErrors != null && digErrors.length>0) {
		// Output errors that have been caught
		doc.writeln("<HR /><b>Ad Rendering Issues:</b><ul>");
		for (var i=0, iSize=digErrors.length; i<iSize; ++i) {
			doc.writeln("<li><font color=\"#ff0000\">" + digErrors[i] + "</font></li>");
		}
		doc.writeln("</ul>");
	}

	if (digAdData != null) {
		// Output Delivered Ad Information
		for (var itype in digAdData) {
			doc.write("<HR />");
			for (var prop in digAdData[itype]) {
				doc.writeln("<b>" + prop + "</b>: " + digAdData[itype][prop]);
				if (typeof digAdData[itype][prop] == 'object') {
					for (var subprop in digAdData[itype][prop]) {
						if (typeof digAdData[itype][prop][subprop] == "string" && digAdData[itype][prop][subprop].length > 0) {
							doc.writeln("\t" + subprop + ":\n\t<TEXTAREA STYLE='font: 8pt; background-color: #eeeeee' READONLY WRAP='OFF' COLS=100 ROWS=10>" + digAdData[itype][prop][subprop] + "</TEXTAREA>");
						}
					}
				}
			}
			doc.writeln("<BR />");
		}
		doc.writeln('</PRE>');
	}
	else {
		doc.writeln('<PRE>digAdData array was not initialized.</PRE>');
	}
	doc.writeln('</body></html>');
	doc.close();
}

// Check if console has been requested
if (location.search.indexOf('WDIG_CS_DEBUG=1') > 0) {
	try {
		// Attempts to attach the console launcher to the onLoad
		// event without overriding previous onLoad handlers.
		if	  (window.addEventListener)	{ window.addEventListener('load', digShowDebugConsole, false);	}	// Gecko, Safari, Konqueror and W3C standard
		else if (document.addEventListener)	{ document.addEventListener('load', digShowDebugConsole, false);	}	// Opera7
		else if (window.attachEvent)	{ window.attachEvent('onload', digShowDebugConsole);				}	// IE
		else	{ window.onload = digShowDebugConsole;							  }	// Override entire event for all other browsers
	}
	catch(e) {
		window.status = "Could not open console: " + e.description;
		setTimeout("window.status=window.defaultStatus", 5000);
	}
}

