// Dynamik
// by Peytz & Co., http://peytz.dk/
// $Revision: 1.36 $

if (typeof dynamik == 'undefined') {

var dynamik = {
	customerName : false,
	method : null,
	args : null,
	selectUrl : null,
	failedUrl : null,
	spots : [],
	placeholders : [],
	placeholderId : 0,
	timeoutId : null,
	emptyFileRoot : null,
	initialized : false,
	documentLoaded : false,
	pageLoaded : false,
	spotsLoaded : false,
	serverTime : 0,
	cycle : false,

	init : function(args) {
		this.args = args;

		if (typeof this.args.emptyFileRoot != 'undefined') {
			this.emptyFileRoot = this.args.emptyFileRoot;
		} else {
			this.emptyFileRoot = this.args.dynamikRoot;
		}

		if (typeof this.args.finishCalledInline == 'undefined') {
			this.args.finishCalledInline = false;
		}

		this.spots = [];
		this.spotsLoaded = false;
		this.serverTime = 0;
		for (var i = 0; i < dynamik.placeholders.length; i++) {
			dynamik.placeholders[i].cycleIndex = -1;
		}
		for (var i = 0; i < args.methods.length; i++) {
			var m = args.methods[i];
			if (!m) continue;
			dynamik.selectUrl = dynamik.getSelectUrl(m.output);
			if (dynamik.selectUrl && m.init()) {
				this.method = m;
				break;
			}
		}
		if (!this.method) {
			dynamik.selectUrl = null;
		}
		if (!this.initialized) {
			this.initialized = true;
		} else {
			this.cycle = false;
			if (this.pageLoaded && typeof this.method.onPageLoad != 'undefined') {
				this.method.onPageLoad();
			}
			if (this.spotsLoaded) {
				dynamik.displaySpots();
			}
			this.cycle = true;
		}
	},
	getSelectUrl : function(output) {
		var url;
		if (this.args.useStaticSelect) {
			if (typeof this.args.staticSelectUrls == 'object' &&
				typeof this.args.staticSelectUrls[output] == 'string') {

				url = this.args.staticSelectUrls[output];
			} else {
				url = false;
			}

		} else {
			url = this.args.dynamikRoot + 'select.php?site=' + escape(this.args.area);

			if (typeof this.args.cacheCount != 'undefined') {
				var count = parseInt(dynamikGetCookie('cacheCount'));
				if (isNaN(count)) {
					count = 0;
				}
				if (count >= this.args.cacheCount) {
					count = 0;
				}
				url += '&cacheCount=' + count;
				if (this.args.cacheCount > 1) {
					dynamikSetCookie('cacheCount', count + 1);
				}
				if (typeof this.args.cacheTime != 'undefined') {
					url += '&cacheTime=' + this.args.cacheTime;
				}
			} else {
				url += '&rnd=' + (new Date()).getTime();
			}
			var flash = dynamikBrowser.getFlashVersion();
			if (flash >= 6) {
				url += '&browser[flash]=6';
			}

			for (var i = 0; i < this.args.queries.length; i++) {
				var query = this.args.queries[i];
				if (!query) continue;
				for (var p in query) {
					if (p == 'count' || p == 'format' || p == 'pool' || p == 'advertiserId') {
						url += '&query[' + i + '][' + p + ']=' + escape(query[p]);
					}
				}
			}
			url += '&dynamikRoot=' + escape(this.args.dynamikRoot);
			if (typeof this.args.target != 'undefined') {
				url += '&target=' + escape(this.args.target);
			}
			if (typeof this.args.display != 'undefined') {
				for (var p in this.args.display) {
					url += '&display[' + p + ']=' + escape(this.args.display[p]);
				}
			}
			if (typeof this.args.user != 'undefined') {
				for (var p in this.args.user) {
				url += '&user[' + p + ']=' + escape(this.args.user[p]);
				}
			}
			if (output == 'cookie') {
				url += '&cookieDomain=' + dynamik.args.cookieDomain;
			}
			url += '&output=' + output;
		}

		return url;
	},
	writeScriptTag : function() {
		document.write('<script type="text/javascript" id="dynamik-script-include"' +
			' src="' + this.selectUrl + '" charset="iso-8859-1" defer></script>');
	},
	getSpotHtml : function(format, count, cycle) {
		var html = '';
		if (!count) count = 1;
		if (this.spotsLoaded && !cycle) {
			for (var i = 0; i < count; i++) {
				var spot = dynamikSpot.getUndisplayed(format);
				if (!spot) break;
				html += spot.html;
				spot.isDisplayed = true;
			}
		} else {
			var placeholder = new dynamikPlaceholder(format, count);
			placeholder.cycle = Boolean(cycle);
			placeholder.cycleIndex = -1;
			html = '<div id="' + placeholder.getElementId() + '"></div>';
		}
		return html;
	},
	insertSpot : function(format, count, cycle) {
		var html = this.getSpotHtml(format, count, cycle);
		if (html) {
			document.write(html);
		}
	},
	onSpotsBeginLoad : function() {
		if (typeof this.args.timeout != 'undefined') {
			this.timeoutId = window.setTimeout(
				'dynamik.onTimeout()', this.args.timeout * 1000);
		}
	},
	onSpotsLoad : function() {
		this.spotsLoaded = true;
		if (this.timeoutId) {
			window.clearTimeout(this.timeoutId);
		}
		this.timeoutId = null;
		dynamik.displaySpots();
	},
	onSpotsLoaded : function() { // DEPRECATED
		this.onSpotsLoad();
	},
	onTimeout : function() {
		if (this.method && typeof this.method.onTimeout != 'undefined') {
			this.method.onTimeout();
		}
		this.onServerError();
	},
	onServerError : function() {
		if (!this.args.useStaticSelect) {
			this.args.useStaticSelect = true;
			var m = dynamikMethodJavascriptBottom;
			dynamik.selectUrl = dynamik.getSelectUrl(m.output);
			if (dynamik.selectUrl && m.init()) {
				this.method = m;
				this.method.onPageLoad();
			} else {
				dynamik.selectUrl = null;
			}
		}
	},
	finish : function() {
		if (this.method && !this.pageLoaded) {
			this.pageLoaded = true;
			if (typeof this.method.onPageLoad != 'undefined') {
				this.method.onPageLoad();
			}
			if (this.spotsLoaded) {
				dynamik.displaySpots();
			}
		}
		this.cycle = true;
	},
	displaySpots : function() {
		for (var i = 0; i < dynamik.placeholders.length; i++) {
			var placeholder = dynamik.placeholders[i]; 
			var div = document.getElementById(placeholder.getElementId());
			if (!div) {
				return;
			}
			var j, spots;
			if (placeholder.cycle) {
				spots = dynamikSpot.getAllByFormat(placeholder.format);
				j = Math.min(placeholder.remaining, spots.length);
				if (spots.length <= 1 && placeholder.cycleIndex != -1) {
					j = 0;
				} else {
					div.innerHTML = '';
				}
			} else {
				j = placeholder.remaining;
			}
			var html = '';
			for (; j > 0; j--) {
				var spot;
				if (placeholder.cycle) {
					placeholder.cycleIndex = (placeholder.cycleIndex + 1) % spots.length;
					spot = spots[placeholder.cycleIndex];
				} else {
					spot = dynamikSpot.getUndisplayed(placeholder.format);
					if (!spot) break;
					placeholder.remaining--;
				}
				html += spot.html;
				spot.isDisplayed = true;
			}
			if (html) {
				div.innerHTML = html;
			}
		}
	},
	cycleSpots : function() { dynamik.displaySpots(); },
	logClick : function(spotId) {
		var url = this.args.dynamikRoot + 'click.php?output=image' +
			'&site=' + escape(this.args.area) + '&spotId=' + spotId;
		var img = new Image();
		img.src = url;
	}
}

var dynamikBrowser = {
	supportsDynamicInsert : function() {
		var e;
		return typeof document.createElement != 'undefined' &&
			(e = document.createElement('span')) &&
			typeof e.innerHTML == 'string';
	},
	supportsDynamicScriptInsert : function() {
		return dynamikBrowser.getIEVersion() >= 5 && !dynamikBrowser.isMac() ||
			dynamikBrowser.isGecko() ||
			dynamikBrowser.getOperaVersion() >= 7.5;
	},
	isIE : function() {
		return navigator.userAgent.indexOf('MSIE') != -1 && !this.isOpera();
	},
	isGecko : function() {
		return navigator.userAgent.indexOf('Gecko') != -1 &&
			navigator.userAgent.indexOf('like Gecko') == -1;
	},
	isOpera : function() {
		return navigator.userAgent.indexOf('Opera') != -1;
	},
	isSafari : function() {
		return navigator.userAgent.indexOf('Safari') != -1;
	},
	isMac : function() {
		return navigator.userAgent.indexOf('Mac') != -1;
	},
	getIEVersion : function() {
		var i = navigator.userAgent.indexOf('MSIE');
		return this.isIE() && i != -1 ? parseFloat(navigator.userAgent.substr(i + 5)) : 0;
	},
	getOperaVersion : function() {
		var i = navigator.userAgent.indexOf('Opera');
		return i != -1 ? parseFloat(navigator.userAgent.substr(i + 6)) : 0;
	},
	getFlashVersion : function() {
		var version = 0;

		var cookie = parseInt(dynamikGetCookie('dynamikFlashVersion'));
		if (!isNaN(cookie)) {
			return cookie;
		}

		/*@cc_on @*/
		/*@if (@_jscript_version >= 5)
			for (var i = 8; i >= 3; i--) {
				try {
					if (new ActiveXObject('ShockwaveFlash.ShockwaveFlash.' + i)) {
						version = i;
						break;
					}
				} catch(e) {}
			}
		@end @*/

		if (version == 0 && typeof navigator.plugins != 'undefined') {
			if (typeof navigator.plugins['Shockwave Flash'] != 'undefined') { 
				var res = navigator.plugins['Shockwave Flash'].description.match(/(\d).\d/);
				if (res) {
					version = parseInt(res[1]);
				}
			}
		}

		dynamikSetCookie('dynamikFlashVersion', version);

		return version;
	}
}

// IE4+5 compatibility
if (typeof Array.prototype.push == 'undefined') {
	Array.prototype.push = function(e) { this[this.length] = e; }
}
// IE4 compatibility
if (typeof document.getElementById == 'undefined' && typeof document.all != 'undefined') {
	document.getElementById = function(id) { return document.all[id]; };
}
if (typeof window.addEventListener != 'undefined') {
	window.addEventListener('load', function() { dynamik.documentLoaded = true; }, false);
}

function dynamikSpot(id, format, html) {
	this.id = id;
	this.format = format;
	this.html = html;
	this.isDisplayed = false;
}
dynamikSpot.getAllByFormat = function(format) {
	var spots = [];
	for (var i = 0; i < dynamik.spots.length; i++) {
		var spot = dynamik.spots[i];
		if (!format || spot.format == format) spots.push(spot);
	}
	return spots;
}
dynamikSpot.getUndisplayed = function(format) {
	var spots = this.getAllByFormat(format);
	for (var i = 0; i < spots.length; i++) {
		if (!spots[i].isDisplayed) return spots[i];
	}
	return null;
}

function dynamikPlaceholder(format, count) {
	this.format = format;
	this.count = count;
	this.remaining = count;
	this.elementId = 'dynamikPlaceholder' + dynamik.placeholderId++;
	dynamik.placeholders.push(this);
}
dynamikPlaceholder.prototype.getElementId = function() {
	return this.elementId;
}

var dynamikMethodJavascriptHead = {
	name : 'JavascriptHead',
	output : 'js',
	init : function() {
		if (dynamik.documentLoaded) {
			return false;
		}
		dynamik.onSpotsBeginLoad();
		dynamik.writeScriptTag();
		return true;
	},
	onTimeout : function() {
		var script = document.getElementById('dynamik-script-include');
		if (script && !dynamikBrowser.isIE() && dynamikBrowser.getIEVersion() < 5) {
			script.src = dynamik.emptyFileRoot + 'empty.js';
			script.parentNode.removeChild(script);
		}
	}
}
var dynamikMethodJavascriptBottom = {
	name : 'JavascriptBottom',
	output : 'js',
	init : function() {
		return dynamikBrowser.supportsDynamicInsert() &&
			(dynamik.args.finishCalledInline ||
			 dynamikBrowser.supportsDynamicScriptInsert());
	},
	onPageLoad : function() {
		dynamik.onSpotsBeginLoad();
		if (!dynamik.args.finishCalledInline &&
		    dynamikBrowser.supportsDynamicScriptInsert()) {

			var script = document.createElement('script');
			script.src = dynamik.selectUrl;
			script.type = 'text/javascript';
			script.charset = 'iso-8859-1';
			script.id = 'dynamik-script-include';
			var head = document.getElementsByTagName('head').item(0);
			head.appendChild(script);
		} else {
			dynamik.writeScriptTag();
		}
		return true;
	},
	onTimeout : function() {
		var script = document.getElementById('dynamik-script-include');
		script.src = dynamik.emptyFileRoot + 'empty.js';
		script.parentNode.removeChild(script);
	}
}
var dynamikMethodXmlHttp = {
	name : 'XmlHttp',
	output : 'xml',
	init : function(url) {
		if (!dynamikBrowser.supportsDynamicInsert()) {
			return false;
		}

		var i = dynamik.args.dynamikRoot.indexOf('/', 7);
		if (dynamik.args.dynamikRoot.substring(0, i) != location.href.substring(0, i)) {
			return false;
		}

		var xmlHttp = null;
		//the following is interpretend by IE though it looks like a comment
		/*@cc_on @*/
		/*@if (@_jscript_version >= 5)
			var ids = ['Msxml2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0',
				'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
			for (var i = 0; !xmlHttp && i < ids.length; i++) {
				try {
					xmlHttp = new ActiveXObject(ids[i]);
				} catch(e) {}
			}
		@end @*/
		if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
			xmlHttp = new XMLHttpRequest();
		}
		if (!xmlHttp || typeof xmlHttp.send == 'undefined') {
			return false;
		}
		var prevOnerror = window.onerror;
		window.onerror = function() { window.onerror = prevOnerror; return true; };
		xmlHttp.open('GET', dynamik.selectUrl, true);
		xmlHttp.onreadystatechange = function() {
			if (xmlHttp.readyState == 4) {
				if (!xmlHttp.responseXML) {
					return;
				}
				var nlSpots = xmlHttp.responseXML.getElementsByTagName('spots');
				if (nlSpots.length == 0) {
					return;
				}
				dynamik.serverTime = nlSpots.item(0).getAttribute('serverTime');
				dynamik.customerName = nlSpots.item(0).getAttribute('customerName');
				var nlSpot = nlSpots.item(0).getElementsByTagName('spot');
				for (var i = 0; i < nlSpot.length; i++) {
					elmSpot = nlSpot.item(i);
					spot = new dynamikSpot(
						elmSpot.getAttribute('id'),
						elmSpot.getAttribute('format'),
						elmSpot.firstChild.data);
					dynamik.spots.push(spot);
				}
				dynamik.onSpotsLoad();
			}
		}
		dynamik.onSpotsBeginLoad();
		xmlHttp.send(null);
		window.onerror = prevOnerror;
		return true;
	},
	bottom : dynamik.displaySpots
};
var dynamikMethodIframe = {
	name : 'Iframe',
	output : 'html',
	init : function() {
		var spot = new dynamikSpot(
			0,
			'282x116',
			'<iframe class="dynamikSpot" src="' + dynamik.selectUrl + '"' +
			' frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>');
		dynamik.spots.push(spot);
		return true;
	},
	onPageLoad : dynamik.displaySpots
}

function dynamikGetCookie(name) {
	var dc = document.cookie;
	if (dc.length > 0) {
		var begin = dc.indexOf(name + '=');
		if (begin != -1) {
			begin += name.length + 1;
			var end = dc.indexOf(';', begin);
			if (end == -1) {
				end = dc.length;
			}
			return unescape(dc.substring(begin, end).replace(/\+/g, ' '));
		}
	}
	return null;
}
function dynamikSetCookie(name, value, domain, expires) {
	document.cookie = name + '=' + escape(value) + '; ' +
		(expires ? 'expires=' + expires.toGMTString() + '; ' : '') +
		(domain ? 'domain=' + domain + '; ' : '') +
		'path=/';
}
function dynamikDeleteCookie(name) {
	dynamikSetCookie(name, 'deleted', dynamik.args.cookieDomain, new Date());
}

}

