function resizeHandler()
{
	if (!is.handheld)
	{
		var page = getById('page');
		if (page)
		{
			// check if this is first call
			if (!resizeHandler.initialized)
			{
				resizeHandler.initialized = true;
				addEvent(window, 'resize', resizeHandler);
			}

			var pageDim = getPageDimensions();

			if (hasClass(page, 'notracker'))
			{
				page.style.width = pageDim.availWidth < 966 ? 'auto' : '966px';
			}
			else if (hasClass(page, 'trackerright'))
			{
				page.style.width = pageDim.availWidth < 1109 ? '882px' : pageDim.availWidth < 1193 ? 'auto' : '966px';
			}
			else
			{
				page.style.width = pageDim.availWidth < 1208 ? 'auto' : '1208px';

				var className = '';
				if (pageDim.availWidth < 1064)
					className = 'res1024';
				else if (pageDim.availWidth < 1114)
					className = 'res1100';
				else if (pageDim.availWidth < 1138)
					className = 'res1152';

				if (page.className != className)
					page.className = className;
			}

			// preload logo hoverimage; determine GoT by presence of board_script_url
			var logo = 'logo' + (window.board_script_url ? '_got' : '') + (page.className in Set('res1024', 'notracker', 'trackerright') ? '_narrow' : '');
			preload(logo, 'g/if/v2/header/' + logo + '_mouseover.gif');
		}
	}
}

function SiteMenu(activeMenu)
{
	this.element = getById('siteMenu');
	this.menuItems = [];
	this.activeMenu = activeMenu;
	this.menuActive = false;
	this.menuItemTimeout = null;
	this.menuTimeout = null;
	this.init();

	SiteMenu.instance = this;
}

Object.extend(SiteMenu.prototype,
{
	init: function()
	{
		if (this.element)
		{
			var menuItems = this.element.getElementsByTagName('li'), menuItem, i = 0;
			// We skip the first item sice it's the bypass link
			while ((menuItem = menuItems[++i]))
			{
				addEvent(menuItem, 'click', this.onClick.bind(this, i));
				addEvent(menuItem, 'mouseover', this.onMouseover.bind(this, i));
				menuItem.subMenu = new SubMenu(i, menuItem.offsetLeft);
				this.menuItems[i] = menuItem;
			}

			var header = getById('header');
			if (header)
			{
				// complete reset only when leaving header area
				addEvent(header, 'mouseover', this.cancelMouseout.bind(this));
				addEvent(header, 'mouseout', this.onMouseout.bind(this, this.activeMenu));
			}

			addEvent(window, 'unload', this.cleanUp.bind(this));
		}
	},
	positionSubMenus: function()
	{
		var i = 0, menuItem;
		while ((menuItem = this.menuItems[++i]))
		{
			if (menuItem.subMenu.element)
				menuItem.subMenu.position();
		}
	},
	cleanUp: function()
	{
		this.menuActive = false;
		this.menuItems = null;
		this.element = null;
	},
	onClick: function(i)
	{
		clearTimeout(this.menuItemTimeout);
		this.menuActive = true;
		this.handleMouseover(i);
	},
	onMouseover: function(i, e)
	{
		clearTimeout(this.menuItemTimeout);
		if (i != this.activeMenu)
		{
			var timeOut = 250;

			if (this.menuActive)
			{
				var target = e.target || e.srcElement;

				if (target.nodeType == 3)
					target = target.parentNode;

				timeOut = target.nodeName == 'A' ? 50 : 100;
			}

			this.menuItemTimeout = setTimeout(this.onClick.bind(this, i), timeOut);
		}
	},
	onMouseout: function(i)
	{
		clearTimeout(this.menuTimeout);
		clearTimeout(this.menuItemTimeout);
		this.menuTimeout = setTimeout(this.handleMouseout.bind(this, i), 5000);
	},
	cancelMouseout: function()
	{
		clearTimeout(this.menuTimeout);
	},
	handleMouseover: function(i)
	{
		var menu;

		if (this.menuActive && this.menuItems && i != this.activeMenu)
		{
			if ((menu = this.menuItems[this.activeMenu]))
			{
				removeClass(menu, 'active');
				if (menu.subMenu.element)
				{
					menu.subMenu.handleMouseout();
					removeClass(menu.subMenu.element, 'active');
				}
				if ((menu = this.menuItems[this.activeMenu+1]))
					removeClass(menu, 'activeNeighbor');
			}

			this.activeMenu = i;

			if ((menu = this.menuItems[this.activeMenu]))
			{
				addClass(menu, 'active');
				if (menu.subMenu.element)
					addClass(menu.subMenu.element, 'active');
				if ((menu = this.menuItems[this.activeMenu+1]))
					addClass(menu, 'activeNeighbor');
			}
		}
	},
	handleMouseout: function(i)
	{
		this.handleMouseover(i);
		this.menuActive = false;
	}
});

function SubMenu(id, offset)
{
	this.element = getById('groupNav' + id);
	this.menu = null;
	this.offset = offset;
	this.width = 0;
	this.menuItems = [];
	this.activeMenu = -1;
	this.menuActive = false;
	this.menuTimeout = null;
	this.menuItemTimeout = null;
	this.init();
}

Object.extend(SubMenu.prototype,
{
	init: function()
	{
		if (this.element)
		{
			var lastitem, menuitem, menusubitem, i = 0;

			if ((this.menu = first_child(this.element, 'ul')))
			{
				menuitem = first_child(this.menu, 'li');
				
				if (menuitem)
				{
					do
					{
						lastitem = menuitem;

						if ((menusubitem = first_child(menuitem, 'div')))
						{
							menuitem.className += 'subitems';
							addEvent(menuitem, 'click', this.onClick.bind(this, i));
							addEvent(menuitem, 'mouseover', this.onMouseover.bind(this, i));

							this.menuItems[i++] = menusubitem;
						}
						else
						{
							addEvent(menuitem, 'mouseover', this.handleMouseover.bind(this, -1));
						}
					}
					while ((menuitem = node_after(menuitem, 'li')));

					this.width = lastitem.offsetLeft;
					this.position();
				}
			}

			addEvent(this.element, 'mouseover', this.cancelMouseout.bind(this));
			addEvent(this.element, 'mouseout', this.onMouseout.bind(this));

			menuitem = null, menusubitem = null;
			addEvent(window, 'unload', this.cleanUp.bind(this));
		}
	},
	cleanUp: function()
	{
		this.menuActive = false;
		this.menuItems = null;
		this.menu = null;
		this.element = null;
	},
	position: function()
	{
		if (this.width)
		{
			var maxLeft = this.element.parentNode.offsetWidth - 10;
			var searchbox = getById('searchbox');
			if (searchbox)
				maxLeft = searchbox.offsetLeft - 10;

			// here we try to 'center' the submenu belof the maintab
			var offset = this.offset - Math.floor(this.width / 2);
			offset += 65; // half of the maintab width plus 9 (fast shortcut)

			// limiter
			if (offset + this.width > maxLeft) offset = maxLeft - this.width;
			if (offset < 0) offset = 0;

			this.element.style.left = offset + 'px';
		}
	},
	onClick: function(i)
	{
		clearTimeout(this.menuItemTimeout);
		this.menuActive = true;
		this.handleMouseover(i);
	},
	onMouseover: function(i)
	{
		clearTimeout(this.menuItemTimeout);
		if (this.menuActive)
			this.handleMouseover(i);
		else if (i != this.activeMenu)
			this.menuItemTimeout = setTimeout(this.onClick.bind(this, i), 50);
	},
	onMouseout: function(i)
	{
		clearTimeout(this.menuTimeout);
		clearTimeout(this.menuItemTimeout);
		this.menuTimeout = setTimeout(this.handleMouseout.bind(this), 1000);
	},
	cancelMouseout: function()
	{
		clearTimeout(this.menuTimeout);
	},
	handleMouseover: function(i)
	{
		if (this.menuItems && i != this.activeMenu)
		{
			var menu = this.menuItems[this.activeMenu]
			if (menu)
				menu.style.display = 'none';

			this.activeMenu = i;
			if ((menu = this.menuItems[this.activeMenu]))
			{
				menu.style.left = menu.parentNode.offsetLeft + 'px';
				menu.style.display = 'block';
			}
		}
	},
	handleMouseout: function()
	{
		this.handleMouseover(-1);
		this.menuActive = false;
	}
});

