function computedStyle(el, property)
{
	var style = false;

	if (el)
	{
		if (el.currentStyle)
			style = el.currentStyle[property.replace(/-([a-z])/, function($0,$1){ return $1.toUpperCase(); })];
		else if (window.getComputedStyle)
			style = document.defaultView.getComputedStyle(el, '').getPropertyValue(property);
	}
	
	return style;
}

// browser detect object
var is = {
	opera: !!window.opera,
	ie: /*@cc_on!@*/false,
	khtml: navigator.userAgent.indexOf('KHTML') > -1,
	gecko: navigator.userAgent.indexOf('KHTML') == -1 && navigator.userAgent.indexOf('Gecko') > -1,
	mac: navigator.userAgent.indexOf('Macintosh') > -1,
	handheld: computedStyle(document.documentElement, 'z-index') == 1
}

// debug - cancelable alert
if (window.debug)
{
	window.alert = function(alert)
	{
		if (!confirm(alert))
			throw 'stopped';
	}
}

// Preload stuff
var preloadImages = {};
if (!window.ImgURL) var ImgURL = '';
function preload(label, url, overwrite)
{
	if (overwrite || !(label in preloadImages))
	{
		if (url.indexOf('http://') != 0) url = ImgURL + url;
		preloadImages[label] = new Image();
		preloadImages[label].src = url;
	}
}

function getPreloadImage(label)
{
	if (label in preloadImages)
	{
		return preloadImages[label].src;
	}
	else if (label != 'empty')
	{
		preload('empty', 'g/px.gif');
		return getPreloadImage('empty');
	}
	else
	{
		return ImgURL + 'g/px/gif';
	}
}

function imgHoverOn()
{
	if (this.__hoverStateImg)
		this.src = getPreloadImage(this.__hoverStateImg);
}

function imgHoverOff()
{
	if (this.__normalStateImg)
		this.src = getPreloadImage(this.__normalStateImg);
}

function imageHoverSwap(img, normalStateImg, hoverStateImg)
{
	img.src = getPreloadImage(normalStateImg);

	if (!img.__hoverStateImg)
	{
		addEvent(img, 'mouseover', imgHoverOn);
		addEvent(img, 'mouseout', imgHoverOff);
	}

	img.__hoverStateImg = hoverStateImg;
	img.__normalStateImg = normalStateImg;
}

Object.extend = function(dest, source, allowOverwrite)
{
	for (var prop in source)
	{
		if (source.hasOwnProperty(prop) && (allowOverwrite || !dest.hasOwnProperty(prop)))
			dest[prop] = source[prop];
	}

	return dest;
}

Object.extend(Array.prototype,
{
	indexOf: function(searchElement, fromIndex)
	{
		var l = this.length, i = 0;
		if (fromIndex)
		{
			i = fromIndex;
			if (i < 0)
			{
				i += l;
				if (i < 0) i = 0;
			}
		}

		while (i < l)
		{
			if (this[i] === searchElement) return i;
			i++;
		}

		return -1;
	},
	forEach: function(func, obj)
	{
		for (var i = 0, l = this.length; i < l; i++)
		{
			if (i in this)
				func.call(obj, this[i], i, this);
		}
	},
	filter: function(func, obj)
	{
		var res = [], val;
		for (var i = 0, l = this.length; i < l; i++)
		{
			if (i in this)
			{
				val = this[i]; // in case func mutates this
			        if (func.call(obj, val, i, this))
					res.push(val);
			}
		}

		return res;
	}
});

// Generics
['forEach', 'filter', 'slice'].forEach(
	function(func)
	{
		if (!(func in Array))
		{
			Array[func] = function(obj)
			{
				return this.prototype[func].apply(obj, Array.prototype.slice.call(arguments, 1));
			}
		}
	}
);

