function A9AdsChangeLocationDisplay(response) {
	var divId = response.divid;
    var renderer = A9ClickriverWidget.getWidget(divId);
    renderer.onResponse(response);
}

/*****************************************************************/

Array.prototype.pushAll = function(from) {
    for (var i = 0; i < from.length; i++) {
        this.push(from[i]);
    }
}

function A9ClickriverWidget(divId, config) {
	this.divId = divId;
	this.config = config;
	this.firstCall = true;
	this.overridenParams = '';
	this.template = A9ClickriverWidget.templates[this.config.template_name];
	
	if (typeof this.config.show_category_icon == 'undefined') {
		this.config.show_category_icon = false;
	}
	this.config.show_category_icon = this.config.show_category_icon && this.template.icon_allowed;
	if (typeof this.config.suppress_change_location == 'undefined') {
		this.config.suppress_change_location = false;
	}
	if (typeof this.config.collapse_blank_space == 'undefined') {
		this.config.collapse_blank_space = true;
	}
	if (typeof this.config.passback == 'undefined') {
		this.config.passback = "";
	}
	
	if (this.config.show_category_icon) {
		this.default_ad_count = this.template.ad_count_icon;
		this.columns = this.template.columns_icon;
	} else {
		this.default_ad_count = this.template.ad_count;
		this.columns = this.template.columns;
	}
	
	if (typeof this.config.ad_count != 'undefined') {
		this.overridenParams += '&ov_ac=' + this.config.ad_count;
	}
	if (typeof this.config.suppress_footer == 'undefined') {
		this.config.suppress_footer = false;
	} else {
		this.overridenParams += '&ov_sf=1';
	}
	if (typeof this.config.picture_url_subdir == 'undefined') {
		this.config.picture_url_subdir = '';
	} else {
		this.overridenParams += '&ov_pu=' + escape(this.config.picture_url_subdir);
	}
	if (!A9ClickriverWidget.inIFrame()) {
		this.overridenParams += '&ov_ni=1';
	}
	
	this.changeLocation = new A9ClickriverCLPopup(this);
}

A9ClickriverWidget.getWidget = function(divId) {
	return A9ClickriverWidget.widgetMap[divId];
}

A9ClickriverWidget.generateElementId = function(baseId) {
	var idx = 0;
	while (idx < 100) {
		var el = document.getElementById(baseId + idx);
		if (el == null) {
			return baseId + idx;
		} else {
			idx++;
		}
	}
}

A9ClickriverWidget.generateDivId = function() {
	return A9ClickriverWidget.generateElementId('a9_sl_div');
}

A9ClickriverWidget.generateIFrameId = function() {
	return A9ClickriverWidget.generateElementId('a9_sl_iframe');
}

A9ClickriverWidget.spawnIFrame = function(cr_params) {
	cr_params.no_iframe = true;
	var serializedConfig = A9ClickriverWidget.serializeConfig(cr_params);
	
	A9ClickriverWidget.includeCSS();
	var iframeId = A9ClickriverWidget.generateIFrameId();
	var iframeClass = 'a9_ad_' + cr_params.template_name + ' a9_ad_' + cr_params.template_name + '_noc';
	var iframeSrc = A9ClickriverWidget.iframeLocation + '?r=' + (new Date()).getTime() + '&u=' + escape(document.location.href);
	//if (typeof cr_params.collapse_blank_space == 'undefined' || cr_params.collapse_blank_space) {
	//	iframeSrc += '&i=' + iframeId + '&l=' + escape(cr_params.resize_html);
	//}
	iframeSrc += '&c=' + serializedConfig;
	
	document.write('<iframe id="' + iframeId + '" name="' + iframeId + '" src="' + iframeSrc + '" frameborder="0" scrolling="no" class="' + iframeClass + '"></iframe>');
	
	return iframeId;
}

A9ClickriverWidget.inIFrame = function() {
	var re = new RegExp('^' + A9ClickriverWidget.iframeLocation.toLowerCase());
	return re.test(document.location.href.toLowerCase());
}

A9ClickriverWidget.verifyConfig = function(cr_params) {
	if (typeof cr_params.channel == 'undefined' || typeof cr_params.categories == 'undefined'
		|| typeof cr_params.template_name == 'undefined' || typeof cr_params.pub_key == 'undefined'
		|| typeof cr_params.test_mode != 'boolean' || typeof A9ClickriverWidget.templates[cr_params.template_name] == 'undefined' ) {
		return false;
	}
	if (typeof cr_params.categories != 'string') {
		var length = cr_params.categories.length;
		for (var i = 1; i < length; i += 2) {
			var w = cr_params.categories[i];
			if (typeof w != 'number' || w <= 0) {
				return false;
			}
		}
	}

	return true;
}