function Tab(id)
{
	this.element = getById(id);
	this.tabItems = [];
	this.tablistItems = [];
	this.activeTab = 1;
	this.toggleTimer = null;
	this.activeCallback = null;
	this.init();
}

Object.extend(Tab.prototype,
{
	init: function()
	{
		if (this.element)
		{
			var ul = document.createElement('ul'), li, a;
			var tab = this.element.firstChild, i = 1;
			while (tab)
			{
				if (tab.nodeType == 1)
				{
					this.tabItems[i] = tab;

					li = document.createElement('li');
					a = document.createElement('a');
					a.setAttribute('href', window.location.href + '#' + tab.id);
					a.appendChild(document.createTextNode(i));
					addEvent(a, 'click', function(e) { e.preventDefault(); });
					addEvent(a, 'mouseover', this.setActive.bind(this, i, true));
					li.appendChild(a);

					if (i != this.activeTab)
					{
						tab.style.display = 'none';
					}
					else
					{
						addClass(li, 'active');
					}

					this.tablistItems[i] = li;
					ul.appendChild(li);

					i++;
				}

				tab = tab.nextSibling;
			}

			this.element.insertBefore(ul, this.element.firstChild);

			addEvent(this.element, 'mouseout', this.startToggle.bind(this));
			addEvent(this.element, 'mouseover', this.stopToggle.bind(this));
			this.startToggle();

			addEvent(window, 'unload', this.cleanUp.bind(this));
		}
	},
	cleanUp: function()
	{
		this.stopToggle();
		this.tablistItems = null;
		this.tabItems = null;
		this.element = null;
		this.activeCallback = null;
	},
	setActive: function(i, doCallback, e)
	{
		if (i != this.activeTab)
		{
			if (this.activeTab)
			{
				this.tabItems[this.activeTab].style.display = 'none';
				removeClass(this.tablistItems[this.activeTab], 'active');
			}

			this.activeTab = i;
			this.tabItems[this.activeTab].style.display = '';
			addClass(this.tablistItems[this.activeTab], 'active');

			if (this.activeCallback && doCallback)
				this.activeCallback(i, false);
		}

		if (e) e.preventDefault();
	},
	toggle: function()
	{
		var i = this.activeTab + 1;
		if (!this.tabItems[i]) i = 1;

		this.setActive(i, true);
		this.startToggle();
	},
	startToggle: function()
	{
		this.stopToggle();
		this.toggleTimer = setTimeout(this.toggle.bind(this), Math.round(40000 / (this.activeTab + 1)));
	},
	stopToggle: function()
	{
		if (this.toggleTimer)
		{
			clearTimeout(this.toggleTimer);
			this.toggleTimer = null;
		}
	}
});

function SuperTab(id)
{
	this.tab = new Tab(id);

	this.tabList = getById(id + 'List');
	this.tablistItems = [];
	this.activeItem = 0;
	this.timer = null;

	this.init();
}

Object.extend(SuperTab.prototype,
{
	init: function()
	{
		if (this.tabList)
		{
			var listItems = this.tabList.getElementsByTagName('li'), li, i = 0;
			while ((li = listItems[i++]))
			{
				if (this.tab.tabItems[i])
				{
					addEvent(li, 'mouseover', this.showDelayed.bind(this, i, true));
					addEvent(li, 'mouseout', this.clearTimer.bind(this, true));
					this.tablistItems[i] = li;
				}
			}

			this.tab.activeCallback = this.setActive.bind(this);
			this.setActive(this.tab.activeTab, false);
		}

		addEvent(window, 'unload', this.cleanUp.bind(this));
	},
	cleanUp: function()
	{
		this.tab = null
		this.tabList = null;
		this.tablistItems = null;
	},
	setActive: function(i, doCallback)
	{
		if (i != this.activeItem)
		{
			if (this.activeItem)
				removeClass(this.tablistItems[this.activeItem], 'active');

			this.activeItem = i;
			addClass(this.tablistItems[this.activeItem], 'active');

			if (doCallback)
			{
				this.tab.setActive(i, false);
				this.tab.stopToggle();
			}
		}
	},
	showDelayed: function(i, bool)
	{
		this.clearTimer();
		this.timer = setTimeout(this.setActive.bind(this, i, bool), 300);
	},
	clearTimer: function(startToggle)
	{
		if (this.timer)
		{
			clearTimeout(this.timer);
			this.timer = null;

			if (startToggle && !this.tab.toggleTimer)
				this.tab.startToggle();
		}
	}
});

function RefreshTimer()
{
	if (this == window)
		return new RefreshTimer();

	if (RefreshTimer.instance)
		return RefreshTimer.instance;

	this.refreshTimerTimer = null;

	this.counter = 0;
	this.lastActivity = 0;
	this.refreshes = {};
	this.inactiveTrigger = 10;
	this.paused = false;
	this.suspended = false;

	return (RefreshTimer.instance = this);
}
Object.extend(RefreshTimer.prototype,
{
	add: function(label, callback, interval)
	{
		this.refreshes[label] = {
			callback: callback,
			interval: interval,
			execute: this.counter + interval
		};

		if (this.refreshTimerTimer == null)
		{
			addEvent(window, 'mousemove', this.stayActive.bind(this));
			addEvent(window, 'focus', this.stayActive.bind(this));
			addEvent(window, 'unload', this.cleanUp.bind(this));

			this.start();
		}
	},
	cleanUp: function()
	{
		if (this.refreshTimerTimer)
			clearTimeout(this.refreshTimerTimer);

		this.refreshes = {};
	},
	stayActive: function()
	{
		this.lastActivity = this.counter;

		// resume timers when there is no timer
		if (this.suspended && !this.paused)
			this.resume();
	},
	start: function(timeout)
	{
		if (!timeout) timeout = 60000;

		this.refreshTimerTimer = setTimeout(this.execute.bind(this), timeout);
	},
	suspend: function()
	{
		window.status = 'Suspending timers';
		this.suspended = true;
	},
	pause: function()
	{
		window.status = 'Pausing timers';
		this.paused = true;
	},
	resume: function()
	{
		window.status = 'Resuming timers';
		this.suspended = false;
		this.paused = false;

		if (this.refreshTimerTimer)
			clearTimeout(this.refreshTimerTimer);

		this.start(1000);
	},
	execute: function()
	{
		this.counter++;

		if (!this.paused && !this.suspended)
		{
			// more than so many minutes no activity, so suspend
			if (this.counter - this.lastActivity > this.inactiveTrigger)
			{
				this.counter--;
				this.suspend();
			}
			else
			{
				window.status = '';

				if ('global' in this.refreshes && this.refreshes['global']['execute'] <= this.counter)
				{
					// skip all other refreshes when the global refresh (complete page refresh) kicks in; don't restart timer
					this.refreshes['global']['callback']();
					return;
				}

				for (var refresh in this.refreshes)
				{
					if (this.refreshes[refresh]['execute'] <= this.counter)
					{
						this.refreshes[refresh]['execute'] = this.counter + this.refreshes[refresh]['interval'];
						this.refreshes[refresh]['callback'](this.counter);
					}
				}
			}
		}

		this.start();
	},
	getCounter: function()
	{
		return this.counter;
	}
});

