function SiteMenu(activeMenu)
{
	this.element = document.getElementById('siteMenu');
	this.menuItems = [];
	this.activeMenu = activeMenu;
	this.menuActive = false;
	this.menuItemTimeout = null;
	this.menuTimeout = null;
	this.init();
}

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 mainNav = document.getElementById('mainNav');
			if (mainNav)
			{
				addEvent(mainNav, 'mouseover', this.cancelMouseout.bind(this));
				addEvent(mainNav, 'mouseout', this.onMouseout.bind(this, this.activeMenu));
			}

			addEvent(window, 'unload', this.cleanUp.bind(this));
		}
	},
	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');
				}
			}

			this.activeMenu = i;

			if ((menu = this.menuItems[this.activeMenu]))
			{
				addClass(menu, 'active');
				if (menu.subMenu.element)
					addClass(menu.subMenu.element, 'active');
			}
		}
	},
	handleMouseout: function(i)
	{
		this.handleMouseover(i);
		this.menuActive = false;
	}
});

function SubMenu(id, offset)
{
	this.element = document.getElementById('groupNav' + id);
	this.offset = offset;
	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 menu = first_child(this.element, 'ul'), menuitem, menusubitem, i = 0;
			if (menu)
			{
				menuitem = first_child(menu, 'li');
				if (menuitem)
				{
					var lastitem = null;

					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')));

					if (lastitem)
					{
						//-- here we try to 'center' the submenu belof the maintab
						this.offset -= Math.floor(lastitem.offsetLeft / 2);
						this.offset += 54; // half of the maintab width
						if (this.offset < 100) this.offset = 100;
						if (this.offset + lastitem.offsetLeft > 880) this.offset = 880 - lastitem.offsetLeft;
						this.element.style.left = this.offset + 'px';
					}
				}
			}

			addEvent(this.element, 'mouseover', this.cancelMouseout.bind(this));
			addEvent(this.element, 'mouseout', this.onMouseout.bind(this));

			menu = null, menuitem = null, menusubitem = null;
			addEvent(window, 'unload', this.cleanUp.bind(this));
		}
	},
	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)
	{
		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 = document.getElementById(id);
	this.tabItems = [];
	this.tablistItems = [];
	this.activeTab = 1;
	this.toggleTimer = 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));
					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();

			ul = null, li = null, a = null;
			addEvent(window, 'unload', this.cleanUp.bind(this));
		}
	},
	cleanUp: function()
	{
		this.stopToggle();
		this.tablistItems = null;
		this.tabItems = null;
		this.element = null;
	},
	setActive: function(i, e)
	{
		if (i != 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 (e) e.preventDefault();
	},
	toggle: function()
	{
		var i = this.activeTab + 1;
		if (!this.tabItems[i]) i = 1;

		this.setActive(i);
		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 Tracker(settings)
{
	this.ajax = null;
	this.settings = settings;
	this.tracker = document.getElementById('utracker');
	this.propertyImg = null;
	this.trackerItems = {};
	this.trackerHeadlines = {};
	this.trackerItemConfig = {};
	this.trackerItemSettings = {};
	this.trackerRefreshes = {};
	this.order = [];
	this.drag = null;
	this.dummyItem = null;
	this.updateOrder = false;
	this.sy = 0;
	this.dy = 0;
	this.ph = 0;
	this.nh = 0;
	this.init();
}

Object.extend(Tracker.prototype =
{
	init: function()
	{
		if (this.tracker)
		{
			// logged in?
			if (UserID)
			{
				// ajax enabled?
				if ((this.ajax = new Ajax()).getRequestObject(true))
				{
					//-- preloads
					preload('tracker_button_right', 'g/if/tracker/button_right.gif');
					preload('tracker_button_right_mouseover', 'g/if/tracker/button_right_mouseover.gif');
					preload('tracker_throbber', 'g/if/tracker/timer_ani.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 = this.createPropertyImage();
				}
			}

			if (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;
	},
	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';
			imageHoverSwap(img, 'tracker_button_right', 'tracker_button_right_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;
	},
	createPropertyImage: function()
	{
		var img = document.createElement('img');
		img.src = ImgURL + 'g/if/icons/layout.gif';
		img.title = 'Tracker keuzes';
		img.style.cssText = 'width:16px;height:16px;margin-left:3px;cursor:pointer';
		addEvent(img, 'click', this.trackerChoices.bind(this));
		this.tracker.appendChild(img);

		return img;
	},
	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)
		{
			if (this.trackerPropPopup.initContent(trackerId))
			{
				setRelativePosition(this.trackerPropPopup.popup.element, propImg, 1, 14);
				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 if (this.trackerChoicePopup.initContent())
			{
				setRelativePosition(this.trackerChoicePopup.popup.element, this.propertyImg, -416, 211, 100, 0);
				this.trackerChoicePopup.popup.show();
			}
		}
	},
	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 = [];
		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.trackerRefreshes[trackerId])
			clearTimeout(this.trackerRefreshes[trackerId]);

		if (this.settings[trackerId] && this.settings[trackerId]['refresh'])
			this.trackerRefreshes[trackerId] = setTimeout(this.refreshTracker.bind(this, trackerId), this.settings[trackerId]['refresh'] * 60000);
	},
	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;left:3px;top:4px;width:11px;height:11px;';

		tracker.appendChild(throbber);

		setTimeout(this.refreshRequest.bind(this, trackerId, true), 500);
	},
	refreshRequest: function(trackerId, async)
	{
		return this.ajax.sendRequest(
			getXmlHttpUrl('frontpage', 'tracker', 'get_items', 'trackerid=' + trackerId),
			{
				method: 'GET',
				type: 'json',
				async: !!async,
				nocache: true,
				handler: async ? this.refreshDone.bind(this, trackerId) : checkJsonResponse
			}
		);
	},
	refreshDone: function(trackerId, response)
	{
		var headlines = checkJsonResponse(response);

		this.builtTracker(trackerId, headlines);

		// remove throbber
		var tracker = this.trackerItems[trackerId].getElementsByTagName('h4')[0];
		tracker.removeChild(tracker.lastChild);

		// new timeout
		this.refreshInit(trackerId);
	},
	getTrackerHeadlines: function(trackerId)
	{
		var headlines = this.refreshRequest(trackerId, false);

		this.builtTracker(trackerId, headlines);
	},
	builtTracker: function(trackerId, headlines)
	{
		if (headlines && headlines[trackerId])
		{
			this.trackerHeadlines[trackerId] = headlines[trackerId];
			this.trackerItemConfig[trackerId] = headlines['itemConfig'];
		}

		if (this.trackerHeadlines[trackerId] && this.trackerHeadlines[trackerId] instanceof Array)
		{
			if (!this.trackerItems[trackerId])
			{
				this.trackerItems[trackerId] = this.builtTrackerHeader(trackerId);
				// this.initTrackerItem(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(this.tracker);
			}
		}
	},
	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:'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)) || this.propertyImg);
		if (stretch)
			utracker_stretch(this.tracker);
	}
});