A9ClickriverWidget.createWidget = function(cr_params) {
	if (!A9ClickriverWidget.verifyConfig(cr_params)) {
		return;
	}
	
	if (!cr_params.no_iframe) {
		return A9ClickriverWidget.spawnIFrame(cr_params);
	} else {
		if (typeof A9ClickriverWidget.widgetMap == 'undefined') {
			A9ClickriverWidget.widgetMap = {};
		}
		
		var divId = A9ClickriverWidget.generateDivId();
		if (divId != null) {
			var widget = new A9ClickriverWidget(divId, cr_params);
			A9ClickriverWidget.widgetMap[divId] = widget;
			
			document.write('<div id="' + divId + '"></div><scr' + 'ipt>setTimeout(function() { A9ClickriverWidget.getWidget("' + divId + '").requestAds(); }, 0);</scr' + 'ipt>\n');
		}
		return divId;
	}
}

A9ClickriverWidget.setSerializableFields = function(cr_params) {
	cr_params.serializableFields = ["channel", "categories", "template_name", "pub_key", "test_mode", "show_category_icon", "suppress_change_location", "passback", "collapse_blank_space", "ad_count", "suppress_footer", "picture_url_subdir", "css_overrides", "no_iframe"];
	if (typeof cr_params.css_overrides == 'undefined') {
		cr_params.css_overrides = {};
	}
	cr_params.css_overrides.serializableFields = ["ad_unit_border_color", "ad_unit_link_color", "header_bg_color", "header_text_color", "header_link_color", "body_bg_color", "body_text_color", "body_link_color"];
}

A9ClickriverWidget.serializeConfig = function(cr_params) {
	function getSerializedValue(value) {
		if (typeof value == 'undefined') {
			return [''];
		} else if (typeof value == 'string') {
			return ['s', escape(value)];
		} else if (typeof value == 'number') {
			return ['n', value];
		} else if (typeof value == 'boolean') {
			return ['b', (value ? 1 : 0)];
		/*} else if (typeof value == 'function') {
			return ['f', escape(value.toString())];*/
		} else if (value.constructor == Array) {
			var length = value.length;
			var result = ['a', length];
			for (var i = 0; i < length; i++) {
				var subResult = getSerializedValue(value[i]);
				result.pushAll(subResult);
			}
			return result;
		} else if (typeof value == 'object' && typeof value.serializableFields != 'undefined') {
			var result = ['o'];
			var fields = value.serializableFields;
			var length = fields.length;
			for (var fieldIdx = 0; fieldIdx < length; fieldIdx++) {
				var subValue = value[fields[fieldIdx]];
				var subResult = getSerializedValue(subValue);
				result.pushAll(subResult);
			}
			return result;
		} else {
		}
		return;
	}
	
	A9ClickriverWidget.setSerializableFields(cr_params);
	var serValue = getSerializedValue(cr_params);
	return serValue.join('~');
}

A9ClickriverWidget.deserializeConfig = function(s) {
	function getDeserializedValue(object, tokens, currentIndex) {
		var type = tokens[currentIndex];
		switch (type) {
			case '':
				return [undefined, 1];
				break;
			case 's':
				var result = unescape(tokens[currentIndex + 1]);
				return [result, 2];
				break;
			case 'n':
				var result = parseFloat(tokens[currentIndex + 1]);
				return [result, 2];
				break;
			case 'b':
				var result = tokens[currentIndex + 1] == '1' ? true : false;
				return [result, 2];
				break;
			/*case 'f':
				eval('var result = ' + unescape(tokens[currentIndex + 1]));
				return [result, 2];
				break;*/
			case 'a':
				var nbElems = tokens[currentIndex + 1];
				var newIndex = currentIndex + 2;
				var result = [];
				for (var i = 0; i < nbElems; i++) {
					var innerResult = getDeserializedValue(object, tokens, newIndex);
					result[i] = innerResult[0];
					newIndex += innerResult[1];
				}
				return [result, newIndex - currentIndex];
				break;
			case 'o':
				var newIndex = currentIndex + 1;
				var fields = object.serializableFields;
				for (var fieldIdx = 0; fieldIdx < fields.length; fieldIdx++) {
					var fieldName = fields[fieldIdx];
					var targetObject = object[fieldName];
					var innerResult = getDeserializedValue(targetObject, tokens, newIndex);
					
					if (typeof innerResult != 'undefined' && typeof innerResult[0] != 'undefined') {
						object[fieldName] = innerResult[0];
					}
					newIndex += innerResult[1];
				}
				return [object, newIndex - currentIndex];
				break;
		}
		return undefined;
	}
	
	var tokens = s.split('~');
	var cr_params = {};
	A9ClickriverWidget.setSerializableFields(cr_params);
	return getDeserializedValue(cr_params, tokens, 0)[0];
}