function Tracker(section, settings)
{
	this.ajax = null;
	this.section = section;
	this.settings = settings;
	this.tracker = getById('utracker');
	this.propertyImg = null;
	this.trackerItems = {};
	this.trackerHeadlines = {};
	this.trackerItemConfig = {};
	this.trackerRefreshes = {};
	this.order = [];
	this.drag = null;
	this.dummyItem = null;
	this.updateOrder = false;
	this.timer = null;
	this.sy = 0;
	this.dy = 0;
	this.ph = 0;
	this.nh = 0;
	this.highContrast = 0;
	this.position = 'l';

	this.init();
}

Object.extend(Tracker.prototype,
{
	init: function()
	{
		if (this.tracker)
		{
			// logged in?
			if (this.settings && window.UserID)
			{
				// ajax enabled?
				if ((this.ajax = new Ajax()).getRequestObject(true))
				{
					if ('highContrast' in this.settings)
						this.highContrast = this.settings['highContrast']['config'] || 0;

					if ('position' in this.settings)
						this.position = this.settings['position']['config'] || 'l';

					// preloads
					this.preloadTrackerButtons();

					preload('tracker_settings', 'g/if/v2/tracker/settings.gif');
					preload('tracker_settings_mouseover', 'g/if/v2/tracker/settings_mouseover.gif');
					preload('tracker_contrast', 'g/if/v2/tracker/contrast.gif');
					preload('tracker_contrast_mouseover', 'g/if/v2/tracker/contrast_mouseover.gif');
					preload('tracker_leftright', 'g/if/v2/tracker/leftright.gif');
					preload('tracker_leftright_mouseover', 'g/if/v2/tracker/leftright_mouseover.gif');

					// dummy trackeritem
					this.dummyItem = document.createElement('div');
					this.dummyItem.className = 'dummy';

					addEvent(this.tracker, 'mousemove', this.dragDo.bind(this));
					addEvent(document, 'mouseup', this.dragStop.bind(this));

					var trackerItems = getElementsByClassName('trackeritem', 'div', this.tracker), trackerItem, i = 0;
					var l, trackerId;
					while ((trackerItem = trackerItems[i]))
					{
						trackerId = trackerItem.getAttribute('id'), l = trackerId.lastIndexOf('-') + 1;
						if (l && (trackerId = trackerId.substr(l)))
						{
							this.order.push(trackerId);
							this.trackerItems[trackerId] = trackerItem;
							this.initTrackerItem(trackerId);
						}

						i++;
					}

					// general properties image
					this.propertyImg = document.createElement('img');
					this.propertyImg.title = 'Tracker keuzes';
					this.propertyImg.style.cssText = 'width:16px;height:16px;margin:4px;cursor:pointer';
					imageHoverSwap(this.propertyImg, 'tracker_settings', 'tracker_settings_mouseover');
					addEvent(this.propertyImg, 'click', this.trackerChoices.bind(this));

					this.tracker.appendChild(this.propertyImg);

					// config images
					var configImage;

					if ('highContrast' in this.settings)
					{
						configImage = document.createElement('img');
						configImage.title = 'Contrast';
						configImage.style.cssText = 'width:16px;height:16px;margin:4px;cursor:pointer';
						imageHoverSwap(configImage, 'tracker_contrast', 'tracker_contrast_mouseover');
						addEvent(configImage, 'click', this.toggleContrast.bind(this));

						this.tracker.appendChild(configImage);
					}

					if ('position' in this.settings)
					{
						configImage = document.createElement('img');
						configImage.title = 'Positie';
						configImage.style.cssText = 'width:16px;height:16px;margin:4px;cursor:pointer';
						imageHoverSwap(configImage, 'tracker_leftright', 'tracker_leftright_mouseover');
						addEvent(configImage, 'click', this.togglePosition.bind(this));

						this.tracker.appendChild(configImage);
					}

					configImage = null;

					// start refresh timer
					RefreshTimer().add('trackerRefresh', this.refreshAll.bind(this), 1);
				}
			}

			// position top
			positionTracker();

			addEvent(this.tracker, 'mouseenter', this.foldout.bind(this));
			addEvent(this.tracker, 'mouseleave', this.foldinDelayed.bind(this));

			if (window.DomLoaded)
				DomLoaded.load(utracker_stretch);

			addEvent(window, 'unload', this.cleanUp.bind(this));
		}
	},
	cleanUp: function()
	{
		this.trackerItems = null;
		this.dummyItem = null;
		this.propertyImg = null;
		this.tracker = null;
		this.ajax = null;
	},
	preloadTrackerButtons: function(update)
	{
		var prefix = '';
		if (this.highContrast) prefix += '_hct';
		if (this.position == 'r') prefix += '_right';

		preload('tracker_button', 'g/if/v2/tracker/button' + prefix + '.gif', update);
		preload('tracker_button_mouseover', 'g/if/v2/tracker/button' + prefix + '_mouseover.gif', update);
		preload('tracker_throbber', 'g/if/v2/tracker/timer' + prefix + '_ani.gif', update);

		if (update)
		{
			getElementsByClassName(
				'tracker_button',
				'img',
				this.tracker,
				function(img)
				{
					img.src = getPreloadImage('tracker_button');
				}
			);
		}
	},
	foldout: function()
	{
		this.stopTimer();

		// only when there are actually any trackers
		if (!window.UserID || this.order.length)
			addClass(this.tracker, 'foldout');
	},
	foldinDelayed: function()
	{
		this.stopTimer();

		if (this.trackerChoicePopup && this.trackerChoicePopup.popup.visible)
			return false;

		if (this.trackerPropPopup && this.trackerPropPopup.popup.visible)
			return false;

		this.timer = setTimeout(this.foldin.bind(this), 500);

		return true;
	},
	foldin: function()
	{
		this.stopTimer();

		removeClass(this.tracker, 'foldout');
	},
	stopTimer: function()
	{
		if (this.timer)
		{
			clearTimeout(this.timer);
			this.timer = null;
		}
	},
	initTrackerItem: function(trackerId)
	{
		var header = this.trackerItems[trackerId] && this.trackerItems[trackerId].getElementsByTagName('h4')[0], img, a;
		if (header)
		{
			addClass(header, 'active');
			addEvent(header, 'mousedown', this.dragStart.bind(this, trackerId));
			header.onselectstart = function() { return false; }

			// don't activate when clicking on the anchor
			if ((a = header.getElementsByTagName('a')[0]))
				addEvent(a, 'mousedown', function(e) { e.stopPropagation(); });

			img = document.createElement('img');
			img.style.cursor = 'pointer';
			img.title = 'Eigenschappen';
			img.className = 'tracker_button'; // for easy selecting when swapping images
			imageHoverSwap(img, 'tracker_button', 'tracker_button_mouseover');
			addEvent(img, 'mousedown', function(e) { e.stopPropagation(); });
			addEvent(img, 'click', this.trackerProperties.bind(this, img, trackerId));

			header.appendChild(img);

			this.refreshInit(trackerId);
		}

		header = null, img = null, a = null;
	},
	trackerProperties: function(propImg, trackerId)
	{
		if (this.trackerPropPopup === undefined)
		{
			if ((this.trackerPropPopup = new TrackerPropPopup(this)))
				document.body.appendChild(this.trackerPropPopup.popup.element);
		}

		if (this.trackerPropPopup && this.trackerPropPopup.trackerId != trackerId)
		{
			this.closeAllPopups();

			if (this.trackerPropPopup.initContent(trackerId))
			{
				var posLeft = this.position == 'r' ? -339 : 20;
				setRelativePosition(this.trackerPropPopup.popup.element, propImg, 1, posLeft);

				RefreshTimer().pause();

				this.trackerPropPopup.popup.show();
			}
		}
	},
	trackerChoices: function()
	{
		if (this.trackerChoicePopup === undefined)
		{
			if ((this.trackerChoicePopup = new TrackerChoicePopup(this)))
				document.body.appendChild(this.trackerChoicePopup.popup.element);
		}

		if (this.trackerChoicePopup)
		{
			if (this.trackerChoicePopup.popup.visible)
			{
				this.trackerChoicePopup.closePopup(true);
			}
			else
			{
				this.closeAllPopups();

				if (this.trackerChoicePopup.initContent())
				{
					var posLeft = this.position == 'r' ? -240 : 215;
					setRelativePosition(this.trackerChoicePopup.popup.element, this.propertyImg, -440, posLeft, 100, 0);

					RefreshTimer().pause();

					this.trackerChoicePopup.popup.show();
				}
			}
		}
	},
	closeAllPopups: function()
	{
		if (this.trackerChoicePopup && this.trackerChoicePopup.popup.visible)
		{
			this.trackerChoicePopup.closePopup(true);
		}

		if (this.trackerPropPopup && this.trackerPropPopup.popup.visible)
		{
			this.trackerPropPopup.closePopup(true);
		}
	},
	toggleContrast: function()
	{
		this.closeAllPopups();

		if (hasClass(this.tracker, 'hct'))
		{
			removeClass(this.tracker, 'hct');
			this.highContrast = 0;
		}
		else
		{
			addClass(this.tracker, 'hct');
			this.highContrast = 1;
		}

		// Fix images
		this.preloadTrackerButtons(true);

		// save on server
		this.saveOption('highContrast');
	},
	togglePosition: function()
	{
		this.closeAllPopups();

		var page = getById('page');
		if (page)
		{
			if (hasClass(page, 'trackerright'))
			{
				removeClass(page, 'trackerright');
				this.position = 'l';
			}
			else
			{
				addClass(page, 'trackerright');
				this.position = 'r';
			}

			// Fix images
			this.preloadTrackerButtons(true);

			// woot, that's a lot of fixing
			positionTracker();
			utracker_stretch();
			resizeHandler();
			initChannelNavToggle();
			if (SiteMenu.instance)
				SiteMenu.instance.positionSubMenus();

			// save on server
			this.saveOption('position');
		}
	},
	saveOption: function(option)
	{
		this.ajax.sendRequest(
			getXmlHttpUrl('frontpage', 'tracker', 'set_options'),
			{
				method: 'POST',
				type: 'text',
				async: true,
				appendSid: true
			},
			'section=' + this.section + '&trackerid=' + option + '&options%5Bconfig%5D=' + this[option]
		);
	},
	dragStart: function(trackerId, e)
	{
		e = e || event;

		if (!this.drag)
		{
			this.drag = trackerId;
			var trackerItem = this.trackerItems[trackerId];

			var y = trackerItem.offsetTop;
			addClass(trackerItem, 'dragitem');
			trackerItem.style.top = y + 'px';

			var index = this.order.indexOf(trackerId);
			this.ph = this.getPreviousTracker(index).clientHeight || 0;
			this.nh = this.getNextTracker(index).clientHeight || 0;

			this.dy = y;
			this.sy = y - e.clientY;

			this.dummyItem.style.height = (trackerItem.clientHeight - 2) + 'px';
			trackerItem.parentNode.insertBefore(this.dummyItem, trackerItem);
		}

		if (e.preventDefault)
			e.preventDefault();
	},
	dragDo: function(e)
	{
		if (this.drag)
		{
			e = e || event;

			var ny = this.sy + e.clientY;
			var trackerId = this.drag;
			this.trackerItems[trackerId].style.top = ny + 'px';

			var el, index, parent;

			if (ny - this.dy > this.nh)
			{
				index = this.order.indexOf(trackerId);
				if ((el = this.getNextTracker(index)))
				{
					parent = this.dummyItem.parentNode;
					parent.insertBefore(parent.removeChild(this.dummyItem), el.nextSibling);

					this.ph = el.clientHeight;
					this.dy += this.ph;

					this.nh = this.getNextTracker(index+1).clientHeight || 0;

					this.order[index] = this.order[index+1];
					this.order[index+1] = trackerId;
					this.updateOrder = true;
				}
			}
			else if (this.dy - ny > this.ph)
			{
				index = this.order.indexOf(trackerId);
				if ((el = this.getPreviousTracker(index)))
				{
					parent = this.dummyItem.parentNode;
					parent.insertBefore(parent.removeChild(this.dummyItem), el);

					this.nh = el.clientHeight;
					this.dy -= this.nh;

					this.ph = this.getPreviousTracker(index-1).clientHeight || 0;

					this.order[index] = this.order[index-1];
					this.order[index-1] = trackerId;
					this.updateOrder = true;
				}
			}
		}
	},
	dragStop: function()
	{
		if (this.drag)
		{
			var trackerItem = this.trackerItems[this.drag];

			trackerItem.parentNode.removeChild(trackerItem);
			removeClass(trackerItem, 'dragitem');
			trackerItem.style.top = 0;
			this.dummyItem.parentNode.replaceChild(trackerItem, this.dummyItem);

			this.drag = null;

			if (this.updateOrder)
			{
				this.updateTrackerOrder();
				this.updateOrder = false;
			}
		}
	},
	getPreviousTracker: function(i)
	{
		var previousTracker = false, trackerId;

		while ((trackerId = this.order[--i]))
		{
			if (this.trackerItems[trackerId].offsetParent)
			{
				previousTracker = this.trackerItems[trackerId];
				break;
			}
		}

		return previousTracker;
	},
	getNextTracker: function(i)
	{
		var nextTracker = false, trackerId;

		while ((trackerId = this.order[++i]))
		{
			if (this.trackerItems[trackerId].offsetParent)
			{
				nextTracker = this.trackerItems[trackerId];
				break;
			}
		}

		return nextTracker;
	},
	updateTrackerOrder: function()
	{
		var postBody = ['section=' + this.section];
		for (var i = 0; i < this.order.length; i++)
			postBody.push('volgorde%5B%5D=' + this.order[i]);

		var result = this.ajax.sendRequest(
			getXmlHttpUrl('frontpage', 'tracker', 'set_order'),
			{
				method: 'POST',
				type: 'json',
				async: false,
				appendSid: true,
				handler: checkJsonResponse
			},
			postBody.join('&')
		);

		if (result)
			this.settings = result;
	},
	refreshInit: function(trackerId)
	{
		if (this.settings[trackerId] && this.settings[trackerId]['refresh'])
		{
			this.trackerRefreshes[trackerId] = RefreshTimer().getCounter() + this.settings[trackerId]['refresh'];
		}
		else if (this.trackerRefreshes[trackerId])
		{
			delete this.trackerRefreshes[trackerId];
		}
	},
	refreshAll: function(timerCount)
	{
		var trackerIds = [], trackerId;
		for (var trackerId in this.trackerRefreshes)
		{
			if (this.trackerRefreshes[trackerId] <= timerCount)
			{
				trackerIds.push(trackerId);
				this.trackerRefreshes[trackerId] = timerCount + this.settings[trackerId]['refresh'];

				this.refreshTracker(trackerId);
			}
		}

		if (trackerIds.length)
			setTimeout(this.refreshRequest.bind(this, trackerIds, true), 500);
	},
	refreshTracker: function(trackerId)
	{
		var tracker = this.trackerItems[trackerId].getElementsByTagName('h4')[0];

		var throbber = document.createElement('img');
		throbber.src = getPreloadImage('tracker_throbber');
		throbber.title = 'Refreshing...';
		throbber.style.cssText = 'position:absolute;' + (this.position == 'r' ? 'right' : 'left') + ':3px;top:4px;width:11px;height:11px;';

		tracker.appendChild(throbber);
	},
	refreshRequest: function(trackerId, async)
	{
		if (trackerId instanceof Array)
			trackerId = trackerId.join(',');

		return this.ajax.sendRequest(
			getXmlHttpUrl('frontpage', 'tracker', 'get_items', 'section=' + this.section + '&trackerid=' + trackerId),
			{
				method: 'GET',
				type: 'json',
				async: !!async,
				nocache: true,
				handler: async ? this.refreshDone.bind(this, trackerId) : checkJsonResponse
			}
		);
	},
	refreshDone: function(trackerIds, response)
	{
		var trackerData = checkJsonResponse(response);

		if (trackerData)
		{
			trackerIds = trackerIds.split(',');
			var trackerId, tracker, i = 0;
			while ((trackerId = trackerIds[i++]))
			{
				if (trackerId in trackerData)
					this.builtTracker(trackerId, trackerData[trackerId]);

				// remove throbber
				if ((tracker = this.trackerItems[trackerId].getElementsByTagName('h4')[0]))
					tracker.removeChild(tracker.lastChild);
			}
		}
	},
	getTrackerHeadlines: function(trackerId)
	{
		var trackerData = this.refreshRequest(trackerId, false);
		if (trackerData && trackerId in trackerData)
			this.builtTracker(trackerId, trackerData[trackerId]);
	},
	builtTracker: function(trackerId, trackerData)
	{
		if (trackerData)
		{
			if ('headlines' in trackerData)
				this.trackerHeadlines[trackerId] = trackerData['headlines'];

			if ('itemConfig' in trackerData)
				this.trackerItemConfig[trackerId] = trackerData['itemConfig'];
		}

		if (this.trackerHeadlines[trackerId] && this.trackerHeadlines[trackerId] instanceof Array)
		{
			if (!this.trackerItems[trackerId])
			{
				this.trackerItems[trackerId] = this.builtTrackerHeader(trackerId);
			}

			var trackerItem = this.trackerItems[trackerId] && this.trackerItems[trackerId].getElementsByTagName('ul')[0];

			if (trackerItem)
			{
				while (trackerItem.hasChildNodes())
					trackerItem.removeChild(trackerItem.firstChild);

				var aantal = this.settings[trackerId]['aantal'] || 3, i = 0, trackerHeadline;
				while (i < aantal && (trackerHeadline = this.trackerHeadlines[trackerId][i++]))
				{
					trackerHeadline.url = trackerHeadline.url.unescapeHtml();
					trackerHeadline.caption = trackerHeadline.caption.unescapeHtml();

					trackerItem.appendChild(
						HTMLBuilder().built(
							{n:'li',c:[{n:'a',a:{href:trackerHeadline.url,className:(trackerHeadline.channelClass+(trackerHeadline.isNew?' new':'')).trim(),title:(trackerHeadline.channelClass?trackerHeadline.channelClass.ucFirst()+': ':'')+trackerHeadline.caption,target:this.getLinkTarget(trackerId)},c:[{n:'span',a:{className:'time'},c:[{n:'#text',v:trackerHeadline.tijd}]},{n:'#text',v:' '},{n:'span',a:{className:'caption'},c:[{n:'#text',v:trackerHeadline.caption}]}]}]})
					);
				}

				ellipsis(trackerItem);
				utracker_stretch();
			}
		}
	},
	builtTrackerHeader: function(trackerId)
	{
		var trackerItem = null, itemConfig = this.trackerItemConfig[trackerId];
		if (itemConfig)
		{
			trackerItem = HTMLBuilder().built({n:'div',a:{className:'trackeritem',id:'tracker-'+trackerId},c:[{n:'h4',c:[{n:'span',a:{className:'time'},c:[{n:'#text',v:'00:00'}]},{n:'#text',v:' '},{n:'a',a:{href:itemConfig['link'],target:this.getLinkTarget(trackerId)},c:[{n:'#text',v:itemConfig['caption']}]}]},{n:'ul',a:{className:'ellipsis'}}]});

			this.appendTracker(trackerId, trackerItem);
		}

		return trackerItem;
	},
	showHideTracker: function(trackerId, show)
	{
		var trackerItem = this.trackerItems[trackerId];

		if (show)
		{
			if (!trackerItem)
			{
				if (!this.trackerHeadlines[trackerId])
					this.getTrackerHeadlines(trackerId);
				else
					this.builtTracker(trackerId);

				this.order.push(trackerId);
			}
			else if (!trackerItem.offsetParent)
			{
				this.appendTracker(trackerId, trackerItem, true);
			}
		}
		else
		{
			// check if attached to the document, can't use parentNode here since in IE it has parentNode '#document-fragment' and in other browsers no parentNode at all
			if (trackerItem && trackerItem.offsetParent)
			{
				trackerItem.parentNode.removeChild(trackerItem);
			}
		}
	},
	getLinkTarget: function(trackerId)
	{
		var itemConfig = this.trackerItemConfig[trackerId];
		return itemConfig && itemConfig['rel'] && itemConfig['rel'] == 'external' ? '_blank' : null;
	},
	appendTracker: function(trackerId, trackerItem, stretch)
	{
		var index = this.order.indexOf(trackerId);
		this.tracker.insertBefore(trackerItem, (index > -1 && this.getNextTracker(index)) || getElementsByClassName('trackerbottom', 'div', this.tracker)[0] || this.propertyImg);
		if (stretch)
			utracker_stretch();
	}
});