Object.extend(String.prototype,
{
	trim: function()
	{
		return this.replace(/^\s+|\s+$/, '');
	},
	ucFirst: function()
	{
		return this.charAt(0).toUpperCase() + this.substr(1);
	},
	escapeHtml: function()
	{
		var escapeChars = {
			'&': '&amp;',
			'<': '&lt;',
			'>': '&gt;',
			'"': '&quot;'
		};

		return this.replace(/[&<>"]/g, function(c) { return escapeChars[c]; });
	},
	unescapeHtml: function()
	{
		var namedEntities = {
			'amp': '&',
			'lt': '<',
			'gt': '>',
			'quot': '"',
			'euro': String.fromCharCode(8364)
		};

		return this.replace(
			/&(amp|lt|gt|quot|euro|#\d+);/g,
			function(c,n)
			{
				return namedEntities[n] || String.fromCharCode(n.substr(1));
			}
		);
	}
});

Object.extend(Function.prototype,
{
	bind: function()
	{
		var handler = this, args = Array.slice(arguments, 0), obj = args.shift();

		return function()
		{
			return handler.apply(obj, args.concat(Array.slice(arguments, 0)));
		}
	}
});

RegExp.escape = function(string)
{
	return string.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1');
}

// handy
function Set()
{
	var set = {}, i = arguments.length;
	while (i--)
		set[arguments[i]] = 1;

	return set;
}

// cached id-ref getter
var idCache = {};
function getById(id)
{
	if (!(id in idCache))
		idCache[id] = document.getElementById(id);

	return idCache[id];
}

// execute methods on DOMload
var DomLoaded =
{
	onload: [],
	loaded: function()
	{
		if (DomLoaded.done) return;
		DomLoaded.done = true;

		if (DomLoaded.timer)
			clearInterval(DomLoaded.timer);

		if (DomLoaded.onload.length)
			DomLoaded.execute();
	},
	load: function(fireThis)
	{
		DomLoaded.onload.push(fireThis);

		if (DomLoaded.onload.length == 1)
		{
			if (document.addEventListener)
				document.addEventListener('DOMContentLoaded', DomLoaded.loaded, false);
			else
			{
				DomLoaded.timer = setInterval(function()
				{
					if (getById('domLoaded'))
						DomLoaded.loaded();
				}, 10);
			}

			// generic fallback
			addEvent(window, 'load', DomLoaded.loaded);
		}
	},
	execute: function()
	{
		var func = DomLoaded.onload.shift();

		if (typeof func == 'function')
			func();

		if (DomLoaded.onload.length)
			setTimeout(DomLoaded.execute, 10);
	}
}

// generic eventhandling
var addEvent = function()
{
	if (document.addEventListener)
	{
		function checkMouseLeaveOrEnter(element, handler)
		{
			return function(e)
			{
				var target = e.relatedTarget || (e.type == 'mouseover' ? e.fromElement : e.toElement);
				while (target)
				{
					if (target == element)
						return;

					target = target.parentNode;
				}

				return handler.call(this, e);
			}
		}

		return function(element, type, handler)
		{
			if (type == 'mouseenter')
			{
				type = 'mouseover';
				handler = checkMouseLeaveOrEnter(element, handler);
			}
			else if (type == 'mouseleave')
			{
				type = 'mouseout';
				handler = checkMouseLeaveOrEnter(element, handler);
			}

			element.addEventListener(type, handler, false);
		}
	}
	else
	{
		function handleEvent(event)
		{
			event = event || fixEvent(window.event);

			// defeat IE resize bug
			if (event.type == 'resize')
			{
				var page = getPageDimensions();
				var currentDimensions = page.innerWidth + 'x' + page.innerHeight;

				if (this.__dimensions && this.__dimensions == currentDimensions)
					return true;

				this.__dimensions = currentDimensions;
			}

			var handlers = this.events[event.type], returnValue;
			for (var i in handlers)
			{
				if (handlers.hasOwnProperty(i) && handlers[i].call(this, event) === false)
					returnValue = false;
			}

			return returnValue;
		}
		function fixEvent(event)
		{
			event.preventDefault = preventDefault;
			event.stopPropagation = stopPropagation;
			event.target = event.srcElement;

			return event;
		}
		function preventDefault() { this.returnValue = false; }
		function stopPropagation() { this.cancelBubble = true; }
		function removeAllEvents()
		{
			while ((cachedEvent = eventCache.pop()))
				removeEvent(cachedEvent.element, cachedEvent.type, cachedEvent.handler);

			// cleanup id-cache
			if (window.idCache)
				window.idCache = null;
		}

		var guid = 1;
		var eventCache = [];

		return function(element, type, handler)
		{
			if (!handler.$$guid) handler.$$guid = guid++;
			if (!element.events) element.events = {};
			if (!element.events[type])
			{
				element.events[type] = {};
				if (element['on' + type]) element.events[type][0] = element['on' + type];
				element['on' + type] = handleEvent;
			}

			element.events[type][handler.$$guid] = handler;

			if (type != 'unload')
			{
				if (!eventCache.length)
					addEvent(window, 'unload', removeAllEvents);

				eventCache.push(
					{
						element: element,
						type: type,
						handler: handler
					}
				);
			}
		}
	}
}();

var removeEvent = function()
{
	if (document.removeEventListener)
	{
		return function(element, type, handler)
		{
			element.removeEventListener(type, handler, false);
		}
	}
	else
	{
		return function(element, type, handler)
		{
			if (element.events && element.events[type] && handler.$$guid)
				delete element.events[type][handler.$$guid];
		}
	}
}();

function getHead()
{
	/*@cc_on
		var bases = document.getElementsByTagName('base');
		if (bases.length && bases[0].childNodes.length)
			return bases[0];
	@*/

	return document.getElementsByTagName('head')[0];
}

function getQueryString(form)
{
	var elements = form.elements, element;
	var qName, qValues, qParts = [];
	var i, j, k, o;
	for (i = 0; i < elements.length; i++)
	{
		element = elements[i];

		if (element.name && !element.disabled)
		{
			qValues = [];

			switch (element.tagName.toLowerCase())
			{
				case 'input':
					k = element.type.toLowerCase();
					if ((k == 'checkbox' || k == 'radio') && !element.checked)
						break;
				case 'textarea':
					qValues.push(element.value);
					break;
				case 'select':
					k = element.options, o = [];
					if (element.multiple)
					{
						for (j = 0; j < k.length; j++)
							if (k[j].selected) o.push(k[j]);
					}
					else
						o.push(k[element.selectedIndex]);

					for (j = 0; j < o.length; j++)
					{
						k = o[j].value;
						if (!k && !('value' in k))
							k = o.text;
						qValues.push(k);
					}

					break;
			}

			if ((k = qValues.length))
			{
				qName = encodeURIComponent(element.name);
				for (j = 0; j < k; j++)
					qParts.push(qName + '=' + encodeURIComponent(qValues[j]));
			}
		}
	}

	return qParts.join('&');
}

function HTMLBuilder(newInstance)
{
	if (this == window)
		return new HTMLBuilder();

	if (HTMLBuilder.instance && !newInstance)
		return HTMLBuilder.instance;

	this.idList = {};
	this.eventHandlers = Set(
		'onblur', 'onchange', 'onclick', 'ondblclick', 'onfocus', 'onkeydown',
		'onkeypress', 'onkeyup', 'onload', 'onmousedown', 'onmousemove', 'onmouseout',
		'onkouseover', 'onmouseup', 'onreset', 'onselect', 'onsubmit', 'onunload'
	);

	if (!newInstance)
		HTMLBuilder.instance = this;

	return this;
}
Object.extend(HTMLBuilder.prototype,
{
	built: function(object)
	{
		this.idList = {};

		return this.builtRecursive(object);
	},
	builtRecursive: function(object)
	{
		var element = null, attribute, i;

		if (object.o)
		{
			element = object.o;
		}
		else if (object.n)
		{
			if (object.n == '#document-fragment')
			{
				element = document.createDocumentFragment();
			}
			else if (object.n == '#text')
			{
				element = document.createTextNode(object.v || '');
			}
			else
			{
				if (object.a && 'name' in object.a)
				{
					try
					{
						element = document.createElement('<' + object.n + ' name=' + object.a['name'] + '>');
						delete object.a['name'];
					}
					catch(e) {}
				}

				if (element || (element = document.createElement(object.n)))
				{
					if (object.a)
					{
						for (attribute in object.a)
						{
							if (object.a[attribute] !== null && object.a.hasOwnProperty(attribute))
							{
								if (	attribute in this.eventHandlers &&
									typeof object.a[attribute] != 'function'
								)
								{
									element[attribute] = new Function(object.a[attribute]);
								}
								else
								{
									if (attribute == 'id')
										this.idList[object.a[attribute]] = element;

									if (attribute == 'style')
										element.style.cssText = object.a['style'];
									else
										element[attribute] = object.a[attribute];
								}
							}
						}
					}

					if (object.c && object.c.length)
					{
						if (	object.n == 'table' &&
							!(object.c[0].n in Set('tbody', 'theader', 'tfooter'))
						)
						{
							element.appendChild(
								this.built(
									{
										n: 'tbody',
										c: object.c
									}
								)
							);
						}
						else
						{
							var childNode;
							for (i = 0; i < object.c.length; i++)
							{
								if (object.c[i] && (childNode = this.builtRecursive(object.c[i])))
									element.appendChild(childNode)
							}
						}
					}

					if (object.t)
					{
						element.appendChild(document.createTextNode(object.t));
					}
				}
			}
		}

		return element;
	},
	getIdList: function()
	{
		return Object.extend({}, this.idList);
	},
	getElementById: function(id)
	{
		return this.idList[id] || null;
	}
});

function Popup(width, closeHandler)
{
	this.width = width;
	this.closeHandler = closeHandler;
	this.element = null;
	this.contentArea = null;
	this.visible = false;

	this.init();
}
Object.extend(Popup.prototype,
{
	init: function()
	{
		preload('popup_close', 'g/if/popup/close_button.gif');
		preload('popup_close_hover', 'g/if/popup/close_button_mouseover.gif');

		this.element = document.createElement('div');
		this.element.className = 'trackerPopup';
		this.element.style.width = this.width + 'px';

		this.element.appendChild(this.createCloseButton());

		this.contentArea = document.createElement('fieldset');
		this.element.appendChild(this.contentArea);

		addEvent(window, 'unload', this.cleanUp.bind(this));
	},
	cleanUp: function()
	{
		this.contentArea = null;
		this.element = null;
	},
	createCloseButton: function()
	{
		var img = HTMLBuilder().built({n:'img',a:{className:'close',title:'sluiten',onclick:this.closeHandler||this.close.bind(this)}});
		imageHoverSwap(img, 'popup_close', 'popup_close_hover');

		return img;
	},
	setContent: function(object)
	{
		while (this.contentArea.hasChildNodes())
			this.contentArea.removeChild(this.contentArea.lastChild);

		if (object)
			this.contentArea.appendChild(object);
	},
	show: function()
	{
		this.element.style.display = 'block';
		this.visible = true;
	},
	close: function()
	{
		this.element.style.display = 'none';
		this.visible = false;
	}
});

function getURLParms(href)
{
	var parms = {};
	var i = href.indexOf('?');
	if (i > -1)
	{
		var get = href.substr(i+1);
		var p1 = get.split('&'), p2;
		i = p1.length;
		while (i--)
		{
			p2 = p1[i].split('=');
			parms[p2[0]] = p2[1];
		}
	}

	return parms;
}

function appendURLParms(url, parms)
{
	var queryString = createQueryString(parms);

	if (queryString)
		queryString = (url.indexOf('?') == -1 ? '?' : '&') + queryString;

	return queryString;
}

function appendDataParms(data, parms)
{
	var queryString = createQueryString(parms);

	if (queryString)
		queryString = (data == '' ? '' : '&') + queryString;

	return queryString;
}

function createQueryString(parms)
{
	var query = [];

	for (var parm in parms)
	{
		if (parms.hasOwnProperty(parm))
			query.push(encodeURIComponent(parm) + '=' + encodeURIComponent(parms[parm]));
	}

	return query.join('&');
}

function getElementsByClassName(className, nodeName, parentElement, callback)
{
	if (!nodeName)
		nodeName = '*';

	if (!parentElement)
		parentElement = document;

	var results = [], regexp = /[.|+?()[\]]/.test(className), s, i = 0, element;

	if (parentElement.getElementsByClassName && nodeName == '*' && !regexp)
	{
		// convert to static array
		results = Array.slice(parentElement.getElementsByClassName(className), 0);

		if (callback)
			results.forEach(callback);
	}
	else if (document.evaluate && !regexp)
	{
		s = document.evaluate(
			".//" + nodeName + "[contains(concat(' ', @class, ' '), ' " + className + " ')]",
			parentElement,
			null,
			XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
			null
		);

		while ((element = s.snapshotItem(i++)))
		{
			results.push(element);
			if (callback)
				callback(element);
		}
	}
	else
	{
		s = parentElement.getElementsByTagName(nodeName);
		var re = getClassRegExp(className), elementClassName;

		while ((element = s[i++]))
		{
			elementClassName = element.className;
			if (	elementClassName.length &&
				(	elementClassName == className ||
					re.test(elementClassName)
				)
			)
			{
				results.push(element);
				if (callback)
					callback(element);
			}
		}
	}

	return results;
}

function is_ignorable(nod)
{
	return ((nod.nodeType == 3 && !/[^\t\n\r ]/.test(nod.data)) || nod.nodeType == 8);
}

function first_child(par, nodeName)
{
	if (par && par.nodeType == 1)
	{
		var res = par.firstChild;
		if (nodeName)
		{
			nodeName = nodeName.toLowerCase();
			do
			{
				if (res.nodeName.toLowerCase() == nodeName)
					return res;
			}
			while ((res = res.nextSibling));
		}
		else
		{
			do
			{
				if (!is_ignorable(res))
					return res;
			}
			while ((res = res.nextSibling));
		}
	}

	return null;
}

function last_child(par, nodeName)
{
	if (par && par.nodeType == 1)
	{
		var res = par.lastChild;
		if (nodeName)
		{
			nodeName = nodeName.toLowerCase();
			do
			{
				if (res.nodeName.toLowerCase() == nodeName)
					return res;
			}
			while ((res = res.previousSibling));
		}
		else
		{
			do
			{
				if (!is_ignorable(res))
					return res;
			}
			while ((res = res.previousSibling));
		}
	}

	return null;
}

function node_after(sib, nodeName)
{
	if (sib)
	{
		if (nodeName)
		{
			nodeName = nodeName.toLowerCase();
			while ((sib = sib.nextSibling))
			{
				if (sib.nodeName.toLowerCase() == nodeName)
					return sib;
			}
		}
		else
		{
			while ((sib = sib.nextSibling))
			{
				if (!is_ignorable(sib))
					return sib;
			}
		}
	}

	return null;
}

function node_before(sib, nodeName)
{
	if (sib)
	{
		if (nodeName)
		{
			nodeName = nodeName.toLowerCase();
			while ((sib = sib.previousSibling))
			{
				if (sib.nodeName.toLowerCase() == nodeName)
					return sib;
			}
		}
		else
		{
			while ((sib = sib.previousSibling))
			{
				if (!is_ignorable(sib))
					return sib;
			}
		}
	}

	return null;
}

function ellipsis(root)
{
	if (ellipsis.__native == undefined)
	{
		ellipsis.__native = true;
		if (document.defaultView && document.defaultView.getComputedStyle)
		{
			var foo = document.createElement('div');
			foo.style.cssText = 'text-overflow:ellipsis;-o-text-overflow:ellipsis';
			if (!foo.style.cssText)
				ellipsis.__native = false;
		}
	}

	if (!ellipsis.__native)
	{
		if (!root)
			getElementsByClassName('ellipsis', null, null, ellipsis_do);
		else
			ellipsis_do(root);
	}
}

function ellipsis_table(tableId)
{
	var productTable = getById(tableId);
	if (productTable)
	{
		// temporary hide rows that have col-spanned cells in order to force the col-widths to only observe non-spanned content
		// FIXME: doesn't work properly in IE and is quite intrusive
		var hasColSpans = false;
		if (!is.ie && !is.khtml)
		{
			Array.forEach(
				productTable.getElementsByTagName('td'),
				function(td)
				{
					if(td.colSpan && td.colSpan > 1)
					{
						hasColSpans = true;
						td.parentNode.style.display = 'none';
					}
				}
			);
		}

		var cols = productTable.getElementsByTagName('col');
		if (cols)
		{
			var totalWidth = 0, col, i = 0, ellipsisCol = null, clientWidth;
			while ((col = cols[i++]))
			{
				if (col.getAttribute('rel') == 'ellipsis')
				{
					ellipsisCol = col;
				}
				else if ((clientWidth = col.clientWidth))
				{
					if (!col.width)
						col.width = clientWidth;

					totalWidth += parseInt(col.width, 10);
				}
			}

			if (ellipsisCol && totalWidth > 0)
				ellipsisCol.width = productTable.parentNode.clientWidth - totalWidth;
		}

		if (hasColSpans)
		{
			Array.forEach(
				productTable.getElementsByTagName('td'),
				function(td)
				{
					if(td.colSpan && td.colSpan > 1)
						td.parentNode.style.display = '';
				}
			);
		}

		// when it still doesn't fit....
		var diff = productTable.clientWidth - productTable.parentNode.clientWidth + 4;
		if (diff > 0)
		{
			var tdwidth = [], colspan;
			Array.forEach(
				getElementsByClassName('ellipsis', 'td', productTable),
				function(td)
				{
					colspan = td.colSpan || 1;
					if (!(colspan in tdwidth))
						tdwidth[colspan] = td.clientWidth - diff - 8;

					if (tdwidth[colspan] > 0)
					{
						var a = first_child(td, 'a');
						if (a)
							a.style.width = tdwidth[colspan] + 'px';
					}
				}
			);
		}
	}
}

function ellipsis_do(root)
{
	var ellipsis_word = false;

	// speed things up
	if (root.clientWidth)
	{
		if (root.nodeName != 'TD')
		{
			root.style.width = root.clientWidth + 'px';
			root.style.position = 'fixed';
		}

		var s = [root], e, o, w;

		while ((e = s.pop()))
		{
			do
			{
				switch (e.nodeType)
				{
					case 1:
						if (e.style.display != 'none')
						{
							if (document.defaultView.getComputedStyle(e, null).getPropertyValue('overflow') == 'hidden')
							{
								ellipsis_overflow(e, ellipsis_word);
							}
							else
							{
								if ((o = e.nextSibling)) s.push(o);
								e = e.firstChild;
								break;
							}
						}

					default:
						e = e.nextSibling;
				}
			}
			while (e);
		}

		root.style.position = '';
	}
}

function ellipsis_overflow(p, ellipsis_word)
{
	var w = p.clientWidth;
	if (w && p.scrollWidth > w)
	{
		var s = [p], e, o, q, l;

		while ((e = s.pop()))
		{
			do
			{
				switch (e.nodeType)
				{
					case 1:
						if ((o = e.previousSibling)) s.push(o);
						e = e.lastChild;
						break;

					case 3:
						if (/[^\t\n\r ]/.test(e.data))
						{
							// Take an educated guess on what the length of the text should be
							q = e.nodeValue;
							l = Math.floor((q.length * w) / p.scrollWidth) - 1;
							if (l > 0)
							{
								do
								{
									e.nodeValue = q.substr(0, --l) + '...';
								}
								while (l && (p.scrollWidth > w || (ellipsis_word && e.nodeValue.charAt(l-1) != ' ')));

								if (l > 0) return;
							}

							e.nodeValue = '';
						}

					default:
						e = e.previousSibling;
				}
			}
			while(e);
		}
	}
}

function addClass(element, className)
{
	if (element.className.length)
	{
		var classes = getClassList(element);
		if (classes.indexOf(className) == -1)
		{
			classes.push(className);
			setClassList(element, classes);
		}
	}
	else
		element.className = className;
}

function removeClass(element, className)
{
	var classes = getClassList(element), index;
	if ((index = classes.indexOf(className)) > -1)
	{
		delete classes[index];
		setClassList(element, classes);
	}
}

function replaceClass(element, oldclass, newclass)
{
	var classes = getClassList(element), index;
	if ((index = classes.indexOf(oldclass)) > -1 && classes.indexOf(newclass) == -1)
	{
		classes[index] = newclass;
		setClassList(element, classes);
	}
}

function hasClass(element, className)
{
	var elementClassName = element.className;
	return	elementClassName.length &&
		(	elementClassName == className ||
			getClassRegExp(className).test(elementClassName)
		);
}

function getClassList(element)
{
	return element.className.length ? element.className.split(/\s+/) : [];
}

function setClassList(element, classes)
{
	element.className = classes.join(' ');
}

var regExpCache = {};
function getClassRegExp(className)
{
	if (!(className in regExpCache))
		regExpCache[className] = new RegExp('(^|\\s)' + className + '(\\s|$)');

	return regExpCache[className];
}

function getOffsetTop(el, offsetParent)
{
	var offsetTop = 0;
	if (!offsetParent) offsetParent = null;
	do
	{
		offsetTop += el.offsetTop
	}
	while ((el = el.offsetParent) && el != offsetParent);

	return offsetTop;
}

function getOffsetLeft(el, offsetParent)
{
	var offsetLeft = 0;
	if (!offsetParent) offsetParent = null;
	do
	{
		offsetLeft += el.offsetLeft
	}
	while ((el = el.offsetParent) && el != offsetParent);

	return offsetLeft;
}

function setRelativePosition(element, offsetElement, offsetTop, offsetLeft, minTop, minLeft)
{
	var offsetParent = null;
	try { offsetParent = element.offsetParent; } catch(e) {}

	var top = getOffsetTop(offsetElement, offsetParent) + offsetTop;
	if (minTop !== undefined && top + (offsetParent && getOffsetTop(offsetParent)) < minTop) top = minTop;

	var left = getOffsetLeft(offsetElement, offsetParent) + offsetLeft;
	if (minLeft !== undefined && left + (offsetParent && getOffsetLeft(offsetParent)) < minLeft) left = minLeft;

	element.style.top = top + 'px';
	element.style.left = left + 'px';
}

function getPageDimensions()
{
	var dE = document.documentElement || document.body;

	return {
		scrollWidth: Math.max(dE.scrollWidth, dE.clientWidth),
		scrollHeight: Math.max(dE.scrollHeight, dE.clientHeight),
		innerWidth: window.innerWidth || (dE.offsetWidth - 2 * (dE.clientLeft || 0)),
		innerHeight: window.innerHeight || (dE.offsetHeight - 2 * (dE.clientTop || 0)),
		availWidth: dE.clientWidth,
		availHeight: dE.clientHeight,
		offsetX: window.pageXOffset || dE.scrollLeft,
		offsetY: window.pageYOffset || dE.scrollTop
	};
}

function addLinkBehaviour(root)
{
	if (!root)
		root = document;

	var externalLinks = window.externalLinks == undefined ? 1 : window.externalLinks;

	var c = root.getElementsByTagName('a'), a, i = 0, attr, match;
	var external = getClassRegExp('external');
	var imageViewer = getClassRegExp('imageviewer(\\[(\\w+)\\])?');
	while ((a = c[i++]))
	{
		if ((attr = a.getAttribute('rel')))
		{
			if (externalLinks && (attr == 'external' || external.test(attr)))
				a.target = '_blank';
			if (window.ImageViewer && (attr == 'imageviewer' || (match = imageViewer.exec(attr))) && is.handheld == false)
				ImageViewer().addImage(
					attr == 'imageviewer' ? 'single' : match[3],
					{
						anchor: a,
						src: a.href,
						thumbsrc: first_child(a, 'img').src,
						caption: a.title
					}
				);
		}
	}

	return true;
}

function FolderTree(id)
{
	var list = getById(id);
	if (list)
	{
		preload('foldertree_open', 'g/if/icons/folder_tree_min.gif');
		preload('foldertree_closed', 'g/if/icons/folder_tree_plus.gif');

		var subLists = list.getElementsByTagName('ul'), i = 0, ul, img, li;
		while ((ul = subLists[i++]))
		{
			if ((img = first_child(ul.parentNode, 'img')))
			{
				img.src = getPreloadImage('foldertree_closed');
				img.style.cursor = 'pointer';
				addEvent(img, 'click', FolderTreeToggle);
			}

			ul.style.display = 'none';
		}

		subLists = getElementsByClassName('highlight', 'li', list), i = 0;
		while ((li = subLists[i++]))
		{
			do
			{
				if ((img = first_child(li, 'img')))
					FolderTreeToggle.call(img);

				li = li.parentNode.parentNode;
			}
			while (li && li.nodeName.toLowerCase() == 'li');
		}
	}
}

function FolderTreeToggle()
{
	var subList = first_child(this.parentNode, 'ul');
	if (subList)
	{
		if (subList.style.display == 'none')
		{
			subList.style.display = 'block';
			this.src = getPreloadImage('foldertree_open');
			if (!this.ellipsed)
			{
				ellipsis(subList);
				this.ellipsed = true;
			}
		}
		else
		{
			subList.style.display = 'none';
			this.src = getPreloadImage('foldertree_closed');
		}
	}
}

// Generic Cookie functies
function getCookie(name)
{
	var cookie = document.cookie.split('; '), i = cookie.length, crumb;
	while (i--)
	{
 		crumb = cookie[i].split('=');
		if (crumb[0] == name)
			return crumb[1] != undefined ? unescape(crumb[1]) : null;
	}

	return null;
}

function setCookie(sName, sValue, sPath)
{
	if(!sPath)
		sPath = '/'; 
		
	document.cookie = sName + '=' + escape(sValue) + '; expires=Fri, 31 Dec 2099 23:59:59 GMT; path=' + sPath + '; domain=.' + document.domain;
}

function deleteCookie(sName, sPath)
{
	if(!sPath)
		sPath = '/'; 
		
	document.cookie = sName + '= ; expires=Fri, 1 Jan 1970 0:00:00 GMT; path=' + sPath + '; domain=.' + document.domain;
}

function updateCookieFromSelect(cookie, select)
{
	if(select.value)
		setCookie(cookie, select.value);
	else
		deleteCookie(cookie);
}

function getSessionId()
{
	var sidName = window.sidName || 'TnetId';
	return getCookie(sidName);
}

function timeDiff(starttime)
{
	return ((new Date().getTime()-starttime)/1000).toString().replace('.',',');
}

function hideMed(img, time)
{
	setCookie('lastmed', time);
	img.parentNode.style.display = 'none';
	positionTracker();
}

var klipklapcookie = {}, skipcookie = true;
function initSectionDisplay()
{
	// for pricewatch
	preload('sectionHideIcon', 'g/bullets/min.gif');
	preload('sectionShowIcon', 'g/bullets/plus.gif');

	// for DM notifier
	preload('fieldsetHideIcon', 'g/forum/images/icons/admin_open.gif');
	preload('fieldsetShowIcon', 'g/forum/images/icons/admin_closed.gif');

	// parse cookie
	var c = getCookie('klipklapcookie');
	if (c)
	{
		var temp = c.split(','), i = temp.length;
		while (i--)
			klipklapcookie[temp[i]] = 1;
	}

	// hide sections
	i = 0;
	c = getElementsByClassName('kk', 'img');
	while ((temp = c[i++]))
	{
		addClass(temp, 'pointer');
		temp.title = 'in/uitklappen';

		if (klipklapcookie[temp.id] && typeof temp.onclick == 'function')
			temp.onclick();
	}

	// show sections
	i = 0;
	c = getElementsByClassName('kkRev', 'img');
	while ((temp = c[i++]))
	{
		addClass(temp, 'pointer');
		temp.title = 'in/uitklappen';

		if (!klipklapcookie[temp.id] && typeof temp.onclick == 'function')
			temp.onclick();
	}

	skipcookie = false;
}

function toggleSectionDisplay(img)
{
	var hide = false, cat = getById(img.id + 'List');
	if (cat)
	{
		if (img.src == getPreloadImage('sectionShowIcon'))
		{
			img.src = getPreloadImage('sectionHideIcon');
			cat.style.display = '';
			ellipsis(cat);
		}
		else
		{
			img.src = getPreloadImage('sectionShowIcon');
			cat.style.display = 'none';
			hide = true;
		}

		if (!skipcookie)
			writeKlipKlapCookie(img, hide);
	}
}

function toggleFieldsetDisplay(img, hideall)
{
	var hide = false;

	if (img.src == getPreloadImage('fieldsetShowIcon'))
	{
		img.src = getPreloadImage('fieldsetHideIcon');
	}
	else
	{
		img.src = getPreloadImage('fieldsetShowIcon');
		hide = true;
	}

	var fe = node_after(img.parentNode);
	do
	{
		if (hideall || fe.tagName.toLowerCase() == 'dl' || fe.tagName.toLowerCase() == 'fieldset' || fe.tagName.toLowerCase() == 'table' || fe.tagName.toLowerCase() == 'ol')
			fe.style.display = hide ? 'none' : '';
	}
	while ((fe = node_after(fe)));

	if (!skipcookie)
		writeKlipKlapCookie(img, hide);
}

function writeKlipKlapCookie(img, hide)
{
	if (img)
	{
		if (hasClass(img, 'kkRev')) hide = !hide;

		if (hide)
			klipklapcookie[img.id] = 1;
		else
			delete klipklapcookie[img.id];
	}

	var temp = [];
	for (var category in klipklapcookie)
		if (klipklapcookie.hasOwnProperty(category))
			temp.push(category);

	setCookie('klipklapcookie', temp.join(','));

	// any toggle operation may cause the page height to change
	if (window.Tracker)
	{
		positionTracker();
		utracker_stretch();
	}
}

// AJAX
function getXmlHttpUrl(application, type, action, queryStringExtras)
{
	var xmlHttpUrl = window.xmlHttpUrl || window.BaseURL + 'xmlhttp/xmlHttp.php';
	var url = xmlHttpUrl + '?application='	+ application
						+ (type ? '&type=' + type : '')
						+ (action ? '&action=' + action : '')
						+ (queryStringExtras ? '&' + queryStringExtras : '');

	return url;
}

if (!window.XMLHttpRequest)
{
	window.XMLHttpRequest = function()
	{
		// http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
		var types = [
			'MSXML2.XMLHTTP.6.0',
			'MSXML2.XMLHTTP.3.0'
		];

		for (var i = 0; i < types.length; i++)
		{
			try
			{
				return new ActiveXObject(types[i]);
			}
			catch(e) {}
		}

		return undefined;
	}
}

function Ajax()
{
	// this is a singleton implementation :)

	if (this == window)
		return new Ajax();

	if (Ajax.instance)
		return Ajax.instance;

	// default options
	this.options = {
		type:		'xml',
		method:		'GET',
		async:		false,
		contentType:	'application/x-www-form-urlencoded',
		encoding:	'ISO-8859-15',
		nocache:	false,
		handler:	null,
		appendSid:	false
	};
	this.requestObjectSync = null;
	this.requestObjectAsync = null;
	this.queue = [];
	this.busy = false;

	return (Ajax.instance = this);
}

Object.extend(Ajax.prototype,
{
	getRequestObject: function(async, forceNewObject)
	{
		var requestObjectName = 'requestObject' + (async ? 'Async' : 'Sync');
		if (this[requestObjectName] === null || forceNewObject)
			this[requestObjectName] = new XMLHttpRequest();

		return this[requestObjectName];
	},
	sendRequest: function(url, options, data)
	{
		options = Object.extend(options || {}, this.options);

		var requestObject = this.getRequestObject(options['async'], is.opera && options['async']);

		if (requestObject)
		{
			if (options['async'] && this.busy)
			{
				this.addToQueue(url, options, data);
			}
			else
			{
				if (options['async'])
					this.busy = true;

				url += appendURLParms(url, { output: options['type'].toLowerCase() });

				if (!options['headers'])
					options['headers'] = {};

				if (options['method'].toUpperCase() == 'POST')
				{
					/* Force "Connection: close" for older Mozilla browsers to work
					 * around a bug where XMLHttpRequest sends an incorrect
					 * Content-length header. See Mozilla Bugzilla #246651.
					*/
					if (requestObject.overrideMimeType && (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
						options['headers']['Connection'] = 'close';

					if (!('Content-Type' in options['headers']))
						options['headers']['Content-Type'] = options.contentType +
							(options.encoding ? '; charset=' + options.encoding : '');

					if (data == undefined) data = '';
					if (options['appendSid'])
						data += appendDataParms(data, { sid: getSessionId() });
				}
				else
				{
					options['method'] = 'GET';
					data = null;

					if (options['nocache'])
					{
						options['headers']['Cache-Control'] = 'no-cache';
						url += appendURLParms(url, { nocache: new Date().getTime() });
					}
				}

				requestObject.open(options['method'].toUpperCase(), url, !!options['async']);

				for (var header in options['headers'])
				{
					if (options['headers'].hasOwnProperty(header))
					{
						requestObject.setRequestHeader(header, options['headers'][header]);
					}
				}

				if (options['async'])
				{
					requestObject.onreadystatechange = this.defaultHandler.bind(this, options);
					requestObject.send(data);
				}
				else
				{
					requestObject.send(data);
					return this.defaultHandler(options);
				}
			}

			return true;
		}

		return false;
	},
	addToQueue: function(url, options, data)
	{
		this.queue.push({url: url, options: options, data: data});
		this.checkQueue();
	},
	checkQueue: function()
	{
		if (!this.busy && this.queue.length)
		{
			var request = this.queue.shift();
			this.sendRequest(request['url'], request['options'], request['data']);
		}
	},
	defaultHandler: function(options)
	{
		var result = null;
		var requestObject = this.getRequestObject(options['async']);

		if (requestObject.readyState == 4)
		{
			if (!requestObject.status || (requestObject.status >= 200 && requestObject.status < 400))
			{
				switch (options['type'].toLowerCase())
				{
					case 'json':
						result = this.parseJSON(requestObject.responseText);
						break;
					case 'xml':
						result = this.validateXML(requestObject);
						break;
					case 'text':
					default:
						result = requestObject.responseText;
				}

				if (options['handler'])
					result = options['handler'](result);
			}

			if (options['async'])
			{
				requestObject.onreadystatechange = function() {}
				this.busy = false;
				this.checkQueue();
			}
		}

		return result;
	},
	validateXML: function(requestObject)
	{
		var xmlDoc = requestObject.responseXML, documentElement = null;

		if (xmlDoc)
			try { documentElement = xmlDoc.documentElement; } catch(e) {}

		if (!documentElement && requestObject.responseText && window.DOMParser)
		{
			var parser = new DOMParser();
			xmlDoc = parser.parseFromString(requestObject.responseText, 'text/xml');
			documentElement = xmlDoc.documentElement;
		}

		if (xmlDoc)
		{
			if (documentElement)
			{
				if (documentElement.tagName == 'parsererror' || documentElement.tagName == 'error')
				{
					if (debug) alert('Error in XML respons:\n' + documentElement.firstChild.nodeValue);
				}
				else
				{
					return xmlDoc;
				}
			}
			else
			{
				if (xmlDoc.parseError)
				{
					if (debug) alert('Error parsing XML respons:\n' + xmlDoc.parseError.reason + '\n' + url);
				}
				else
				{
					if (debug) alert('No valid data in XML respons');
				}
			}
		}
		else
		{
			if (debug) alert('The responseXML object was empty');
		}

		return false;
	},
	parseJSON: function(string)
	{
		try
		{
			return /^("(\\.|[^"\\\n\r])*"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+$/.test(string)
				&& eval('(' + string + ')');
		}
		catch (e) {}

		if (debug) alert('Error parsing JSON respons: ' + string);

		return false;
	},
	stripScripts: function(html)
	{
		return html.replace(/<script[^>]*>([\S\s]*?)<\/script>/gi, '');
	},
	evalScripts: function(html)
	{
		return html.replace(
			/<script[^>]*>([\S\s]*?)<\/script>/gi,
			function()
			{
				var script = arguments[1];
				if (window.execScript)
					window.execScript(script, 'javascript');
				else
					window.eval(script);

				return '';
			}
		);
	}
});

function loadRemoteCategoryList(responseXML)
{
	var categoryRoot = responseXML.documentElement;

	//The (first) categories-element
	return  recurseCategoryList(categoryRoot);
}

function recurseCategoryList(categoryRoot)
{
	var categories = [], category, i = 0;

	if (categoryRoot.tagName == 'categories' && categoryRoot.hasChildNodes())
	{
		while ((category = categoryRoot.childNodes[i]))
		{
			// Get the textnodes <id>, <name>, <categories>(if any)
			categories[i] =
			{
				id:		category.childNodes[0].firstChild.data,
				name:		category.childNodes[1].firstChild.data,
				children:	category.childNodes[2] ? recurseCategoryList(category.childNodes[2]) : null,
				islabel:	category.getAttribute('islabel') == 'true' ? true : false
			}

			i++;
		}
	}

	return categories;
}

var categoryList = [];
function loadCategoryList(action)
{
	if (!action) action = 'pw';

	if (!categoryList[action])
	{
		var url = getXmlHttpUrl('frontpage', 'category', action);
		categoryList[action] = new Ajax().sendRequest(url, {handler:loadRemoteCategoryList});
	}

	return categoryList[action];
}

function loadRemoteCountryFilterList(responseXML)
{
	var listRoot = responseXML.documentElement;

	var filters = [], filter, i = 0;

	if (listRoot.tagName == 'countryFilterList' && listRoot.hasChildNodes())
	{
		while((filter = listRoot.childNodes[i]))
		{
			// Get the textnodes <id>, <name>, <categories>(if any)
			filters[i] =
			{
				id:	filter.childNodes[0].firstChild.data,
				name:	filter.childNodes[1].firstChild.data
			}

			i++;
		}
	}

	return filters;
}

var countryFilterList = null;
function loadCountryFilterList()
{
	if(!countryFilterList)
	{
		var url = getXmlHttpUrl('frontpage', 'countryFilterList');
		countryFilterList = new Ajax().sendRequest(url, {handler:loadRemoteCountryFilterList});
	}

	return countryFilterList;
}

var productIdNameCache = [];
function findProductForId(id)
{
	if (!productIdNameCache[id])
	{
		// <products>
		var url = getXmlHttpUrl('frontpage', 'product', 'id', 'id=' + encodeURIComponent(id));
		productIdNameCache[id] = new Ajax().sendRequest(url, {handler:processProductList});
	}

	return productIdNameCache[id];
}

function processProductList(responseXML)
{
	var productListRoot = responseXML.documentElement;
	var productList = [], product, i = 0;
	while ((product = productListRoot.childNodes[i]))
	{
		// Get the textnodes <id>, <name>
		productList[i] =
		{
			id:	product.childNodes[0].firstChild.data,
			name:	product.childNodes[1].firstChild.data
		}

		i++;
	}

	return productList;
}

var searchStringCache = [];
function findProductForString(searchString, categoryParentId)
{
	var cacheId = categoryParentId + '-' + searchString;
	if (!searchStringCache[cacheId])
	{
		var url = getXmlHttpUrl('frontpage', 'product', 'name',
					'searchString=' + encodeURIComponent(searchString) + '&categoryParentId=' + encodeURIComponent(categoryParentId));
		searchStringCache[cacheId] = new Ajax().sendRequest(url, {handler:processProductList});
	}

	return searchStringCache[cacheId];
}

//-- function checks a JSON response that consists of an object with a single property
function checkJsonResponse(response)
{
	if (response !== false)
	{
		if ('data' in response)
		{
			return response['data'];
		}

		if ('error' in response)
		{
			alert(response['error']);
			return false;
		}

		if (debug) alert('No valid data received in JSON response');
	}

	return false;
}

// generic cancelEvent
function cancelEvent(e)
{
	if (e.preventDefault)
	{
		e.preventDefault();
	}
	else if (e.cancelBubble != undefined)
	{
		if (e.keyCode) e.keyCode = 0;
		e.returnValue = 0;
		e.cancelBubble = true;
	}

	return false;
}

// sitestat
function sitestat(ns_l)
{
	ns_l+='&amp;ns__t='+(new Date()).getTime();
	var ns_pixelUrl=ns_l;
	var ns_0=document.referrer;
	ns_0=(ns_0.lastIndexOf('/')==ns_0.length-1)?ns_0.substring(ns_0.lastIndexOf('/'),0):ns_0;
	if(ns_0.length>0)ns_l+='&amp;ns_referrer='+escape(ns_0);
	if(document.images)
	{
		var ns_1=new Image();
		ns_1.src=ns_l;
	}
	else
		document.write('<img src="'+ns_l+'" width="1" height="1" alt="">');
}

function logResolution()
{
	var screenWidth = screen.width;
	var screenHeight = screen.height;
	var pageDimensions = getPageDimensions();

	var rand = Math.round(Math.random() * 100000000);
	preload['logResolutionImage'] = new Image();
	preload['logResolutionImage'].src = BaseURL + 'ext/px.dsp?s=resolutionstats&screenWidth=' + screenWidth + '&screenHeight=' + screenHeight + '&windowWidth=' + pageDimensions['innerWidth'] + '&windowHeight=' + pageDimensions['innerHeight'] + '&rand=' + rand;
}

function sendTrackingCommand(section, parameterstring)
{
	var rand = Math.round(Math.random() * 100000000);
	var url = BaseURL + 'ext/px?s=' + section + (parameterstring ? '&' + parameterstring : '') + '&r=' + rand;
	
	var img = new Image();
	img.src = url;
}

function registerClickOut(shopId, shopName, cost, productId, productName, category, location)
{
	var hadTracker = 0;
	if(window.pageTracker)
	{
		var orderId = new Date().getTime() + '_' + shopId + '_' + productId;
		window.pageTracker._addTrans(orderId, shopName, cost);
		window.pageTracker._addItem(orderId, productId, productName, category, cost, 1, location);
		window.pageTracker._trackTrans();
		
		hadTracker = 1;
	}
	
	if(pageviewIdentifier)
		location = pageviewIdentifier;
	
	sendTrackingCommand('pw', 'pid=' + productId + '&sid=' + shopId + '&c=' + cost + '&t=' + hadTracker + '&l=' + location);
}

var openPopups = [];
function PricePopup(tableRow, useEllipsis, parentPopup)
{
	if(parentPopup)
		this.parentPopup = parentPopup;
	
	this.tableRow = tableRow;
	this.element = null;
	this.contentArea = null;
	this.visible = false;
	this.useEllipsis = useEllipsis;
	this.ellipsed = false;
	this.blockHide = false;
	this.timer = null;

	this.init();
}
Object.extend(PricePopup.prototype,
{
	init: function()
	{
		preload('pricePopupClose', 'g/balloon/pricepopup/close_button.gif');
		preload('pricePopupCloseHover', 'g/balloon/pricepopup/close_button_mouseover.gif');

		this.element = document.createElement('div');
		this.element.className = 'pricePopup';
		this.element.style.width = '350px';

		var pointer = document.createElement('div');
		pointer.className = 'pointerTopRight';
		this.element.appendChild(pointer);

		this.element.appendChild(this.createCloseButton());
		this.contentArea = document.createElement('fieldset');
		this.contentArea.style.width = '310px';
		this.element.appendChild(this.contentArea);

		document.body.appendChild(this.element);

		addEvent(this.element, 'mouseenter', this.block.bind(this));
		addEvent(this.element, 'mouseleave', this.unblock.bind(this));

		addEvent(window, 'unload', this.cleanUp.bind(this));
	},
	setContent: function(newContent)
	{
		this.contentArea.innerHTML = newContent;
		this.ellipsed = false;
	},
	resetPosition: function(tableRow)
	{
		if(tableRow)
			this.tableRow = tableRow;
		
		setRelativePosition(this.element, this.tableRow, this.tableRow.clientHeight + 24, -349, 100, 20);
	},
	cleanUp: function()
	{
		this.tableRow = null;
		this.element = null;
	},
	createCloseButton: function()
	{
		var img = HTMLBuilder().built({n:'img',a:{className:'close',title:'sluiten',onclick:this.close.bind(this, true)}});
		imageHoverSwap(img, 'pricePopupClose', 'pricePopupCloseHover');

		return img;
	},
	showDelayed: function()
	{
		if(!this.visible && !this.timer)
		{
			this.timer = setTimeout(this.show.bind(this), 300);
		}
	},
	show: function()
	{
		if(openPopups.length > 0)
		{
			var openPopup;
			while( (openPopup = openPopups.pop()) )
				openPopup.close();
		}
	
		this.timer = null;

		if(this.parentPopup && this.parentPopup.show)
			this.parentPopup.show();

		this.element.style.display = 'block';
		this.visible = true;
		
		openPopups.push(this);

		if(this.useEllipsis && !this.ellipsed)
		{
			Array.forEach(
				this.contentArea.getElementsByTagName('table'),
				function(table)
				{
					addClass(table, 'ellipsis');
					ellipsis(table);
				}
			);

			this.ellipsed = true;
		}
	},
	close: function(forceClose)
	{
		if(!this.blockHide || forceClose)
		{
			this.element.style.display = 'none';
			this.visible = false;
			if(this.timer)
				clearTimeout(this.timer);
			this.timer = null;
		}
	},
	hideDelayed: function(timeout)
	{
		// There is a timer running to display this item, cancel it
		if(this.timer && !this.visible)
		{
			this.close(true);
		}
		else if (this.visible)
		{
			if(!timeout)
				timeout = 1000;
				
			if(!this.blockHide && !this.timer)
				this.timer = setTimeout(this.close.bind(this), timeout);
		}
	},
	block: function()
	{
		if(this.timer)
		{
			clearTimeout(this.timer);
			this.timer = null;
		}
		this.blockHide = true;
	},
	unblock: function()
	{
		this.blockHide = false;
		this.hideDelayed(5000);
	}
});

function LowestPricePopup(productId, tableRow)
{
	this.popup = null;
	this.productId = productId;
	this.dataRequested = false;

	this.init(tableRow);
}
Object.extend(LowestPricePopup.prototype,
{
	init: function(tableRow)
	{
		this.popup = new PricePopup(tableRow, true, this);	
	},
	show: function()
	{
		if(!this.dataRequested)
		{
			this.dataRequested = true;
			
			var ajax = new Ajax();
			if(ajax.getRequestObject(true))
			{
				// FIXME: Add some Ajax-info here
				var tabledata = ajax.sendRequest(
									getXmlHttpUrl('frontpage', 'productprices', 'top5') + '&productId=' + this.productId,
									{
										method: 'GET',
										type: 'text',
										async: false,
										appendSid: true
									});
				
				this.popup.setContent(tabledata);
				this.popup.resetPosition();
			}
		}
	},
	showDelayed: function()
	{
		this.popup.showDelayed();
	},
	hideDelayed: function()
	{
		this.popup.hideDelayed();
	}
});

function displayLowestPrices(row, productId)
{
	if(!row.popup)
		row.popup = new LowestPricePopup(productId, row);
	
	row.popup.showDelayed();
}

function hideLowestPrices(row)
{
	row.popup.hideDelayed();
}

/* Google AdSense */
var current_adsense_position = '';
function create_google_advertorial(id, adsenseData)
{
	if (window.tnet_google_ad_client && adsenseData)
	{
		current_adsense_position = id;

		document.write("<script type='text/javascript'>"
			+ "var google_page_url=adsense_page_url,google_language='nl',"
			+ "google_ad_client='" + window.tnet_google_ad_client + "',"
			+ ('slot' in adsenseData ? "google_ad_slot='" + adsenseData['slot'] + "'," : "google_ad_type='text',google_ad_channel='" + adsenseData['channel'] + "',")
			+ (window.dblc_zone && window.dblc_zone == 'test' ? "google_adtest='on'," : "")
			+ "google_ad_output='js',google_max_num_ads='" + adsenseData['numads'] + "';<\/script>"
			+ "<script type='text/javascript' src='http://pagead2.googlesyndication.com/pagead/show_ads.js'><\/script>");
	}
	else
	{
		getById(id).style.display = 'none';
	}
}


// Allow for multiple sections with different functions to wrap the advertisements
function google_ad_request_done(google_ads)
{
	var el = current_adsense_position && getById(current_adsense_position), l;

	if (!el) return false;

	if ((l = google_ads.length) == 0)
	{
		el.style.display = 'none';
		return false;
	}

	var feedbackurl = 'http://services.google.com/feedback/abg?url=' + encodeURIComponent(adsense_page_url) + '&hl=nl&client='+google_ad_client;
	var s = ['<div class="textadContainer"><div class="textadBg"><div class="textadTop"><small><a href="' + feedbackurl + '" class="adsensefburl">Ads door Google</a></small></div>'], i = 0, google_ad;

	if (!window.defaultStatus) window.defaultStatus = '';

	var width = current_adsense_position in Set('b_re', 'as_rectangle') ? 100 : Math.floor(100 / l);

	while ((google_ad = google_ads[i++]))
	{
		feedbackurl += '&adU='+google_ad.visible_url+'&adT='+encodeURIComponent(google_ad.line1).replace(/%20/g, '+');

		/*@cc_on
			google_ad.line1 = IE_EuroFix(google_ad.line1);
			google_ad.line2 = IE_EuroFix(google_ad.line2);
			google_ad.line3 = IE_EuroFix(google_ad.line3);
		@*/

		s.push(
			(l > 1 ? '<div class="textadColumn" style="width:' + width + '%">' : '')
			+ '<div class="textadContent">'
			+ '<h4><a href="' + google_ad.url + '" onmouseover="window.status=\'ga naar ' + google_ad.visible_url + '\';return true" onmouseout="window.status=window.defaultStatus;return true">' + google_ad.line1 + '</a></h4>'
			+ '<a href="' + google_ad.url + '" onmouseover="window.status=\'ga naar ' + google_ad.visible_url + '\';return true" onmouseout="window.status=window.defaultStatus;return true">'
			+ google_ad.line2 + (google_ad.line3 ? ' ' + google_ad.line3 : '')
			+ ' <span class="url">' + google_ad.visible_url + '</span>'
			+ '</a></div>'
			+ (l > 1 ? '</div>' : '')
		);
	}

	s.push('<div class="textadBottom"><div class="hr"><hr></div></div></div></div>');

	el.innerHTML = s.join('');
	el.style.height = 'auto';
	el.style.display = 'block';

	return true;
}

function IE_EuroFix(text)
{
	for (var i = 0, replaced = ''; i < text.length; i++)
	{
		switch (text.charCodeAt(i))
		{
			case 128:
				replaced += '&euro;';
				break;
			case 381:
				replaced += '&acute;';
				break;
			default:
				replaced += text.charAt(i);
		}
	}

	return replaced;
}