A9ClickriverWidget.weightedRandomSelect = function(array) {
	var total_weight = 0;
	var length = array.length;
	for (var i = 1; i < length; i += 2) {
		total_weight += array[i];
	}
	var rand = Math.random() * total_weight;
	var previous_weights = 0;
	for (var i = 1; i < length; i += 2) {
		if (rand < previous_weights + array[i]) {
			return array[i - 1];
		}
		previous_weights += array[i];
	}          
	return array[length - 1];          
}

A9ClickriverWidget.fixEncoding = function(str) {
    str = str.replace(/\u0080/g, '\u20ac');
    str = str.replace(/\u0082/g, '\u201a');
    str = str.replace(/\u0084/g, '\u201e');
    str = str.replace(/\u0085/g, '\u2026');
    str = str.replace(/\u0089/g, '\u2030');
    str = str.replace(/\u008b/g, '\u2039');
    str = str.replace(/\u0091/g, '\u2018');
    str = str.replace(/\u0092/g, '\u2019');
    str = str.replace(/\u0093/g, '\u201c');
    str = str.replace(/\u0094/g, '\u201d');
    str = str.replace(/\u0096/g, '\u2013');
    str = str.replace(/\u0097/g, '\u2014');
    str = str.replace(/\u0099/g, '\u2122');
    str = str.replace(/\u009b/g, '\u203a');
    str = str.replace(/\u00c2\u00ae/g, '\u00ae');
    return str;
}

A9ClickriverWidget.getWrappableText = function(text) {
	/*var result = text.replace(/\./g, zerospace + '.');
	result = result.replace(/\//g, zerospace + '/');
	result = result.replace(/-/g, zerospace + '-');
	result = result.replace(/_/g, zerospace + '_');
	return result;*/
	return text.split('').join('<wbr>');
}


A9ClickriverWidget.baseURL = "http://sl.a9.com/";
A9ClickriverWidget.pictureBaseURL = A9ClickriverWidget.baseURL + "cfp/";
A9ClickriverWidget.iframeLocation = A9ClickriverWidget.baseURL + "/cfp-iframe.jsp";

A9ClickriverWidget.templates = {};
A9ClickriverWidget.templates['160x600'] = {};
A9ClickriverWidget.templates['160x600'].render_order = ['t', 'l', 'u'];
A9ClickriverWidget.templates['160x600'].ad_count = 4;
A9ClickriverWidget.templates['160x600'].columns = 1;
A9ClickriverWidget.templates['160x600'].icon_allowed = false;

A9ClickriverWidget.templates['240x400'] = {};
A9ClickriverWidget.templates['240x400'].render_order = ['t', 'l', 'u'];
A9ClickriverWidget.templates['240x400'].ad_count = 5;
A9ClickriverWidget.templates['240x400'].columns = 1;
A9ClickriverWidget.templates['240x400'].icon_allowed = true;
A9ClickriverWidget.templates['240x400'].ad_count_icon = 4;
A9ClickriverWidget.templates['240x400'].columns_icon = 1;

A9ClickriverWidget.templates['300x250'] = {};
A9ClickriverWidget.templates['300x250'].render_order = ['t', 'l', 'u'];
A9ClickriverWidget.templates['300x250'].ad_count = 3;
A9ClickriverWidget.templates['300x250'].columns = 1;
A9ClickriverWidget.templates['300x250'].icon_allowed = true;
A9ClickriverWidget.templates['300x250'].ad_count_icon = 2;
A9ClickriverWidget.templates['300x250'].columns_icon = 1;

A9ClickriverWidget.templates['300x600'] = {};
A9ClickriverWidget.templates['300x600'].render_order = ['t', 'l', 'u'];
A9ClickriverWidget.templates['300x600'].ad_count = 8;
A9ClickriverWidget.templates['300x600'].columns = 1;
A9ClickriverWidget.templates['300x600'].icon_allowed = true;
A9ClickriverWidget.templates['300x600'].ad_count_icon = 7;
A9ClickriverWidget.templates['300x600'].columns_icon = 1;