function TrackerPropPopup(tracker)
{
	this.tracker = tracker;
	this.trackerId = 0;
	this.settings = null;
	this.propertyElements = null;
	this.popup = null;

	this.init();
}
Object.extend(TrackerPropPopup.prototype,
{
	init: function()
	{
		this.popup = new Popup(320, this.closePopup.bind(this));

		addEvent(window, 'unload', this.cleanUp.bind(this));
	},
	cleanUp: function()
	{
		this.propertyElements = null;
		this.popup = null;
		this.tracker = null;
	},
	initContent: function(trackerId)
	{
		this.trackerId = trackerId;
		this.settings = Object.extend({}, this.tracker.settings[this.trackerId]);

		// fetch max number of links
		if (!this.tracker.trackerHeadlines[trackerId])
			this.tracker.getTrackerHeadlines(trackerId);

		// set max for aantal
		var maxItems = 10;
		if (this.tracker.trackerItemConfig[trackerId] && this.tracker.trackerItemConfig[trackerId]['max'])
			maxItems = this.tracker.trackerItemConfig[trackerId]['max'];

		var caption = this.settings.caption || (this.tracker.trackerItemConfig[trackerId] && this.tracker.trackerItemConfig[trackerId]['caption']) || trackerId.ucFirst();

		this.popup.setContent(
			HTMLBuilder().built({n:'div',c:[{n:'h4',c:[{n:'#text',v:(caption)+' tracker:'}]},{n:'table',a:{cellpadding:2},c:[('aantal' in this.settings?{n:'tr',c:[{n:'td',a:{width:50},c:[{n:'#text',v:'Aantal:'}]},{n:'td',c:[{o:new Slider({max:maxItems,value:this.settings['aantal']||3,slideArea:this.popup.contentArea,onchange:this.changeAantal.bind(this)}).sliderControl},{n:'span',a:{id:'trackerAantal'},c:[{n:'#text',v:' ('+this.settings['aantal']+')'}]}]}]}:null),('refresh' in this.settings?{n:'tr',c:[{n:'td',a:{width:50},c:[{n:'#text',v:'Refresh:'}]},{n:'td',c:[{o:new Slider({max:5,value:this.settings['refresh'],slideArea:this.popup.contentArea,onchange:this.changeRefresh.bind(this)}).sliderControl},{n:'span',a:{id:'trackerRefresh'},c:[{n:'#text',v:this.getRefreshText(this.settings['refresh'])}]}]}]}:null),{n:'tr',c:[{n:'td',a:{colSpan:2,style:'text-align:center'},c:[{n:'input',a:{type:'button',className:'button',value:'Opslaan',onclick:this.saveSettings.bind(this)}}]}]}]}]})
		);
		this.propertyElements = HTMLBuilder().getIdList();

		return true;
	},
	changeAantal: function(aantal)
	{
		if (this.tracker.settings[this.trackerId]['aantal'] == 0 || aantal == 0)
			this.tracker.showHideTracker(this.trackerId, aantal);

		this.propertyElements['trackerAantal'].firstChild.nodeValue = ' (' + aantal + ')';
		this.tracker.settings[this.trackerId]['aantal'] = aantal;
		this.tracker.builtTracker(this.trackerId);
	},
	getRefreshText: function(aantal)
	{
		return ' ' + (aantal ? aantal + ' ' + (aantal > 1 ? 'minuten' : 'minuut') : 'uit');
	},
	changeRefresh: function(aantal)
	{
		this.propertyElements['trackerRefresh'].firstChild.nodeValue = this.getRefreshText(aantal);
		this.tracker.settings[this.trackerId]['refresh'] = aantal;
	},
	saveSettings: function()
	{
		var postBody = ['section='+this.tracker.section, 'trackerid='+this.trackerId], settings = this.tracker.settings[this.trackerId];
		for (var option in settings)
		{
			if (settings.hasOwnProperty(option))
				postBody.push(encodeURIComponent('options['+option+']') + '=' + encodeURIComponent(settings[option]));
		}

		var result = this.tracker.ajax.sendRequest(
			getXmlHttpUrl('frontpage', 'tracker', 'set_options'),
			{
				method: 'POST',
				type: 'json',
				async: false,
				appendSid: true,
				handler: checkJsonResponse
			},
			postBody.join('&')
		);

		if (result)
			this.tracker.settings = result;

		this.tracker.refreshInit(this.trackerId);

		this.closePopup();
	},
	closePopup: function(reset)
	{
		if (reset)
		{
			this.tracker.showHideTracker(this.trackerId, true);

			// reset original settings
			this.tracker.settings[this.trackerId] = {};
			Object.extend(this.tracker.settings[this.trackerId], this.settings);
			this.tracker.builtTracker(this.trackerId);
		}

		this.trackerId = 0;
		this.popup.close();
		this.tracker.foldinDelayed();

		RefreshTimer().resume();
	}
});