function TrackerPropPopup(tracker)
{
	this.tracker = tracker;
	this.trackerId = 0;
	this.settings = null;
	this.popup = null;

	this.init();
}
Object.extend(TrackerPropPopup.prototype,
{
	init: function()
	{
		this.popup = new Popup(290, this.closePopup.bind(this));

		addEvent(window, 'unload', this.cleanUp.bind(this));
	},
	cleanUp: function()
	{
		this.popup = null;
		this.tracker = null;
	},
	initContent: function(trackerId)
	{
		this.trackerId = trackerId;
		this.settings = Object.extend({}, this.tracker.settings[this.trackerId]);

		if (!this.tracker.trackerHeadlines[trackerId])
			this.tracker.getTrackerHeadlines(trackerId);

		this.popup.setContent(
			HTMLBuilder().built({n:'div',c:[{n:'h4',c:[{n:'#text',v:(this.settings.caption||trackerId.ucFirst()) + ' 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({min:0,max:9,step:1,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),('showonlynew' in this.settings?{n:'tr',c:[{n:'td',a:{width:50},c:[{n:'input',a:{type:'checkbox',id:'showOnlyNew',defaultChecked:this.settings['showonlynew'],onclick:this.changeShowOnlyNew.bind(this)}}]},{n:'td',c:[{n:'label',a:{htmlFor:'showOnlyNew'},c:[{n:'#text',v:'Alleen nieuwe items tonen'}]}]}]}:null),('refresh' in this.settings?{n:'tr',c:[{n:'td',a:{width:50},c:[{n:'#text',v:'Refresh:'}]},{n:'td',c:[{o:new Slider({min:0,max:5,step:1,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)}}]}]}]}]})
		);

		return true;
	},
	changeAantal: function(aantal)
	{
		if (this.tracker.settings[this.trackerId]['aantal'] == 0 || aantal == 0)
			this.tracker.showHideTracker(this.trackerId, aantal);

		document.getElementById('trackerAantal').firstChild.nodeValue = ' (' + aantal + ')';
		this.tracker.settings[this.trackerId]['aantal'] = aantal;
		this.tracker.builtTracker(this.trackerId);
	},
	changeShowOnlyNew: function(e)
	{
		e = e || event;
		var target = e.target || e.srcElement, checked = target.checked;

		// not yet supported
	},
	getRefreshText: function(aantal)
	{
		return ' ' + (aantal ? aantal + ' ' + (aantal > 1 ? 'minuten' : 'minuut') : 'uit');
	},
	changeRefresh: function(aantal)
	{
		document.getElementById('trackerRefresh').firstChild.nodeValue = this.getRefreshText(aantal);
		this.tracker.settings[this.trackerId]['refresh'] = aantal;
	},
	saveSettings: function()
	{
		var postBody = ['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();
	}
});

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];
				caption = settings.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();
	}
});

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, 10);
			this.max = parseInt(this.options.max, 10);
			this.step = parseInt(this.options.step, 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 < -3) nx = -3;
			if (nx > this.mx) nx = this.mx;
			this.slider.style.left = nx + 'px';

			var nv = this.min + Math.round((nx + 3) / 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;

			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) - 3;
		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(utracker)
{
	if (!utracker)
		utracker = document.getElementById('utracker');

	if (utracker)
	{
		var nh = utracker.clientHeight /* + 10 ? */;
		var ch = utracker.parentNode.clientHeight;
		if (ch && ch < nh)
		{
			// oddly enough IE6 gives type 'string' for minHeight
			if (typeof utracker.parentNode.style.minWidth == 'undefined')
				utracker.parentNode.style.height = nh + 'px';
			else
				utracker.parentNode.style.minHeight = nh + 'px';
		}
	}
}

// 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, dblc_ctry)
{
	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.tweak' + dblc_channel + '.nl/' + dblc_zone +
					';keyword=' + dblc_keyword +
					';sz=' + dblc_size +
					';tile=' + dblc_tile +
					(dblc_size == '468x60,728x90' ? ';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, adsenseReplacement)
{
	dblc_firstdone = true;

	var el_tmp = document.getElementById('b_'+type+'_tmp');
	if (el_tmp)
	{
		if (el_tmp.offsetHeight > 24)
		{
			loadedBanners[type] = el_tmp;
		}
		else
		{
			if (adsenseReplacement && (type != 'ad' || !loadedBanners['re']))
			{
				var el = document.getElementById('b_'+type);

				if (el)
				{
					el.innerHTML = '';
					el.className = 'textadContainer';
					el.style.height = 'auto';
					create_google_advertorial(adsenseReplacement, type);
				}
			}
		}
	}
}

function bannerSync(type)
{
	var el = document.getElementById('b_'+type);

	if (el)
	{
		var el_tmp = loadedBanners[type];

		if (el_tmp)
		{
			// 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]);
			}

			// type switching based upon width for topbanner
			if (type == 'tb')
			{
				if (el_tmp.offsetWidth > 468)
				{
					if (el_tmp.offsetWidth > 728)
					{
						var contentArea = document.getElementById('contentArea');
						if (contentArea)
						{
							el.parentNode.removeChild(el);
							el.className = 'headerReplacement';
							contentArea.parentNode.insertBefore(el, contentArea);
						}
					}
					else
					{
						el.className = 'leaderBoard';
					}
				}
				else
				{
					el.className = 'topBanner';
				}
			}

			var tmp, news;

			if (type == 're' && hasClass((news = el.parentNode.parentNode), 'news'))
			{
				// create breakout box for rectangle in news
				tmp = document.createElement('div');
				tmp.id = 'b_re_helper';

				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';
			}
			else
			{
				while (el_tmp.hasChildNodes())
				{
					tmp = el_tmp.removeChild(el_tmp.firstChild);
					el.appendChild(tmp);
				}
			}

			el.style.display = 'block';
		}
		else
		{
			// when empty move advertorial to rectangle position (frontpage index)
			if (type == 're')
			{
				el_tmp = document.getElementById('b_ad');
				if (el_tmp)
				{
					el_tmp.parentNode.removeChild(el_tmp);
					el.parentNode.insertBefore(el_tmp, el);
				}
			}

			el.style.display = 'none';
		}
	}
}

var current_google_position = '', current_google_replace_type = '';
function create_google_advertorial(id, replaceType)
{
	// Url's are always shown when we display two items or less
	var google_ads_settings =
	{
		as_small:
		{
			channel: 1341951722,
			num_ads: 2
		},
		as_normal:
		{
			channel: 2723286129,
			num_ads: 2
		},
		as_rectangle:
		{
			channel: 1364049884,
			num_ads: 3
		}
	}

	if (window.tnet_google_ad_client && google_ads_settings[id])
	{
		if (replaceType)
			current_google_position = 'b_'+replaceType+'_tmp', current_google_replace_type = replaceType;
		else
			current_google_position = id, current_google_replace_type = '';

		document.write("<script type='text/javascript'>"
			+ "var google_page_url=adsense_page_url,google_language='nl',google_ad_type='text',"
			+ (window.dblc_zone && window.dblc_zone == 'test' ? "google_adtest='on'," : "")
			+ "google_ad_client='" + window.tnet_google_ad_client + "',"
			+ "google_ad_channel='" + google_ads_settings[id]['channel'] + "',google_ad_output='js',"
			+ "google_max_num_ads='" + google_ads_settings[id]['num_ads'] + "';<\/script>"
			+ "<script type='text/javascript' src='http://pagead2.googlesyndication.com/pagead/show_ads.js'><\/script>");
	}
	else
	{
		document.getElementById(elementId).style.display = 'none';
	}
}


// Allow for multiple sections with different functions to wrap the advertisements
function google_ad_request_done(google_ads)
{
	var el = current_google_position && document.getElementById(current_google_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="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_google_position != 'b_re_tmp' ? Math.floor(100 / l) : 100;

	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>');

	el.innerHTML = s.join('');

	if (current_google_replace_type)
		loadedBanners[current_google_replace_type] = el;
	else
		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;
}