A9ClickriverWidget.templates['336x280'] = {};
A9ClickriverWidget.templates['336x280'].render_order = ['t', 'l', 'u'];
A9ClickriverWidget.templates['336x280'].ad_count = 3;
A9ClickriverWidget.templates['336x280'].columns = 1;
A9ClickriverWidget.templates['336x280'].icon_allowed = true;
A9ClickriverWidget.templates['336x280'].ad_count_icon = 3;
A9ClickriverWidget.templates['336x280'].columns_icon = 1;

A9ClickriverWidget.templates['400x250'] = {};
A9ClickriverWidget.templates['400x250'].render_order = ['t', 'l', 'u'];
A9ClickriverWidget.templates['400x250'].ad_count = 4;
A9ClickriverWidget.templates['400x250'].columns = 1;
A9ClickriverWidget.templates['400x250'].icon_allowed = true;
A9ClickriverWidget.templates['400x250'].ad_count_icon = 3;
A9ClickriverWidget.templates['400x250'].columns_icon = 1;

A9ClickriverWidget.templates['468x60'] = {};
A9ClickriverWidget.templates['468x60'].render_order = ['t', 'l'];
A9ClickriverWidget.templates['468x60'].ad_count = 2;
A9ClickriverWidget.templates['468x60'].columns = 2;
A9ClickriverWidget.templates['468x60'].icon_allowed = false;

A9ClickriverWidget.templates['468x240'] = {};
A9ClickriverWidget.templates['468x240'].render_order = ['t', 'l', 'u'];
A9ClickriverWidget.templates['468x240'].ad_count = 4;
A9ClickriverWidget.templates['468x240'].columns = 1;
A9ClickriverWidget.templates['468x240'].icon_allowed = true;
A9ClickriverWidget.templates['468x240'].ad_count_icon = 3;
A9ClickriverWidget.templates['468x240'].columns_icon = 1;

A9ClickriverWidget.templates['470x350'] = {};
A9ClickriverWidget.templates['470x350'].render_order = ['t', 'l', 'u'];
A9ClickriverWidget.templates['470x350'].ad_count = 6;
A9ClickriverWidget.templates['470x350'].columns = 1;
A9ClickriverWidget.templates['470x350'].icon_allowed = true;
A9ClickriverWidget.templates['470x350'].ad_count_icon = 5;
A9ClickriverWidget.templates['470x350'].columns_icon = 1;

A9ClickriverWidget.templates['728x180'] = {};
//A9ClickriverWidget.templates['728x180'].render_order = ['t', 'u', 's', 'l'];
//A9ClickriverWidget.templates['728x180'].ad_count = 4;
//A9ClickriverWidget.templates['728x180'].columns = 1;
A9ClickriverWidget.templates['728x180'].render_order = ['t', 'l', 'u'];
A9ClickriverWidget.templates['728x180'].ad_count = 6;
A9ClickriverWidget.templates['728x180'].columns = 3;
A9ClickriverWidget.templates['728x180'].icon_allowed = true;
A9ClickriverWidget.templates['728x180'].ad_count_icon = 4;
A9ClickriverWidget.templates['728x180'].columns_icon = 2;

A9ClickriverWidget.templates['728x90'] = {};
A9ClickriverWidget.templates['728x90'].render_order = ['t', 'l', 'u'];
A9ClickriverWidget.templates['728x90'].ad_count = 3;
A9ClickriverWidget.templates['728x90'].columns = 3;
A9ClickriverWidget.templates['728x90'].icon_allowed = true;
A9ClickriverWidget.templates['728x90'].ad_count_icon = 2;
A9ClickriverWidget.templates['728x90'].columns_icon = 2;

A9ClickriverWidget.prototype.onResponse = function(response) {
	var hasAds = (typeof response.ads != 'undefined' && response.ads.length != 0);
	var hasCategories = (typeof response.categories != 'undefined' && response.categories.length != 0);
	if (hasAds) {
		if (this.firstCall) {
			if (typeof response.suppress_footer != 'undefined') {
				this.config.suppress_footer = response.suppress_footer;
			}
			if (typeof response.picture_url_subdir != 'undefined') {
				this.config.picture_url_subdir = response.picture_url_subdir;
			}
			A9ClickriverWidget.includeCSS();
			this.generateCSSOverrides();
			//this.changeLocation.create();
		} else {
			this.changeLocation.clearErrors();
			this.changeLocation.hide();
			response.categories[0].isLocationUserChangeable = 'true';
		}
		this.render(response);
	} else {
		if (this.firstCall) {
			if (hasCategories) {
				this.punt();
			}
		} else {
			this.changeLocation.onError();
		}
	}
	this.firstCall = false;
}