function TrackerChoicePopup(tracker)
{
	this.tracker = tracker;
	this.popup = null;

	this.init();
}
Object.extend(TrackerChoicePopup.prototype,
{
	init: function()
	{
		this.popup = new Popup(220, this.closePopup.bind(this));

		addEvent(window, 'unload', this.cleanUp.bind(this));
	},
	cleanUp: function()
	{
		this.popup = null;
		this.tracker = null;
	},
	initContent: function()
	{
		var options = [], settings, caption;
		for (var trackerId in this.tracker.settings)
		{
			if (this.tracker.settings.hasOwnProperty(trackerId))
			{
				settings = this.tracker.settings[trackerId];

				// this check skips config items
				if ('aantal' in settings)
				{
					caption = settings.caption || (this.tracker.trackerItemConfig[trackerId] && this.tracker.trackerItemConfig[trackerId]['caption']) || trackerId.ucFirst();

					options.push({n:'tr',c:[{n:'td',a:{width:20},c:[{n:'input',a:{type:'checkbox',id:'showtracker_'+trackerId,defaultChecked:!!settings['aantal'],onclick:this.toggleTracker.bind(this, trackerId)}}]},{n:'td',c:[{n:'label',a:{htmlFor:'showtracker_'+trackerId},c:[{n:'#text',v:caption}]}]}]});
				}
			}
		}

		options.push({n:'tr',c:[{n:'td',a:{colSpan:2,style:'text-align:center'},c:[{n:'input',a:{type:'button',className:'button',value:'Opslaan',onclick:this.saveSettings.bind(this)}}]}]});

		this.popup.setContent(
			HTMLBuilder().built({n:'div',c:[{n:'h4',c:[{n:'#text',v:'Tracker keuzes:'}]},{n:'table',a:{cellpadding:2},c:options}]})
		);

		return true;
	},
	toggleTracker: function(trackerId, e)
	{
		e = e || event;
		var target = e.target || e.srcElement, checked = target.checked;

		this.tracker.showHideTracker(trackerId, checked);
	},
	saveSettings: function()
	{
		var trackerId, trackerItem, index;
		for (trackerId in this.tracker.settings)
		{
			if (this.tracker.settings.hasOwnProperty(trackerId))
			{
				trackerItem = this.tracker.trackerItems[trackerId];
				index = this.tracker.order.indexOf(trackerId);

				if (trackerItem && trackerItem.offsetParent)
				{
					if (index < 0) this.tracker.order.push(trackerId);

					if (!this.tracker.settings[trackerId]['aantal'])
						this.tracker.initTrackerItem(trackerId);
				}
				else
				{
					if (index > -1) this.tracker.order.splice(index, 1);
				}
			}
		}

		this.tracker.updateTrackerOrder();
		this.closePopup();
	},
	closePopup: function(reset)
	{
		if (reset)
		{
			var trackerId, trackerItem, index;
			for (trackerId in this.tracker.settings)
			{
				if (this.tracker.settings.hasOwnProperty(trackerId))
				{
					trackerItem = this.tracker.trackerItems[trackerId];
					if (trackerItem)
					{
						if (this.tracker.settings[trackerId]['aantal'])
						{
							if (!trackerItem.offsetParent)
								this.tracker.appendTracker(trackerId, trackerItem, true);
						}
						else
						{
							if (trackerItem.offsetParent)
								trackerItem.parentNode.removeChild(trackerItem);

							if ((index = this.tracker.order.indexOf(trackerId)) > -1)
								this.tracker.order.splice(index, 1);
						}
					}
				}
			}
		}

		this.popup.close();
		this.tracker.foldinDelayed();

		RefreshTimer().resume();
	}
});