A9ClickriverWidget.prototype.getContainer = function() {
	return document.getElementById(this.divId);
}

A9ClickriverWidget.prototype.getLinkElementDivId = function() {
	return this.divId + '_linkelem';
}

A9ClickriverWidget.prototype.getItemsOrder = function() {
	return this.template.render_order;
}

A9ClickriverWidget.prototype.requestAds = function() {
	var script = document.createElement('script');
	script.type = 'text/javascript';
	script.charset = 'UTF-8';
	
	var chosenCategories;
	
	if (typeof this.config.categories == 'string') {
		chosenCategories = this.config.categories;
	} else {
		chosenCategories = A9ClickriverWidget.weightedRandomSelect(this.config.categories);
	}
	
	var url = (this.config.url) ? escape(this.config.url) : escape(document.location.href);
	script.src = A9ClickriverWidget.baseURL + 'synd?oenc=UTF-8&pub=cfp&pubKey=' + this.config.pub_key + '&cat=' + escape(chosenCategories) 
		+ '&ch=' + escape(this.config.channel) + '&url=' + url + '&useragent=' + escape(navigator.userAgent)
		+ '&cfpjsv=1&adspercat=' + this.default_ad_count + (this.config.test_mode ? '&adtest=on' : '') + '&divid=' + this.divId + this.overridenParams + "&rnd=" + (new Date()).getTime();
		//+ "&numretr=" + 0;    
	
	this.getContainer().appendChild(script);
}

A9ClickriverWidget.includeCSS = function() {
	//var cssLocation = document.location.protocol + '//sl.a9.com/cfp.css';
	var cssLocation = A9ClickriverWidget.baseURL + 'cfp.css';
	
	//Setting up the CSS
	var head = document.getElementsByTagName('head')[0];         
	var css = document.createElement('link');
	css.type = 'text/css';
	css.rel = 'stylesheet';
	css.href = cssLocation;
	head.appendChild(css);
}

A9ClickriverWidget.isColor = function(s) {
    return /^\s*#\s*[\da-fA-F]{0,6}\s*$/.test(s) || /^\s*\w+\s*$/.test(s) || /^\s*rgb\s*\((?:\s*[\da-fA-F]+\s*%?\s*,){2}\s*[\da-fA-F]+\s*%?\s*\)\s*$/.test(s);
}

A9ClickriverWidget.prototype.generateCSSOverrides = function() {
	if (!this.config.css_overrides) {
		return;
	}
	
	var head = document.getElementsByTagName('head')[0];         
	var inlineCSS = document.createElement('style');
	inlineCSS.type = 'text/css';
	
	var text = '';
	if (this.config.css_overrides.ad_unit_border_color) {
		var color = this.config.css_overrides.ad_unit_border_color;
		if (A9ClickriverWidget.isColor(color)) {
			text += '.a9_ad#' + this.divId + ' {border-color:' + color + ";}\n";
			text += '.a9_ad#' + this.divId + ' .header {border-color:' + color + ";}\n";
		}
	}
	if (this.config.css_overrides.header_link_color || this.config.css_overrides.ad_unit_link_color) {
		var color = this.config.css_overrides.header_link_color || this.config.css_overrides.ad_unit_link_color;
		if (A9ClickriverWidget.isColor(color)) {
			text += '.a9_ad#' + this.divId + ' .changelocation {color:' + color + ";}\n";
		}
	}
	if (this.config.css_overrides.body_link_color || this.config.css_overrides.ad_unit_link_color) {
		var color = this.config.css_overrides.body_link_color || this.config.css_overrides.ad_unit_link_color;
		if (A9ClickriverWidget.isColor(color)) {
			text += '.a9_ad#' + this.divId + ' .ad div.title a:link, ' 
				+ '.a9_ad#' + this.divId + ' .ad div.title a:visited, ' 
				+ '.a9_ad#' + this.divId + ' .ad div.title a:active, '
				+ '.a9_ad#' + this.divId + ' .ad div.url a:link, ' 
				+ '.a9_ad#' + this.divId + ' .ad div.url a:visited, ' 
				+ '.a9_ad#' + this.divId + ' .ad div.url a:active '
				+ '{color:' + color + ";}\n";
		}
	}
	if (this.config.css_overrides.header_bg_color) {
		var color = this.config.css_overrides.header_bg_color;
		if (A9ClickriverWidget.isColor(color)) {
			text += '.a9_ad#' + this.divId + ' .header {background-color:' + color + ";}\n";
		}
	}
	if (this.config.css_overrides.header_text_color) {
		var color = this.config.css_overrides.header_text_color;
		if (A9ClickriverWidget.isColor(color)) {
			text += '.a9_ad#' + this.divId + ' .title_changeloc .title {color:' + color + ";}\n";
			text += '.a9_ad#' + this.divId + ' .footer_title a.footerlink:link, ' 
				+ '.a9_ad#' + this.divId + ' .footer_title a.footerlink:visited, ' 
				+ '.a9_ad#' + this.divId + ' .footer_title a.footerlink:active '
				+ '{color:' + color + ";}\n";
		}
	}
	if (this.config.css_overrides.body_bg_color) {
		var color = this.config.css_overrides.body_bg_color;
		if (A9ClickriverWidget.isColor(color)) {
			text += '.a9_ad#' + this.divId + ' {background-color:' + color + ";}\n";
			text += '.a9_ad#' + this.divId + ' .content {background-color:' + color + ";}\n";
		}
	}
	if (this.config.css_overrides.body_text_color) {
		var color = this.config.css_overrides.body_text_color;
		if (A9ClickriverWidget.isColor(color)) {
			text += '.a9_ad#' + this.divId + ' .lines {color:' + color + ";}\n";
			text += '.a9_ad#' + this.divId + ' .footer_content a.footerlink:link, ' 
				+ '.a9_ad#' + this.divId + ' .footer_content a.footerlink:visited, ' 
				+ '.a9_ad#' + this.divId + ' .footer_content a.footerlink:active '
				+ '{color:' + color + ";}\n";
		}
	}
	
	if (inlineCSS.styleSheet) {
		inlineCSS.styleSheet.cssText= text;
	} else {
		inlineCSS.appendChild(document.createTextNode(text));
	}
	
	head.appendChild(inlineCSS);
}

A9ClickriverWidget.prototype.refreshAds = function() {
	var script = document.createElement('script');
	script.type = 'text/javascript';
	script.charset = 'UTF-8';
	script.src= A9ClickriverWidget.baseURL + 'js?oenc=UTF-8&rnd='+ (new Date()).getTime() + '&userLocationInput=' + this.changeLocation.userLocation + '&r=' + this.refreshId + '&requestedCat=' + this.category;
	
	this.getContainer().appendChild(script);
}

A9ClickriverWidget.prototype.punt = function() {
	var scriptAttrs = ['src', 'type', 'charset', 'language'];
	//var iframeAttrs = ['width', 'height', 'style', 'src'];

	function setAttrs(sourceNode, destNode, attributes) {
		for (var i = 0; i < attributes.length; i++) {
			var key = attributes[i];
			if (sourceNode.getAttribute(key)) {
				destNode.setAttribute(key, sourceNode.getAttribute(key));
			}
		}
	}

	function clone(node) {
		if (node.nodeType == 1 && node.tagName.toLowerCase() == 'script') {
			var script = document.createElement("script");
			setAttrs(node, script, scriptAttrs);
			
			if (typeof script.text != 'undefined') {
				script.text = node.innerHTML;
			} else {
				script.innerHTML = node.innerHTML;
			}
			return script;
		} else {
			var c = node.cloneNode(false);
			if (node.hasChildNodes()) {
				var children = node.childNodes;
				for (var i = 0; i < children.length; i++) {
					c.appendChild(clone(children[i]));
				}
			}
			return c;
		}

	}
	
	var div = document.createElement('div');
	div.innerHTML = this.config.passback;
	
	var dest = clone(div);
	var container = this.getContainer();
	container.className = '';
	container.appendChild(dest);
}