function Slider(options)
{
	this.options = options;

	this.sliderControl = null;
	this.slider = null;

	this.min = 0;
	this.max = 0;
	this.step = 0;
	this.value = 0;
	this.onchange = null;

	this.drag = false;
	this.mx = 0;
	this.cx = 0;
	this.sx = 0;
	this.x = 0;

	this.init();
}
Object.extend(Slider.prototype,
{
	init: function()
	{
		if (this.options)
		{
			this.min = parseInt(this.options.min || 0, 10);
			this.max = parseInt(this.options.max, 10);

			if ('step' in this.options)
			{
				this.step = parseInt(this.options.step, 10);
			}
			else
			{
				this.step = Math.ceil((this.max - this.min) / 10);
			}

			this.value = parseInt(this.options.value, 10);

			this.onchange = this.options.onchange;

			var width = (((this.max - this.min) / this.step) * 20) + 3;
			this.mx = width - 5;

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

			this.slider = document.createElement('div');
			this.slider.className = 'slider';
			this.sliderControl.appendChild(this.slider);

			this.sliderSnap();
			addEvent(this.slider, 'mousedown', this.sliderStart.bind(this));
			this.slider.onselectstart = function() { return false; }

			addEvent(this.sliderControl, 'click', this.sliderClick.bind(this));

			addEvent(this.options.slideArea || document, 'mousemove', this.sliderMove.bind(this));
			addEvent(document, 'mouseup', this.sliderStop.bind(this));

			addEvent(window, 'unload', this.cleanUp.bind(this));
		}
	},
	cleanUp: function()
	{
		this.slider = null;
		this.sliderControl = null;
	},
	sliderStart: function(e)
	{
		e = e || event;

		this.sx = e.clientX;
		this.drag = true;
	},
	sliderMove: function(e)
	{
		e = e || event;
		if (this.drag)
		{
			var nx = this.cx - this.sx + e.clientX;
			if (nx < -4) nx = -4;
			if (nx > this.mx) nx = this.mx;
			this.slider.style.left = nx + 'px';

			var nv = this.min + Math.round(((nx + 4) / 20) * this.step);
			if (nv != this.value)
				this.sliderOnChange(nv);
		}
	},
	sliderClick: function(e)
	{
		e = e || event;

		var target = e.target || e.srcElement;

		if (!this.drag && target != this.slider)
		{
			var nx = e.layerX || e.offsetX || 0;

			var nv = this.min + Math.round((nx / 20) * this.step);
			if (nv != this.value)
				this.sliderOnChange(nv, true);
		}
	},
	sliderStop: function(e)
	{
		this.drag = false;
		this.sliderSnap();
	},
	sliderSnap: function()
	{
		this.cx = (((this.value - this.min) / this.step) * 20) - 4;
		this.slider.style.left = this.cx + 'px';
	},
	sliderOnChange: function(value, snapSlider)
	{
		this.value = this.options.value = value;

		if (snapSlider)
			this.sliderSnap();

		if (this.onchange)
			this.onchange(this.value);
	}
});

function utracker_stretch()
{
	var utracker = getById('utracker');
	if (utracker)
	{
		var contentWrapper = getById('contentWrapper');
		if (contentWrapper)
		{
			var ch = contentWrapper.clientHeight;
			var nh = utracker.clientHeight;

			var channelNav = getById('channelNav');
			if (channelNav)
				nh += channelNav.clientHeight;

			if (ch && ch < nh)
			{
				// oddly enough IE6 gives type 'string' for minHeight
				if (typeof contentWrapper.style.minWidth == 'undefined')
					contentWrapper.style.height = nh + 'px';
				else
					contentWrapper.style.minHeight = nh + 'px';
			}
		}
	}
}

function positionTracker()
{
	var utracker = getById('utracker');
	if (utracker)
	{
		var top = 88;
		var channelNav = getById('channelNav');
		if (channelNav)
			top = channelNav.offsetTop + channelNav.clientHeight - 8;

		utracker.style.top = top + 'px';
	}
}

function initChannelNavToggle()
{
	var page = getById('page');
	if (page && !hasClass(page, 'notracker'))
	{
		var channelNav = getById('channelNav');
		if (channelNav)
		{
			var logoPointer = getById('logopointer');
			if (logoPointer)
			{
				if (hasClass(page, 'trackerright'))
				{
					logoPointer.style.cursor = 'default';
					logoPointer.title = '';
					logoPointer.onclick = function(){};
				}
				else
				{
					logoPointer.style.cursor = 'pointer';
					logoPointer.title = 'Rubriekenkiezer tonen/verbergen';
					logoPointer.onclick = toggleChannelNav;
				}
			}

			if (getCookie('channel') == 'off')
				addClass(channelNav, 'hidden');
		}
	}
}

function toggleChannelNav()
{
	var channelNav = getById('channelNav');
	if (channelNav)
	{
		var hide = !hasClass(channelNav, 'hidden');

		if (hide)
			addClass(channelNav, 'hidden');
		else
			removeClass(channelNav, 'hidden');

		setCookie('channel', (hide ? 'off' : 'on'));
		positionTracker();

		if (!hide)
			utracker_stretch();
	}
}

function Poll(id)
{
	this.pollId = id;

	this.init();
}
Object.extend(Poll.prototype,
{
	init: function()
	{
		this.pollForm = document.getElementById('poll');
		this.pollContainer = null;

		if (this.pollForm)
		{
			addClass(this.pollForm, 'jsenabled');

			var labels = this.pollForm.getElementsByTagName('label'), label, option, i = 0;
			while ((label = labels[i++]))
			{
				if (label.htmlFor && (option = document.getElementById(label.htmlFor)) && !option.disabled)
				{
					addEvent(label, 'mouseover', this.optionMouseOver);
					addEvent(label, 'mouseout', this.optionMouseOut);
					addEvent(label, 'click', this.optionSelect.bind(this, option));

				}

				if(option && option.checked)
				{
					addClass(label, 'selected');
				}
			}

			labels = null, label = null, option = null;
			addEvent(window, 'unload', this.cleanUp.bind(this));
		}
	},
	cleanUp: function()
	{
		this.pollContainer = null;
		this.pollForm = null;
	},
	optionMouseOver: function()
	{
		addClass(this, 'hover');
	},
	optionMouseOut: function()
	{
		removeClass(this, 'hover');
	},
	optionSelect: function(option, e)
	{
		var result = Ajax().sendRequest(
			getXmlHttpUrl('frontpage', 'poll', 'vote', 'PollID=' + this.pollId),
			{
				method: 'POST',
				type: 'text',
				async: false,
				nocache: true,
				appendSid: true
			},
			'option=' + option.value
		);

		if (result)
			this.showVotes(result);
		else
			this.pollform.submit();

		return false;
	},
	getVotes: function()
	{
		var result = Ajax().sendRequest(
			getXmlHttpUrl('frontpage', 'poll', 'show', 'PollID=' + this.pollId),
			{
				method: 'GET',
				type: 'text',
				async: false,
				nocache: true
			}
		);

		if (result)
			this.showVotes(result);
	},
	showVotes: function(result)
	{
		if (!this.pollContainer)
		{
			this.pollContainer = this.pollForm.parentNode;
			this.pollContainer.removeChild(this.pollForm);
		}

		this.pollContainer.innerHTML = result;
		this.init();
	}
});