A9ClickriverWidget.prototype.render = function(response) {
	var container = this.getContainer();
	var itemsOrder = this.getItemsOrder();
	
	container.className = "a9_ad a9_ad_" + this.config.template_name;
	if (this.config.show_category_icon) {
		container.className += " a9_ad_wgr " + "a9_ad_" + this.config.template_name + "_wgr";
	}
	if (!this.config.collapse_blank_space) {
		container.className += " a9_ad_" + this.config.template_name + "_noc";
	}
	if (this.config.css_overrides && this.config.css_overrides.ad_unit_border_color) {
		container.className += " a9_ad_border a9_ad_" + this.config.template_name + "_border";
	}
	if (!this.config.collapse_blank_space && this.config.css_overrides && this.config.css_overrides.ad_unit_border_color) {
		container.className += " a9_ad_" + this.config.template_name + "_border_noc";
	}
	
	var category = response.categories[0];
	this.category = category.tag;
	this.refreshId = response.refresh;
	
	var ads_html = '<div class="header">';
	// Picture
	var pictureURL = A9ClickriverWidget.pictureBaseURL + this.config.picture_url_subdir + category["tag"] + ".jpg";        
	if (this.config.show_category_icon) { 
		ads_html += '<div class="picture_title"><img src="' + pictureURL + '"/></div>';    
	}
	
	// Title
	ads_html += '<div class="title_changeloc"><span class="title">' + category.title + '</span>';
	if (!this.config.suppress_change_location && category.isLocationUserChangeable == 'true') {
		ads_html += '<span class="changelocation_wrapper"><span class="changelocation" id="' + this.getLinkElementDivId() + '" onmouseover="A9ClickriverWidget.getWidget(\'' + this.divId + '\').changeLocation.scheduleShow();" onmouseout="A9ClickriverWidget.getWidget(\'' + this.divId + '\').changeLocation.scheduleHide();">Change Location</span></span>';
	}
	ads_html += '</div>';
	if (!this.config.suppress_footer) {
		ads_html += '<div class="footer_title"><a class="footerlink" href="http://clickriver.com/" target="_blank">Clickriver Ads</a></div>';
	}
	ads_html += '<div class="row_separator"></div></div>';
	
	// Main content
	ads_html += '<div class="content">';
	
	if (this.config.show_category_icon) { 
		ads_html += '<div class="picture_content"><img src="' + pictureURL + '"/></div>';    
	}
	
	ads_html += '<div class="ads">';

	for (var i = 0, length = response.ads.length; i < length; i++) {
		if ((this.columns > 1) && (i % this.columns == 0) && (i > 0)) {
			ads_html += '<div class="row_separator"></div>';
		}
		ads_html += '<div class="ad_floater">';
		ads_html += '<div class="ad">';
		
		var ad = response.ads[i];
		var adTitle = A9ClickriverWidget.fixEncoding(ad.line1);
		var adLine1 = A9ClickriverWidget.fixEncoding(ad.line2);
		var adLine2 = A9ClickriverWidget.fixEncoding(ad.line3);
		var adVisibleURL = A9ClickriverWidget.getWrappableText(ad.visible_url);
		
		for (var j = 0; j < itemsOrder.length; j++) {  
			var item = itemsOrder[j];
			if (item == 't') {
				ads_html += '<div class="title"><a href="' + ad.url + '" target="_blank">' + adTitle + '</a></div>';
			}
			if (item == 'u') {
				ads_html += '<div class="url"><a href="' + ad.url + '" target="_blank">' + adVisibleURL + '</a></div>';
			}
			if (item == 'l') {
				ads_html += '<div class="lines"><span class="line1">' + adLine1 + '</span> <span class="line2">' + adLine2 + '</span></div>';
			}
			if (item == 's') {
				ads_html += '<span class="separator"></span>';
			}
		}
		
		ads_html += '</div></div>'; // ad + floater
	}
	
	ads_html += '<div class="row_separator"></div>';
	ads_html += '</div>'; // ads
	
	ads_html += '</div>'; // content
	
	if (!this.config.suppress_footer) {
		ads_html += '<div class="row_separator"></div>';
		ads_html += '<div class="footer_content"><a class="footerlink" href="http://clickriver.com/" target="_blank">Clickriver Ads</a></div>';
		ads_html += '<div class="row_separator"></div>';
	}
	
	container.innerHTML = ads_html;
}


function A9ClickriverCLPopup(widget) {
	this.widget = widget;
	this.showTimer = null;
	this.hideTimer = null;
	this.showTimerDelay = 500;
	this.hideTimerDelay = 500;
	
	this.create();
}

A9ClickriverCLPopup.prototype.create = function() {
	clDiv = document.createElement('div');
	clDiv.className = 'a9_ad_change_location_popup a9_ad_change_location_popup_' + this.widget.config.template_name;
	clDiv.id = this.getChangeLocationDivId();
	
	var zipDivId = this.getZipDivId();
	var html = "<div class='label'>Enter a Zip Code to see service providers in another area.</div>";
	html += "<div id='" + this.getErrorDivId() + "' class='error_msg'></div>";
	html += "<div><input id='" + zipDivId + "' name='" + zipDivId + "' class='zip' onkeypress='return A9ClickriverWidget.getWidget(\"" + this.widget.divId + "\").changeLocation.onSubmit(event)' onclick='this.value=\"\"' value='Enter Zip Code'/>";
	html += "<span class='go_button' onclick='A9ClickriverWidget.getWidget(\"" + this.widget.divId + "\").changeLocation.onSubmit(event)'>&nbsp;</span></div>";
	clDiv.innerHTML = html;
	clDiv.style.display = 'none';
	document.body.insertBefore(clDiv, document.body.firstChild);
	
	var self = this;
	this.setHandler(clDiv.id, 'onmouseover', function() {self.scheduleShow();});
	this.setHandler(clDiv.id, 'onmouseout', function() {self.scheduleHide();});
}

A9ClickriverCLPopup.prototype.setHandler = function(elemId, eventName, handlerFunction) {
	var elem = document.getElementById(elemId);
	elem[eventName] = handlerFunction;
}

A9ClickriverCLPopup.prototype.getChangeLocationDivId = function() {
	return this.widget.divId + '_change_location';
}

A9ClickriverCLPopup.prototype.getChangeLocationDiv = function() {
	return document.getElementById(this.getChangeLocationDivId());
}

A9ClickriverCLPopup.prototype.getZipDivId = function() {
	return this.widget.divId + '_zip';
}

A9ClickriverCLPopup.prototype.getErrorDivId = function() {
	return this.widget.divId + '_error';
}

A9ClickriverCLPopup.prototype.findPosition = function(root, object) {
	var curleft = 0;
	var curtop = 0;
	while (object.offsetParent && object != root) {
		curleft += object.offsetLeft;
		curtop += object.offsetTop;
		object = object.offsetParent;
	}
	return [curleft, curtop];
}

A9ClickriverCLPopup.prototype.isVisible = function() {
	var clDiv = this.getChangeLocationDiv();
	return (clDiv.style.display != 'none');
}

A9ClickriverCLPopup.prototype.scheduleShow = function() {
	if (this.isVisible()) {
		if (this.hideTimer != null) {
			clearTimeout(this.hideTimer);
			this.hideTimer = null;
		}
	} else {
		if (this.showTimer == null) {
			var self = this;
			this.showTimer = setTimeout(function() {self.show();}, this.showTimerDelay);
		}
	}
}

A9ClickriverCLPopup.prototype.scheduleHide = function() {
	if (!this.isVisible()) {
		if (this.showTimer != null) {
			clearTimeout(this.showTimer);
			this.showTimer = null
		}
	} else {
		if (this.hideTimer == null) {
			var self = this;
			this.hideTimer = setTimeout(function() {self.hide();}, this.hideTimerDelay);
		}
	}
}

A9ClickriverCLPopup.prototype.show = function() {
	this.showTimer = null;
	
	var clDiv = this.getChangeLocationDiv();
	clDiv.style.display = 'inline';
	var container = this.widget.getContainer();
	
	var linkElement = document.getElementById(this.widget.getLinkElementDivId());
	var linkPosition = this.findPosition(document, linkElement);
	var clLeft = linkPosition[0] + linkElement.offsetWidth - clDiv.offsetWidth;
	if (clLeft <= 1) {
		clLeft = 1;
	}
	var clTop = linkPosition[1] + linkElement.offsetHeight;
	
	clDiv.style.left = clLeft + "px";
	clDiv.style.top =  clTop + "px"; 
}

A9ClickriverCLPopup.prototype.hide = function() {
	this.hideTimer = null;
	
	var clDiv = this.getChangeLocationDiv();
	clDiv.style.display = 'none';
}

A9ClickriverCLPopup.prototype.onSubmit = function(event) {
	var zipDiv = document.getElementById(this.getZipDivId());
	var keyCode = (event.which == null) ? event.keyCode : event.which;
	if (event.type == 'keypress' && keyCode != 13) {
		if (zipDiv.value.length < 5 || keyCode == 0 || keyCode == 8) {
			return true;
		} else {
			return false;
		}
	}
	
	var clDiv = this.getChangeLocationDiv();
	var zip = zipDiv.value;
	if (!zip.match(/^[0-9]{5}$/)) { 
		var span = document.getElementById(this.getErrorDivId());
		span.innerHTML = "You must enter a valid U.S. Zip Code.";
		span.style.display = "block";
		return;
	}
	this.userLocation = zip;
	
	this.widget.refreshAds();
	return true;
}

A9ClickriverCLPopup.prototype.onError = function() {
	var errorDiv = document.getElementById(this.getErrorDivId());
	errorDiv.innerHTML = "No services found in this area";
	errorDiv.style.display = "block";
}

A9ClickriverCLPopup.prototype.clearErrors = function() {
	var errorDiv = document.getElementById(this.getErrorDivId());
	errorDiv.innerHTML = "";
	errorDiv.style.display = "none";
}


if (typeof cr_params != 'undefined') {
	A9ClickriverWidget.createWidget(cr_params);
}