// search functions
function showSearchOptions()
{
	var searchOptionsBox = getById('searchOptions');
	if (searchOptionsBox)
	{
		searchOptionsBox.style.display = 'block';
		addEvent(document, 'click', hideSearchOptions);
	}
}
function hideSearchOptions(e)
{
	var target = e.target || e.srcElement;

	while (target)
	{
		if (target.id == 'searchbox')
			return false;

		target = target.parentNode;
	}

	getById('searchOptions').style.display = 'none';
	removeEvent(document, 'click', hideSearchOptions);

	return true;
}

// banner functions
var dblc_tile=1,dblc_ord,dblc_serverup=true,dblc_firstdone=false,dblc_waitserver=4000;

function dblc_testserver()
{
	if (!dblc_firstdone)
	{
		if (dblc_waitserver > 0)
		{
			dblc_waitserver -= 200;
			setTimeout('dblc_testserver()',200);
		}
		else
		{
			dblc_serverup = false;
			if (is.ie)
				document.scripts['dblc_tag1'].src = '//';
		}
	}
}

function dblc_writeTag(dblc_size, dblc_type)
{
	if (dblc_serverup)
	{
		// first tag
		if (dblc_tile == 1)
		{
			dblc_ord = Math.floor(Math.random() * 10000000000000000);
			setTimeout('dblc_testserver()', 200);
		}

		document.write('<script type="text/javascript" id="dblc_tag' + dblc_tile +
					'" src="http://ad.nl.doubleclick.net/adj/' +
					'vnumedia.' + (dblc_channel == 'gethering' ? dblc_channel + '.tweak' : 'tweak' + dblc_channel) + '.nl/' + dblc_zone +
					';keyword=' + dblc_keyword +
					';sz=' + dblc_size +
					';tile=' + dblc_tile +
					(dblc_type == 'tb' ? ';dcopt=ist' : '') + // Allow interstitial ads (those ugly corner-ads)
					';ord=' + dblc_ord +
					(dblc_ctry ? ';ctry=' + dblc_ctry : '') +
					'?"><\/scr'+'ipt>');

		dblc_tile++;
	}
}

var loadedBanners = {};
function bannerCheck(type, adReplacement, adReplacementData)
{
	dblc_firstdone = true;

	var el_tmp = getById('b_'+type+'_tmp');
	if (el_tmp)
	{
		if (el_tmp.offsetHeight > 24 || /<(object|embed)\s/i.test(el_tmp.innerHTML))
		{
			loadedBanners[type] = el_tmp;
		}
		else
		{
			if (adReplacement && (type != 'ad' || !loadedBanners['re']))
			{
				var el = getById('b_'+type);

				if (el)
				{
					el.innerHTML = '';

					if (adReplacement == 'tl_sidebar')
					{
						create_textlinks('b_'+type, adReplacementData);
					}
					else
					{
						// adsense
						create_google_advertorial('b_'+type, adReplacementData);
					}
				}
			}
		}
	}
}

function bannerSync(type)
{
	var el_tmp = loadedBanners[type];

	if (el_tmp)
	{
		var el = getById('b_'+type);

		if (el)
		{
			// remove all script-elements for opera, else they will be re-executed
			if (is.opera)
			{
				var script = el_tmp.getElementsByTagName('script');
				while (script.length) script[0].parentNode.removeChild(script[0]);
			}

			var width = el_tmp.offsetWidth, height = el_tmp.offsetHeight, breakout = false;

			// type switching based upon width for topbanner
			if (type == 'tb')
			{
				if (width > 472)
				{
					if (width > 732)
					{
						var header = getById('headerWrapper');
						if (header)
						{
							// create replacement holder right after header
							var replacement = document.createElement('div');
							replacement.id = 'headerReplacement';
							replacement.appendChild(el);
							header.appendChild(replacement);

							/* true logo tijdelijk verbergen
							var sponsorImage = getElementsByClassName('sponsorlogo', 'a');
							if (sponsorImage.length)
								sponsorImage[0].style.display = 'none';
							*/

							// logopointer verbergen
							var logopointer = getById('logopointer');
							if (logopointer)
								logopointer.style.display = 'none';

							// update tracker herpositioneren
							var utracker = getById('utracker');
							if (utracker)
								utracker.style.top = (parseInt(utracker.style.top) + height) + 'px';
						}
					}
					else
					{
						el.className = 'leaderBoard';
						el.style.width = '728px';
					}
				}
				else
				{
					el.className = 'topBanner';
					el.style.width = '468px';
				}
			}
			else if (type == 're')
			{
				var tmp, news;

				if (height > 280 || height < 200)
					height = 280;
				if (width > 336 || width < 300)
					width = 336;

				if (hasClass((news = el.parentNode.parentNode), 'news'))
				{
					// create breakout box for rectangle in news
					var sbwidth = el.parentNode.offsetWidth;
					if (width > sbwidth)
					{
						breakout = true;

						tmp = document.createElement('div');
						tmp.id = 'b_re_helper';
						tmp.style.height = height + 'px';
						// 21 is the padding between .content and .sidebar
						tmp.style.width = (Math.max(width - (sbwidth + 21), 1)) + 'px';

						var content = first_child(news, 'div');
						content.insertBefore(tmp, content.firstChild);

						// move b_re_tmp to #contentWrapper
						el_tmp.parentNode.removeChild(el_tmp);
						news.parentNode.appendChild(el_tmp);
						el_tmp.style.top = getOffsetTop(tmp, news.parentNode) + 'px';

						// set height based on content; some rectangles are < 280px high
						el.style.height = height + 'px';
					}
				}

				if (!breakout)
					el.style.width = width + 'px';
			}

			if (!breakout)
			{
				while (el_tmp.hasChildNodes())
				{
					tmp = el_tmp.removeChild(el_tmp.firstChild);
					el.appendChild(tmp);
				}
			}

			el.style.display = 'block';
		}
	}
}

function create_textlinks(id, replaceData)
{
	var el = getById(id);

	if (!el) return false;

	if (!replaceData || !(replaceData instanceof Array) || !replaceData.length)
	{
		el.style.display = 'none';
		return false;
	}

	var s = ['<div class="textadContainer"><div class="textadBg"><div class="textadTop"><small>Gesponsorde links</small></div><table class="textadTable">'], i = 0, textlink, no_external;

	while ((textlink = replaceData[i++]))
	{
		no_external = /http:\/\/([a-z]+\.)?tweakers\.net\//.test(textlink.link);

		s.push(
			'<tr><td><img src="' + (textlink.image.indexOf('http://') === 0 ? textlink.image : ImgURL + 'g/banners/' + textlink.image) + '" alt="' + textlink.client + ' logo"></td>'
			+ '<td class="ellipsis textadContent"><a href="' + textlink.link + '"' + (no_external ? '' : ' target="_blank"') + ' title="' + textlink.title.replace(/<[^>]*>/g, '') + '">' + textlink.title + textlink.text.replace(/\[timestamp\]/, new Date().getTime()) + '</a></td></tr>'
		);
	}

	s.push('</table><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;
}
