/***************************************************************/
/*                                                             */
/*   @owner     : Telegraaf Media Nederland                    */
/*   @copyright : Speurders Online                             */
/*   @comment   : This file is used on speurdersindekrant.nl   */
/*                                                             */
/*   CONTENTS OF THIS FILE                                     */
/*                                                             */
/*      - debugging and temporary functions                    */
/*      - functions for easy coding with javascript (+ajax)    */
/*      - functions for html elements and animations           */
/*      - old functions, do we need these ???                  */
/*      - obsolete functions, we need to get rid of it         */
/*                                                             */
/***************************************************************/

/* this function is for debugging purposes, you need to have a div with id 'debug' on the page */
function debug(string, type) {
	return;
    if (typeof debugmessages != "undefined" && debugmessages && !IE) {
   		var debugDiv = document.getElementById('debug');
   		if (debugDiv != null) {
   			if (getHtml(debugDiv).length == 0) {
				if ((debugHeader = document.getElementById('debugHeader')) != null) removeClass(debugHeader, 'hidden');
   			}
   			var parent = String(debug.caller).split('function ',2)[1].split('(',2)[0];
   			greatParentCaler = debug.caller.caller;
   			greatParent = (greatParentCaler) ? String(greatParentCaler).split('function ',2)[1].split('(',2)[0] : '';
   			var prefix = (type) ? type + ': ' : 'ERROR: ';
   			removeClass(debugDiv, 'hidden');
			setHtml(debugDiv, prefix + greatParent + ' -> ' + parent + ': ' + string + '<br />' + getHtml(debugDiv));
		}
	}
}


function error(message) {
	debug(message, 'DEBUG');
}

function info(message) {
	debug(message, 'INFO');
}

function warm(message) {
	debug(message, 'WARN');
}


/***********************************************************/
/* these functions may come in handy for coding javascript */
/***********************************************************/
// IE fix if some console.logs are still in the code
if ( typeof console == 'undefined') {
	var console = {
		log : function(){},
		debug : function(){},
		warn : function(){},
		error : function(){},
		info : function(){}
	};
}

/* set IE to true or false */
var IE = ((document.all) && (navigator.userAgent.indexOf('Opera')== -1)) ? true : false;
var NS6	= document.getElementById && !document.all;

/* lockArr is een array die gebruikt wordt door isLocked, lock en unlock, hier kun je op de arraykeys 
   strings in zetten met een value true or false */
var lockArr	= [];

/* get an element by it's id, this one replaces the old getElement function */
function get(id) {
	return tmg('#' + id)[0];
}

function check(id) {
	if (document.getElementById) {
		if(document.getElementById(id) != null) {
			return true;
		} else {
			return false;
		}
	} else if (document.all) {
		return document.all[id];
	}
	return false;
}

var tmg;

function tmg(selector, context) {
	return new tmg.fn.init(selector, context);
}

tmg.prototype = tmg.fn = {
	init : function(selector, context) {
		
		// old implementation / remove when using sizzle
		// context = context || document;
		
		/* for debugging */
		this.selector = selector;
		this.context = context;
		
		if (selector && selector.nodeName) {
			this[0] = selector;
			this.length = 1;
		} else if (typeof selector == 'function') {
			tmg.bindReady ( selector );
		} else if ( ! selector) {
			this[0] = document;
			this.length = 0;
		} else if (typeof selector != 'string') {
			var counter = 0;
			selector = tmg.makeArray(selector);
			for (obj in  selector) {
				if (selector [ obj ] != undefined) {
					this[counter] = selector[obj];
					counter++;
				}
			};
			this.length = counter;
		} else
			this.find(selector, context); // 173 ms total load time FF3
		return this;
	},
	next : function() {
		return tmg(tmg.nodes.next(this[0]));
	},
	prev : function() {
		return tmg(tmg.nodes.prev(this[0]));
	},
	parent : function() {
		return tmg(tmg.nodes.parent(this[0]));
	},
	parents : function(selector) {
		result = tmg(tmg.nodes.parents(this[0]));
		if (selector)
			return result.find(selector);
		return result;
	},
	children : function() {
		return tmg(tmg.nodes.children(this[0]));
	},
	siblings : function(){
		return tmg(tmg.nodes.siblings(this[0]));
	},
	css : function(key, val){
		if (typeof key == 'string') {
			if (val != undefined) {
				this.each(function(obj){
					if (obj.style) obj.style[key] = val;
				});
			} else if (this[0] && this[0].style) {
				return tmg.currentCss(this[0], key);
			} else {
				return '';
			}
		} else if (typeof key == 'object') {
			alert('not supported yet');
		} else if (key == undefined && this[0]) {
			return this[0].style;
		}
		return this;
	},
	getElementsByClassName : function(classNames, context){
		var result = [];
		if (context) {
			if (!context.getElementsByClassName) {
				var children = IE ? context.all : context.getElementsByTagName('*');
				for (child in children)
					if (tmg.className.has(children[child], classNames))
						result[result.length] = children[child];
			} else result = context.getElementsByClassName(classNames);
		}
		return result;
	},
	find : function(selector, context) {
		
		context = context || this[0];
		
		// sizzle way
		var result = Sizzle(selector, context); // 165 ms total load time FF3
		for (var walk = 0; walk < result.length; walk++)
			this[walk] = result[walk];
		this.length = result.length;
		
		return this;
			
		// old implementation
		if (typeof selector == 'string' && context) {
			if (selector.charAt(0) == '.') {
				var tags = this.getElementsByClassName(selector.substring(1), context);
				for (var walk = 0; walk < tags.length; walk++) this[walk] = tags[walk];
				this.length = tags.length;
			} else if (selector.charAt(0) == '#') {
				this[0] = context.getElementById(selector.substring(1));
				this.length = this[0] ? 1 : 0;
			} else {
				var tags = context.getElementsByTagName(selector);
				for (var walk = 0; walk < tags.length; walk++)	this[walk] = tags[walk];
				this.length = tags.length;
			}
		}
		
		return this;
	},
	isXMLDoc: function( ) {
		return this[0].documentElement && !this[0].body ||
			this[0].tagName && this[0].ownerDocument && !this[0].ownerDocument.body;
	},
	checked : function(value) {
		if (this[0]) {
			if (value != undefined) this[0].checked = value;
			else return this[0].checked;
		}
		return this;
	},
	contents : function() {
		
		if (this[0])
			return tmg(tmg.nodes.contents(this[0]));
		return this;
	},
	value : function(value){
		if (this[0]) {
			if (value != undefined) {
				this[0].value = value;
				return this;
			} else return this[0].value;
		}
	},
	hover : function(over, out) {
		
		function handleHover(e) {
			var target = e.relatedTarget;
			
			// go up the tree to find the common ancestor
			while ( target && target != this )
				target = target.parentNode ? target.parentNode : this;
			
			return target == this ? false : (e.type == "mouseover" ? over : out).apply(this, [e]);
		}
		
		return this.mouseover(handleHover).mouseout(handleHover);
	},
	gt : function(index){
		var result = [];
		this.each(function(obj, i){
			if (i > index) result[result.length] = obj;
		});
		return tmg(result);
	},
	removeClass : function(classNames) {
		this.each(function(obj){
			tmg.className.remove(obj, classNames)
		})
		return this;
	},
	addClass : function(classNames) {
		this.each(function(obj){
			tmg.className.add(obj, classNames);
		});
		return this;
	},
	toggleClass : function(classNames, newClass){
		if (this[0]) {
			if (tmg.className.has(this[0], classNames)) {
				tmg.className.remove(this[0], classNames);
				if (newClass != undefined) tmg.className.add(this[0], newClass); 
			} else {
				tmg.className.add(this[0], classNames);
				if (newClass != undefined) tmg.className.remove(this[0], newClass);
			}
		}
		return this;
	},
	hasClass : function(classNames){
		return tmg.className.has(this[0], classNames);
	},
	isVisible : function() {
		if (this[0])
			return this.css('display') != 'none' && ! tmg.className.has(this[0], 'hidden');
		return this;
	},
	animate : function(what, callback) {
		this[0].id = Math.random();
		this.css('display', 'block');
		window.temp = new animation(this[0].id, { height:100, horizontal:false, vertical:true, 'callback':callback});
		temp.toggleDiv('slow');
		return this;
	},
	show : function(how, callback) {
		this.each(function(obj){
			if (how == 'slow') tmg(obj).animate('height', callback);
			else tmg(obj).css('display', 'block').removeClass('hidden');
		});
		return this;
	},
	hide : function(how, callback) {
		this.each(function(obj){
			if (how == 'slow') tmg(obj).animate('height', callback);
			else tmg(obj).css('display', 'none');
		});
		return this;
	},
	toggle : function(how, callback) {
		this.each(function(obj){
			if (tmg(obj).isVisible()) tmg(obj).hide(how, callback);
			else tmg(obj).show(how, callback);
		});
		return this;
	},
	enabled : function(newValue) {
		if (newValue != undefined) {
			this.each(function(obj, i){
				obj.disabled = ! newValue;
				if (newValue == false) tmg.className.add(obj, 'disabled');
				else tmg.className.remove(obj, 'disabled');
			});
		} else {
			return ! this[0].disabled;
		}
		return this;
	},
	on : function(trigger, fn) {
		this.each(function(obj){
			if ( ! fn) {
				
			} else
				tmg.event.add(obj, trigger, fn);
		});
		return this;
	},
	get : function(id){
		if (this && this[id])
			return tmg(this[id]);
		return this;
	},
	first : function(){
		return this.get(0);
	},
	last : function() {
		return this.get(this.length - 1);
	},
	load : function(fn) { return this.on('load', fn); },
	error : function(fn) { return this.on('error', fn); },
	mouseup : function(fn) { return this.on('mouseup', fn); },
	mousedown : function(fn) { return this.on('mousedown', fn); },
	mousemove : function(fn) { return this.on('mousemove', fn); },
	mouseover : function(fn) { return this.on('mouseover', fn); },
	mouseout : function(fn) { return this.on('mouseout', fn); },
	click : function(fn) { return this.on('click', fn); },
	blur : function(fn) { return this.on('blur', fn); },
	change : function(fn) { return this.on('change', fn); },
	submit : function(fn) { return this.on('submit', fn); },
	keydown : function(fn) {return this.on('keydown', fn); },
	keyup : function(fn) {return this.on('keyup', fn); },
	each : function(fn) {
		tmg.each(tmg.makeArray(this), fn);
	},
	invert : function() {
		var result = tmg.invertArray(tmg.makeArray(this));
		for (var walk = 0, len = result.length; walk < len; walk++)
			this[walk] = result[walk];
		return this;
	},
	link : function(url) {
		this.each(function(obj){
			if (obj.nodeType == 1) {
				if (obj.tagName == 'INPUT') {
					obj.onclick = function(){
						window.location = url;
					}
				} else {
					var node = document.createElement('a');
					node.href = url;
					node.innerHTML = obj.innerHTML;
					obj.parentNode.replaceChild(node, obj);
				}
			}
		});
		return this;
	},
	nodeName : function() {
		return tmg.nodes.name(this[0]);
	},
	src : function(url) {
		if (this[0]) {
			if (url) this[0].src = url;
			else return this[0].src || this.attr('src');
		}
		return this;
	},
	html : function(val){
		if (val != undefined) {
			this.each(function(obj){
				obj.innerHTML = val;
			});
			return this;
		}
		return this[0] ? this[0].innerHTML : '';
	},
	text : function(){
		var result = '';
		if (this[0]) {
			return tmg.nodes.text(this[0]);
		}
		return '';
	},
	attr : function(id, val){
		var result;
		
		// use isXMLDoc for IE?
		if (this[0])
			if (val != undefined) {
				this.each(function(obj){
					this[0][id] = val;
					result = this;
				});
			} else if (this[0].hasAttribute) {
				result = this[0].hasAttribute(id);
				result = result ? this[0].getAttribute(id) : '';
			} else 	if (result = this[0].getAttributeNode(id)) {
			//} else if (this[0].getAttributeNode && (result = this[0].getAttributeNode(id))) {
				result = result ? result.nodeValue : '';
			}
		
		return result || '';
	},
	emptyArray : function() {
		for (var walk = 0; walk < this.length; walk++) {
			this[walk] = obj[walk];
		}
		this.length = 0;
	}
}
tmg.fn.init.prototype = tmg.fn;

tmg.extend = tmg.fn.extend = function() {
	// copy reference to target object
	var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options;

	// Handle a deep copy situation
	if ( target.constructor == Boolean ) {
		deep = target;
		target = arguments[1] || {};
		// skip the boolean and the target
		i = 2;
	}

	// Handle case when target is a string or something ( possible in deep copy ) 
	if ( typeof target != "object" && typeof target != "function" ) 
		target = {};

	// extend tmg itself if only one argument is passed
	if ( length == i ) {
		target = this;
		--i;
	}

	for ( ; i < length; i++ ) 
		// Only deal with non-null/undefined values
		if ( ( options = arguments[ i ] ) != null ) 
			// Extend the base object
			for ( var name in options ) {
				var src = target[ name ], copy = options[ name ];

				// Prevent never-ending loop
				if ( target === copy ) 
					continue;

				// Recurse if we're merging object values
				if ( deep && copy && typeof copy == "object" && !copy.nodeType ) 
					target[ name ] = tmg.extend ( deep, 
						// Never move original objects, clone them
						src || ( copy.length != null ? [ ] : { } ) 
					, copy );

				// Don't bring in undefined values
				else if ( copy !== undefined ) 
					target[ name ] = copy;

			}

	// Return the modified object
	return target;
};

tmg.extend({
	enrich : function(original, options) {
	
		original = original || {};
		options = options || {};
		
		for (var option in options) {
			if (options[option] === 'true') options[option] = true;
			if (options[option] === 'false') options[option] = false;
			original[option] = options[option];
		}
		
		return original;
	},
	makeObject : function(string){
		var result = {};
		tmg.each(string.split('?').pop().split('&'), function( obj ){
			var pair = obj.split('=');
			result[pair.shift()] = pair.shift();
		})
		return result; 
	},
	each : function(objects, fn){
		for (i in objects) fn(objects[i], i);
		return this;
	},
	currentCss : function(elm, key){
		var result;
		if (elm.currentStyle)
			result = elm.currentStyle[key];
		else if (window.getComputedStyle)
			result = document.defaultView.getComputedStyle(elm, null).getPropertyValue(key);
		return result;
	},
	trim : function( text ) {
		return (text || "").replace( /^\s+|\s+$/g, "" );
	},
	each : function(objects, fn){
		for (i in objects) fn(objects[i], i);
		return this;
	},
	invertArray : function(array) {
		var result = [];
		
		if (array && array[0])
			for (var walk = 0; walk < array.length; walk++)
				result[array.length - (walk + 1)] = array[walk];
		
		return result;
	},
	makeArray : function(obj){
		var result = [];
		for (var walk = 0; walk < obj.length; walk++) {
			result[walk] = obj[walk];
		}
		return result;
	},
	inArray : function(elem, array){
		for ( var i = 0, length = array.length; i < length; i++ )
			if ( array[ i ] === elem )
				return i;

		return -1;
	}
});

var userAgent = navigator.userAgent.toLowerCase();

tmg.browser = {
	version: ( userAgent.match ( /.+ ( ?:rv|it|ra|ie ) [\/: ] ( [\d.]+ ) / ) || [] ) [1],
	safari: /webkit/.test ( userAgent ) ,
	opera: /opera/.test ( userAgent ) ,
	msie: /msie/.test ( userAgent ) && !/opera/.test ( userAgent ) ,
	mozilla: /mozilla/.test ( userAgent ) && !/ ( compatible|webkit ) /.test ( userAgent ) 
};

tmg.extend ( {
	isReady : false,
	readyList : [],
	readyBound : false,
	bindReady : function ( fn ) {
		
		if ( ! tmg.isReady ) tmg.readyList[tmg.readyList.length] = fn;
		
		if ( tmg.readyBound ) return;
		else {
			tmg.readyBound = true;
			tmg.readyCheck ();
		}
	},
	ready : function() {
		
		if ( ! tmg.isReady ) {
			//console.time ( 'Dom Ready Events' );
			tmg.isReady = true;
			
			//console.group ( 'DOM Ready Events' ) 
			for ( var i in tmg.readyList ) tmg.readyList[i] ();
			//console.groupEnd () 
			
			//console.timeEnd ( 'Dom Ready Events' );
			//console.timeEnd ( 'From start till ready' );
			if ( tmg.profilingMode ) tmg.warn ( 'Profiling takes a lot of time and should only be used in development environments.' );
		}
	},
	readyCheck : function() {
		// Mozilla, Opera ( see further below for it ) and webkit nightlies currently support this event
		if ( document.addEventListener && !tmg.browser.opera ) 
			// Use the handy event callback
			document.addEventListener ( "DOMContentLoaded", tmg.ready, false );
		
		// If IE is used and is not in a frame
		// Continually check to see if the document is ready
		if ( tmg.browser.msie && window == top ) ( function() {
			if ( tmg.isReady ) { 
				return;
			}
			try {
				// If IE is used, use the trick by Diego Perini
				// http://javascript.nwbox.com/IEContentLoaded/
				document.documentElement.doScroll ( "left" );
			} catch ( error ) {
				setTimeout ( arguments.callee, 0 );
				return;
			}
			// and execute any waiting functions
			tmg.ready ();
		} ) ();
		
		if ( tmg.browser.opera ) 
			document.addEventListener ( "DOMContentLoaded", function() {
				if ( tmg.isReady ) return;
				for ( var i = 0; i < document.styleSheets.length; i++ ) 
					if ( document.styleSheets[i].disabled ) {
						setTimeout ( arguments.callee, 0 );
						return;
					}
				// and execute any waiting functions
				tmg.ready ();
			}, false );
	
		if ( tmg.browser.safari ) {
			var numStyles;
			 ( function() {
				if ( tmg.isReady ) return;
				if ( document.readyState != "loaded" && document.readyState != "complete" ) {
					setTimeout ( arguments.callee, 0 );
					return;
				}
				if ( numStyles === undefined ) 
					numStyles = tmg ( "style, link[rel=stylesheet]" ) .length;
				if ( document.styleSheets.length != numStyles ) {
					setTimeout ( arguments.callee, 0 );
					return;
				}
				// and execute any waiting functions
				tmg.ready ();
			} ) ();
		}
		
		
		// A fallback to window.onload, that will always work
		tmg.event.add ( window, "load", tmg.ready );
	}
} );


tmg.extend ( {
	event : {
		add : function ( elem, type, handle ) {
			if ( elem.nodeType == 3 || elem.nodeType == 8 )
				return;
	
			// For whatever reason, IE has trouble passing the window object
			// around, causing it to be cloned in the process
			if ( tmg.browser.msie && elem.setInterval )
				elem = window;

			if ( elem.addEventListener ) {
				elem.addEventListener ( type, handle, false );
			} else if ( elem.attachEvent ) {
				elem.attachEvent ( "on" + type, function(event){
					event.target = event.srcElement; 
					var returnvalue = handle.call(elem, event);
					if (returnvalue == false)
						event.returnValue = false;
				} );
			} else {
				obj['on' + type] = handle;
			}
		}
	}
} );
tmg.className = {
	remove : function(elem, classNames) {
		var result = '', foundToken = false;
		if (elem != undefined && elem.className) {
			var classes = elem.className.split(' ');
			for (var walk = 0, len = classes.length; walk < len; walk++) {
				if (classes[walk] != classNames) result += (result == '' ? '' : ' ') + classes[walk];
				else foundToken = true;
			}
			elem.className = result;
		}
		return foundToken;
	},
	add : function(elem, classNames) {
		if (elem != undefined)
			if( ! tmg.className.has(elem, classNames) ) {
				elem.className += (elem.className == '' ? '' : ' ') + classNames;
				return true;
			}
		return false;
	},
	has : function(elem, classNames) {
		if (elem != undefined && elem.className && classNames) {
			var classes = elem.className.split(' ');
			for (cl in classes)
				if (classes[cl] == classNames) return true;
		} 
		return false;
	}
}
tmg.nodes = {
	name : function(el) {
		return typeof(el)!=undefined && el && el.nodeName ? el.nodeName.toLowerCase() : '';
	},
	contents : function(el){
		result = el;
		if (el) {
			if (tmg.nodes.name(el) == 'iframe') {
				if (el.contentDocument) { // FF
					result = el.contentDocument;
				} else { // IE
					result = el.contentWindow.document;
				}
			} else {
				result = tmg.makeArray(el.childNodes)
			}
			//return tmg.nodes.name(el) == 'iframe' ? el.contentDocument || el.contentWindow.document : tmg.makeArray(el.childNodes);
		}
		return result;
	},
	next: function(el) {
		if (el && el.nextSibling) {
			if (el.nextSibling.nodeType == 1) return el.nextSibling;
			else el = tmg.nodes.next(el.nextSibling);
		}
		return el;
	},
	prev : function(el) {
		if (el && el.previousSibling) {
			if (el.previousSibling.nodeType == 1) return el.previousSibling;
			else el = tmg.nodes.prev(el.previousSibling);
		}
		return el;
	},
	siblings : function(el){
		var result = [];
		var counter = 0;
		var parent = tmg.nodes.parent(el);
		var siblings = tmg.nodes.children(parent);
		
		for (var walk = 0; walk < siblings.length; walk++) {
			if (siblings[walk] != el) {
				result[counter] = siblings[walk];
				counter++;
			}
		}
		return result;
	},
	children : function(el){
		var result = [];
		var counter = 0;
		
		if (el.childNodes) {
			for (var walk = 0; walk < el.childNodes.length; walk++) { 
				if (el.childNodes[walk].nodeType == 1) {
					result[counter] = el.childNodes[walk];
					counter++;
				}
			}
		}
		return result;
	},
	parent : function(el) {
		if (el && el.parentNode)
			return el.parentNode;
		return document;
	},
	parents : function(el) {
		var result = [];
		while(el.tagName != 'HTML' && (el = tmg.nodes.parent(el)))
			result[result.length] = el;
		return result;
	},
	text : function(el) {
		var result = '';
		tmg.each(tmg.makeArray(el.childNodes), function(obj, i) {
			if (obj && obj.nodeType) {
				if (obj.nodeType == 1) {
					result += tmg.nodes.text(obj);
				} else {
					result += obj.nodeValue == null ? '' : obj.nodeValue;
				}
			}
		});
		return result;
	},
	text : function(el) {
		var result = '';
		tmg.each(tmg.makeArray(el.childNodes), function(obj, i) {
			if (obj && obj.nodeType) {
				if (obj.nodeType == 1) {
					result += tmg.nodes.text(obj);
				} else {
					result += obj.nodeValue == null ? '' : obj.nodeValue;
				}
			}
		});
		return result;
	}
};

(function(){

	var opnieuwbeginnen="<a href='/speurder/beginopnieuw/' title='ga terug naar de Homepage en begin opnieuw met het maken van uw Advententie'>begin opnieuw</a>";
	var defaulterrormsgs = {
		'-1' : '', // NOERROR
		2 : 'U heeft characters gebruikt, die door ons systeem niet worden herkend. Alle letters, alle cijfers en gangbare interpunctie wordt door ons systeem ondersteund. Zou u uw tekst willen aanpassen?', // HASERRONEOUSCHARS
		3 : 'Het lijkt erop dat u woorden heeft gebruikt die breder zijn dan 1 kolom in de krant. Zou u uw tekst willen aanpassen en kleinere woorden willen gebruiken?', // HASLONGWORDS
		5 : 'De Speurder is te lang. Zou u uw Speurder korter willen maken?', // ISTOOLONG
		6 : 'Het lijkt erop dat u woorden heeft gebruikt die breder zijn dan 1 kolom in de krant. Zou u uw tekst willen aanpassen en kleinere woorden willen gebruiken?', // HASLONGELEMENTS
		8 : 'Het bestand \'%\' kan niet worden gevonden', // FILENOTEXISTS
		9 : 'Het afbeeldingsformaat \'%\' wordt niet ondersteund.', // FORMATNOTSUPPORTED
		15 : '???', // ISTOOSHORT
		16 : 'Er heeft een ongeldige bewerking plaats gevonden op de server.', // ILLEGALARGUMENT
		17 : 'Het aantal millimeters van uw Advertentie is te groot.', // ADVERTTOOHEIGH
		18 : 'Het aantal millimeters van uw Advertentie is te klein.', // ADVERTTOOLOW	
		19 : 'Kan bewerking niet voltooien, er mist een argument.', // MISSINGALARGUMENT
		20 : 'Uw sessie is verlopen, u dient opnieuw te beginnen met het maken van uw advertentie.', // SESSIONTIMEOUT
		21 : 'Voor deze actie is het vereist dat u bent ingelogd.', // NOUSERFOUND
		22 : 'Er is een ongeldig attribuut aangetroffen.', // INVALIDARGUMENT
		23 : 'Het bestand waar uw afbeelding in opgeslagen zit, lijkt stuk te zijn. Probeert u het gaarne opnieuw met een andere afbeelding. ', // FILECONVERSIONERROR
		24 : 'Er is een onbekende fout opgetreden', // UNKOWNERROR
		25 : 'Er heeft een timeout plaatsgevonden tijdens het converteren van uw afbeelding.', // FILECONVERIONTIMEOUT
		26 : 'Er is een fout opgetreden bij het lezen van een bestand.', // FILEREADERROR
		27 : 'Er is een fout opgetreden bij het opslaan van een bestand.', // FILEWRITEERROR
		28 : 'Het door u opgestuurde bestand is te groot. Bestanden mogen maximaal 10 megabyte groot zijn.', // FILEUPLOADSIZE_MAXERROR
		29 : 'U bent al ingelogd.', // USER_INGELOGD
		30 : 'U bent niet ingelogd.', // USER_NIET_INGELOGD
		31 : 'De gebruikersnaam is al in gebruik.', //USER_BESTAAT_AL
		32 : 'Er is een fout opgetreden in de Prijsberekening service (PE).', //PE_ERROR
		33 : 'Er zijn geen zoekresultaten.', //NO_RESULTS
		34 : 'Er zijn te veel zoekresultaten. Uw zoekterm is te abstract.', // TOO_MANY_RESULTS
		35 : 'Onbekend Rubriek-id.',	// UNKNOWN_RUBRIEK_ID
		36 : 'Advertentietekst voldoet niet (b.v. woord > 200 karakters gebruikt.).', // ADVERT_CONSTRAINTERROR
		37 : 'Wacht a.u.b. todat de huidige actie is afgerond.', // COMMANDSTATE_ERROR
		38 : 'U heeft geen toegang tot deze order. Vul eerst aan de rechterzijde uw gebruikersnaam en wachtwoord in om in te loggen.', //	NOT_AUTHORIZED_FOR_ORDER
		39 : 'Er heeft een time-out plaatsgevonden bij het genereren van uw materiaal.', // BTWRAPPER_CONNECTION_FAILED
		40 : 'Er is een communicatiefout opgetreden tijdens de communicatie met de server.', // GENERAL_COMMUNICATION_ERROR
		41 : 'Uw actiecode is niet geldig.' // ACTIECODE_NOT_VALID
		
	}      

	
	tmg.extend({
		getError : function(id, arguments) {
			
			var result = defaulterrormsgs[id ? id : tmg.errors.UNKNOWNERROR];
			if (typeof arguments == 'string')
				arguments = [ arguments ];
			
			for (var arg in arguments)
				result = result.replace('%', arguments[arg]);
			
			return result;
		},
		errors : {
			NOERROR : -1,
			HASERRONEOUSCHARS : 2,
			HASLONGWORDS : 3,
			ISTOOLONG : 5,
			HASLONGELEMENTS : 6,
			FILENOTEXISTS : 8,
			FORMATNOTSUPPORTED : 9,
			ISTOOSHORT : 15,
			ILLEGALARGUMENT : 16,
			ADVERTTOOHEIGH : 17,
			ADVERTTOOLOW : 18,
			MISSINGALARGUMENT : 19,
			SESSIONTIMEOUT : 20,
			NOUSERFOUND : 21,
			INVALIDARGUMENT : 22,
			FILECONVERSIONERROR : 23,
			UNKOWNERROR : 24,
			FILECONVERIONTIMEOUT : 25,
			FILEREADERROR : 26,
			FILEWRITEERROR : 27,
			FILEUPLOADSIZE_MAXERROR : 28,
			USER_INGELOGD : 29,
			USER_NIET_INGELOGD : 30,
			USER_BESTAAT_AL : 31,
			PE_ERROR : 32,
			NO_RESULTS : 33,
			TOO_MANY_RESULTS : 34, 
			UNKNOWN_RUBRIEK_ID : 35, 
			ADVERT_CONSTRAINTERROR : 36,
			COMMANDSTATE_ERROR : 37,
			NOT_AUTHORIZED_FOR_ORDER : 38,
			BTWRAPPER_CONNECTION_FAILED : 39,
			GENERAL_COMMUNICATION_ERROR : 40,
			ACTIECODE_NOT_VALID : 41
		}
	});

	tmg.extend({
		loadJson : function (uri, data, callback, synchronous, options){
			
			options = options || {};
			
			if (synchronous){
				var text = defaultHandleRequest(uri, data, true);
				try {
					eval( 'var json = ' + text);
				} catch( e ) {
					callback( { error:tmg.errors.GENERAL_COMMUNICATION_ERROR } );
					return;
				}
				callback(json);
			} else {
				asyncHandleRequest(uri, data, {
					'onSuccess': function(req, xml, text) {
						try {
							eval( 'var json = ' + text);
						} catch ( e ) {
							callback( { error:tmg.errors.GENERAL_COMMUNICATION_ERROR } );
							return;
						}
						callback(json);
					},
					notrack : options.notrack
				});
			}
		},
		loadSynchronisedJson: function(uri, data, callback){
			tmg.loadJson(uri, data, callback, true);
		}
	});
	tmg.fn.extend({
		loadWidgetData : function(information, data, callback, options){
			
			var self = this;
			
			tmg.loadJson('/servlet/CommandServlet?command=userinfocommand&get=' + information, data, function(json){
				
				if (json.error)
					setError(tmg.getError(json.error))
					
				var len = json.length;
				var items = json[information];
				callback(items, self);
			}, false, options);
			
			return this;
		}
	});
})();

function trackPage(url) {
	//if (typeof(pageTracker) != "undefined" && url!='') {
	//	pageTracker._trackPageview(url);
	//}
}

function findAnayticsPageName(url) {

	if (url.indexOf('getmaterialmillimeters')>-1 ) {
		return ('/ajax/' + ( tmg.makeObject( url ).command || url ) ).replace(/\/\//g, '/');
	} else {
		return ('');
	}
	
}


function each(el, fn) {
	tmg.each(el, fn);
}
/* the each function needs a functionname which it will perform, it passes two variables to the called 
   function; ob which is the value of the array-key and i which is the iterator */
/* use of each function: arrayName.forEach(functionName);
   example: ['hi', 'bye'].each(alert); */
//Array.prototype.each = function(func){
//	for (var i=0; ob=this[i]; i++) { alert(func); func(ob, i); } 
//};

/* if you want to use an array instead of an object collection */
function collection(col){
	return tmg.makeArray(col);
}

/* this function removes one ocurrence of the toRemove value in the given array */
/* we probably want to prototype this, and maybe return the array */
function removeFromArray ( array, toRemove ) {
	
	/* walk through the array */
	for ( walk = 0; walk < array.length; walk++ ) {
		
		/* delete the entry if it is found */
		if ( array[walk] == toRemove ) {
			array[walk] = array[array.length-1];
			
			/* we asume the array only has one ocurrence of toRemove */
			break;
		}
	}
	
	/* trim the length of the array */
	theArr.length = theArr.length-1;
}

/* this function finds a value in a given array */
/* we probably want to prototype this */
function inArray(array, toFind) {
	return tmg.inArray(toFind, array) >= 0;
}


/* this function add's a value to the end of an array */
function addToArray(array, add) {
	array[array.length] = add;
}

/* this function returns the length of an array when array.length doesn't work,
   this can be the case when u use strings as keys for the array */
function arrayLength(array) {
	var counter = 0;
	for (i in array) counter++;
	return counter-1;
}

/* this function parses a float value */
/* TODO: do we need this ? */
function getFloat(string) {
	return parseFloat(string);
}

/* this function overrides the parseInt function because of the octal bug */
/* TODO: do we want to override parseInt because of octal bug ? */
//function parseInt(string) {
//	return parseFloat(string);
//}

/* this function checks if an element is locked */
function isLocked(id) {
	if (lockArr[id] == true) {
		return true;
	} else {
		return false;
	}
}

/* function for locking an element, this doesn't realy lock it, you need to check for it yourself using the isLocked function */
function lock(id) {
	lockArr[id] = true;
}

/* this function releases the lock of an element */
function unlock(id) {
	lockArr[id] = false;
}

/* COMMENT */
function getNode(number) {
	return (IE) ? number : (number * 2) +1;
}

/* COMMENT */
function ucFirst(string) {
	return string.substring(0, 1).toUpperCase() + string.substring(1); 
} 

/* COMMENT */
function getUniqueNode(xml, tagname) {
	
	var result = undefined;
	
	var node = xml.getElementsByTagName(tagname)[0];
	if (node != undefined) {
		var subnode = node.childNodes[0];
		if (subnode != undefined) result = subnode.nodeValue;
		else result = node.nodeValue;
	}
	return result;
}

/* create a new div element, set it's class and id and return it */
function newDiv(id, divClass) {
	
	var div = document.createElement('div');
	div.setAttribute('id', id);
	//div.setAttribute('class', divClass);
	div.className = divClass;
	return div;
}

/* this function initializes a xmlHttpRequest and returns it */
/* TODO: this function is not tested with other browsers then FF 1.0+ IE 5.55+ and Safari 3+, does Opera work for example ? */
function initRequest() {
	var xmlHttp;
	
	/* this is for FF (and others ?) */
	if (window.XMLHttpRequest) xmlHttp = new XMLHttpRequest();
	/* this is for IE */
	else if (window.ActiveXObject) xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	/* if clients browser doesn't support xmlHttp */
	else alert('Kan geen xmlHttp verbinding maken, neem contact op met de servicedesk.');
	
	return xmlHttp;
}

function getWeekday() {
}

function getWeekdayInt() {
}

function getDayOfWeekByWeekday(longWeekday) {
	var shortWeekday = 0;
	
	switch (longWeekday.toLowerCase()) {
		case 'maandag'   : shortWeekday = 1; break;
		case 'dinsdag'   : shortWeekday = 2; break;
		case 'woensdag'  : shortWeekday = 3; break;
		case 'donderdag' : shortWeekday = 4; break;
		case 'vrijdag'   : shortWeekday = 5; break;
		case 'zaterdag'  : shortWeekday = 6; break;
		case 'zondag'    : shortWeekday = 7; break;
		default          : break;
	}
	return shortWeekday;
}

function getShortWeekdayByWeekday(longWeekday) {
	var shortWeekday = '';
	
	switch (longWeekday.toLowerCase()) {
		case 'maandag'   : shortWeekday = 'ma'; break;
		case 'dinsdag'   : shortWeekday = 'di'; break;
		case 'woensdag'  : shortWeekday = 'wo'; break;
		case 'donderdag' : shortWeekday = 'do'; break;
		case 'vrijdag'   : shortWeekday = 'vr'; break;
		case 'zaterdag'  : shortWeekday = 'za'; break;
		case 'zondag'    : shortWeekday = 'zo'; break;
		default          : break;
	}
	return shortWeekday;
}
function getShortWeekdayByInt() {
}


/* COMMENT */
function setError(message) {
	hideModal();
	var element = get('errorDiv');
	message = '<div class="right" style="font-weight:normal;"><a onclick="clearError();" href="javascript:void(0);" title="verberg deze melding">verberg</a></div>' + message;
	setHtml(element , message);
	removeClass(element, 'hidden');
	display(element);
	window.location = '#';
}

/* COMMENT */
function getNiceDayOfWeek(dayOfWeek) {
	 
	return dayOfWeek === 0 ? 7 : dayOfWeek;
}

/* COMMENT */
function clearError() {
	var element = get('errorDiv');
	setHtml(element , '');
	setClass(element, 'hidden');
	noDisplay(element);
}

function trim(value) {
	value = value.replace(/^\s+/,'');
	value = value.replace(/\s+$/,'');
	return value;
}    


/* this function handles a post ajax call and checks the error, status and message returned */
/* caller needs to have a div called 'errordiv' in its page */
/* TODO: this isn't reusable, maybe split the first and second part */
/* TODO: this function is not tested with other browsers then FF 1.0+ IE 5.55+ and Safari 3+, does Opera work for example ? */
function defaultHandleRequest(url, postdata, textonly) {  
	
	/* add a timestamp to the postdata string */
	/* TODO: BECAUSE ??? */
	postdata +=  "&timestamp=" + new Date().getTime();
	
	/* initialize the request */
	/* TODO: the url which is passed is bogus */
	var req = initRequest();
	
	/* if req could not be initialized */
	if (req == null) return false;

	/* open the request, set the headers and send the postdata */
	req.open("POST", url, false);
	req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8;');
	req.send(postdata);

	if (typeof findAnayticsPageName == "function") {
		var analyticspagename=findAnayticsPageName ( url );
		if (analyticspagename!='') {
			trackPage( analyticspagename );
		}
	}
	/* get and return the xml from the request */
	return textonly ? req.responseText : req.responseXML;
}


// Asynchronous ajax handler
// Example:
//
//	var ok = asyncHandleRequest(url, postdata, {
//		'onSuccess' : function(r, xml, txt) {
//			Do something nice with the returned xml or txt
//		},
//		'onFailure' : function(r, status, statusText) {
//			Do something with the error, status is http status code
//		},
//  Optionally you can set a timeout and a cancel handler
//		'timeoutMilliSecs' : 4000,
//		'onCancel'  : function(r) {
//			alert('Cancelled');
//		},
//	Optionally you can provide start/finish functions, called
//	before starting the rest and after ending the request (ending
//	meaning succesfully, erroroneously or timeout)
//		'onStart' : function() {
//		},
//		'onFinish' : function() {
//		}
//	});

function asyncHandleRequest(url, postdata, options) {
	
	options = options || {};

	/* add a timestamp to the postdata string */
	/* TODO: BECAUSE ??? */
	postdata += "&timestamp=" + new Date().getTime();
	
	/* initialize the request */
	/* TODO: the url which is passed is bogus */
	var req = initRequest();
	
	/* if req could not be initialized */
	if (req == null) return false;
	
	/* Register the event handler */
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (options['timeoutID'])
				clearTimeout(options['timeoutID']);

			if (req.status == "200") {
				if (typeof options['onSuccess'] == 'function')
					options['onSuccess'](req, req.responseXML, req.responseText);
			} else {
				if (typeof options['onFailure'] == 'function')
					options['onFailure'](req, req.status, req.statusText);
			}

			if (typeof options['onFinish'] == 'function')
				options['onFinish']();
		}
	};

	if (typeof options['onStart'] == 'function')
		options['onStart']();

	/* open the request, set the headers and send the postdata, flagging for async */
	req.open(options.get ? "GET" : "POST", url, true);	
	req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8;');
	req.send(postdata);

    if (options.timeoutMilliSecs) { 
        function cancelTimer() {
            var _req;
            var _options;

            function asyncCancelRequest() {
                _req.onreadystatechange = function() {}

                if (typeof _options['onCancel'] == 'function')
                    _options['onCancel'](req);

				if (typeof _options['onFinish'] == 'function')
					_options['onFinish']();
            }

            this.startTimer = function(req, options) {
                _req = req;
                _options = options;
                options['timeoutID'] = setTimeout(asyncCancelRequest, options.timeoutMilliSecs);
            }
        }

        var cancelTimerObj = new cancelTimer();
        cancelTimerObj.startTimer(req, options);
	}
    
    if ( ! options.notrack )
    	trackPage( findAnayticsPageName ( url ) );

}


/***************************************************/
/*        for html elements and animations         */
/***************************************************/

/* change the class in a class-string of an element */
function changeClass(element, from, to) {
	if (element != null && element.className != null ) {
		setClass(element, element.className.replace(from, to));
	}
}

/* a short way to set a class, remember elements can have multiple classes. if you use this it overrides
   the other classes, if you don't want to do this use the addClass function*/
function setClass(element, newClass) {
	if (element != null) {
		element.className = newClass;
	}
}

function switchClass(element, value) {
	
	if (element != null) {
		if (hasClass(element, value)) 
			removeClass(element, value);
		else 
			addClass(element, value);
	}
}


/* add's a class to an element, if you want de override the classes element may already have use 
   the setClass function instead */
function addClass(element, className) {
	tmg(element).addClass(className);
}

/* remove one class from an alement */
function removeClass(element, className) {
	return tmg(element).removeClass(className);
}

/* check if an element has the given class */
function hasClass(el,cl){
	return tmg(el).hasClass(cl);
}

/* check if an element has the given class */
function hasClassOld(element, className) {
	return hasClass(element, className);
}

/* a short way to display an element, this is different from the makeVisible function which sets the visibility to '' */
function display(element, how) {
	if (how === true) how = 'block';
	else if (how === false) how = 'none';
	if (element) {
 		element.style.display = (how !== undefined) ? how : '';
		removeClass(element, 'hidden');
	} else {
		debug('element kan niet verborgen/weergegeven worden');
	}
}

function toggle(element) {
	if (element != undefined && element.style) {
		
		if (element.style.display == 'none' || hasClass(element, 'hidden')) {
			element.style.display = 'block';
			removeClass(element, 'hidden');
		} else {
			element.style.display = 'none';
		}
	}
	return element;
}

/* variants for id and class */
function displayId(id, how) {
    var element = get(id);
    display(element, how);
}
function displayClass(clas, how) {
    tmg('.' + clas).css('display', how);
}

/* a short way to hide an element, this is different from the makeInvisible function which sets the visibility to hidden */
function noDisplay(element) {
	if (element != null) {
		element.style.display = 'none';
	}
}
function noDisplayId(id) {
    displayId(id, 'none');
}
function noDisplayClass(clas) {
    displayClass(clas, 'none');
}

/* function to make an element visible, this is different from the display() function which sets the style.display property to '' */
function makeVisible(element) {
	if (element && element.style)
		element.style.visibility = '';
}

/* function to make an element invisible, this is different from the noDisplay() function which sets the style.display property to 'none' */
function makeInvisible(element) {
	if (element && element.style)
		element.style.visibility = 'hidden';
}

/* this function changes the background-color of an element */
function background(element, color) {
	element.style.backgroundColor = color;
}

/* this function resets the background-color of an element */
function resetBackground(element) {
	background(element, '');
}

/* get the height of a div, return zero if height is one pixel because of ie bug, if you do not want this use getRealHeight instead */
function getHeight(element) {
	var height = getFloat(element.offsetHeight);
	return (height == 1) ? 0 : height;
}

/* COMMENT */
function getWidth(element) {
	return element.style.width;
}

/* COMMENT */
function getRealWidth(element) {
	return element.offsetWidth;
}

/* this function returns the real height, the difference with getHeight is that it doesn't return 0 if the height is actually 1 */
function getRealHeight(element) {
	return element.offsetHeight;
}

/* this function sets the height of the given element */
function setHeight(element, height) {
	if (element && element.style)
		element.style.height = (height == null) ? null : setPixels((height == 0) ? 1 : height);
}

/* this function sets the height of the given element in percents */
function setHeightPercent(element, height) {
	element.style.height = height + '%';
}

/* this function sets the height of the given element */
function setWidth(element, width) {
	if (width === '' && IE) width = null;
	element.style.width = (width == null) ? null : setPixels(width);
}

/* this function sets the height of the given element */
function setWidthPercent(element, width) {
	element.style.width = width + '%';
}

/* get the inner html of an element */
function getHtml(element) {
	return element.innerHTML;
}

/* set the inner html of an element */
function setHtml(element, value) {
    if (element!=null) {
		element.innerHTML = value;
	} else {
	   return false;
	}
}

/* set the value of an element i.e. inputs */
function setValue(element, newValue) {
	element.value = newValue;
}

/* COMMENT */
function setBorder(element, width, color) {
	element.style.border = width + 'px solid ' + color;
}

/* get the offsetHeight of an element. offsetHeight is a property that gets the height of an element relative to the layout, this includes margins, paddings and borders */
function getOffsetHeight(element) {
	return element.offsetHeight;
}

/* get the offsetWidth of an element. offsetWidth is a property that gets the width of an element relative to the layout, this includes margins, paddings and borders */
function getOffsetWidth(element) {
	return element.offsetWidth;
}

/* set the overflow of an element, overflow makes scrollbars visible, hidden of auto */
function setOverflow(element, value) {
	element.style.overflow = value;
}

/* set the checkbox to a value if it is not disabled */
function setCheckbox(element, value, showMessage) {
	
	if (!element) return false;
	
	if (element.disabled) {
		if (showMessage == null || showMessage == true) setError('Er is een fout opgetreden met deze checkbox, neem contact op met onze service afdeling.');
		return false;
	}
	element.checked = value;
	return true;
}

/* this function adds px to the end of the number given */
function setPixels(number) {
	if (typeof number !== 'string') return parseInt(number) + 'px';
	else if (number.indexOf('px') != -1) return number;
	else if (number.indexOf('%') != -1) return number.replace('%', 'px');
	else return parseInt(number) + 'px';
}

/* COMMENT */
function isVisible(element) {
	return !(element.style.visibility == 'hidden' || element.style.display == 'none' || getHeight(element) == 0);
}

/* we check if the height or width of the element is set to zero or one
   the function getHeight returns zero if the height is one because of ie bug */
function isCollapsed(element) {
	return ( (getHeight(element)<=1) || (getRealWidth(element) <= 1) );
}

/* we check if the width of the element is set to zero */
function widthCollapsed(element) {
	return ( getRealWidth(element) <= 1) ;
}

/* this function makes a div invisible, originally we only set it to height:0px; but ie doesn't support
   this correctly, so instead we set it to 1px height and set style.visibility to hidden by making it invisible  */
function collapse(element) {
	setHeight(element, 1);
	makeInvisible(element);
}

/* this function makes a div invisible, originally we only set it to height:0px; but ie doesn't support
   this correctly, so instead we set it to 1px height and set style.visibility to hidden by making it invisible  */
function collapseWidth(element) {
	setWidth(element, 0);
	makeInvisible(element);
}

/* COMMENT */
function setColor(element, color) {
	element.style.color = color;
}

/* COMMENT */
function resetColor(element) {
	element.style.color = '';
}

/* COMMENT */
function getRadioValue(radioObj) {
	for(i=0; i<radioObj.length; i++) if (radioObj[i].checked == true) return radioObj[i].value;
}

/* COMMENT */
function setRadio(radioObj, index) {
	radioObj[index].checked = true;
}

/* COMMENT */
function prefix(string, prefix, length) {
	var diff = length - string.length;
	for(i=0; i<diff; i++) string = prefix + string;
	return string;
}

/* COMMENT */
function getSelectValue(element) {


	if (element && element.selectedIndex !=null) {
		return element[element.selectedIndex].value;
	} else {
		return "";
	}
}

/* COMMENT */
function setSelectValue(element, value) {
	var found = false;
	for (var i = 0; i < element.options.length; i++) {
		if (typeof value != 'undefined' && element.options[i].value == value) {
			element.selectedIndex = i;
			found = true;
			break;
		}
	}

	return found;
}

/* COMMENT */
function setSelectValueByText(element, desc) {
	var found = false;
	for (var i = 0; i < element.options.length; i++) {
		if (typeof desc != 'undefined' && element.options[i].text == desc) {
			element.selectedIndex = i;
			found = true;
			break;
		}
	}

	return found;
}


/* COMMENT */
function dateBefore(first, last) {
	if (parseFloat(first.substring(4, 8)) < parseFloat(last.substring(4, 8))) return true;
	else if (parseFloat(first.substring(2, 4)) < parseFloat(last.substring(2, 4))) return true;
	else if (parseFloat(first.substring(0, 2)) < parseFloat(last.substring(0, 2))) return true;
	else if (first == last) return true;
	return false;
}

/* COMMENT */
function resetRadio(radioObj) {
	if (radioObj)
		for(i=0; i<radioObj.length; i++) radioObj[i].checked = false;
}

/* COMMENT */
function resetCheckbox(id) {
	get(id).checked = false;
}

/* get the opacity/alpha/transparency of a div */
function getOpacity(element) {

	/* for ie we need the style.filter property
	   for other browsers we need the style.opacity property */
	var opacityValue = null; 
	if (IE) {
		if (element.style.filter != '') {
			opacityValue = parseInt(element.style.filter.replace('alpha(opacity=', '').replace(')', ''));
		} else {
			opacityValue = 0;
		}
	} else {
		opacityValue = parseInt(element.style.opacity * 100);
	}
	return (opacityValue == null || opacityValue >= 99 ) ? 100 : opacityValue;

}

/* this function sets the opacity/alpha/transparency of a div,
   tested with ie5.5+ and ff1.0+. We return in a scale of 0 to 100 */
function setTransparency(element, opacity) {

	opacity = (opacity == 100) ? 99.999 : opacity;

	/* for ie we need the style.filter property */
	if (IE) {
		if (opacity >= 99) element.style.filter = '99.999';
		else element.style.filter = 'alpha(opacity='+opacity+')';

	} else { /* for other browsers we need the style.opacity property */

		/* Safari<1.2, Konqueror */
		element.style.KHTMLOpacity = opacity/100;
		
		/* Older Mozilla and Firefox */
		element.style.MozOpacity = opacity/100;
		
		/* Safari 1.2, newer Firefox and Mozilla, CSS3 */
		element.style.opacity = opacity/100;
	}
}

/* this is a function to get the height and width of an element when it's collapsed.
   it hides the element, resets the values to null en then gets the offsets, these
   value are then returned */
/* which can be 'height', 'width' or 'both' */
/* this functionality is made into one function to speed it up, if we need to do this 
   twice users might see more obviously the height en width being set to null */
function getHiddenOffset(element, which) {
	
	var elementWidth = elementHeight = null;
	
	/* make sure it is not visible when we reset the height */
	makeInvisible(element);
	
	/* save the old values for later */
	oldHeight = getHeight(element);
	oldWidth = getWidth(element);
	
	/* reset the height and width and then get the hidden height and width */
	/* set it back to collapsed values */
	if (which == 'both' || which == 'height') {
		setHeight(element, null);
		
		elementHeight = getOffsetHeight(element);
		setHeight(element, oldHeight);
	}
	if (which == 'both' || which == 'width') {
		setWidth(element, null);
		elementWidth = getOffsetWidth(element);
		setWidth(element, oldWidth);
	}
	
	/* make it visible again for later use */
	makeVisible(element);
	
	return [elementHeight, elementWidth];
}

/* this function gets the hidden height of an element by calling the getHiddenOffset function */
function getHiddenHeight(element) {
	return getHiddenOffset(element, 'height')[0];
}

/* this function gets the hidden width of an element by calling the getHiddenOffset function */
function getHiddenWidth(element) {
	return getHiddenOffset(element, 'width')[1];
}

/* COMMENT */
function getElementsByClassName(theClass) {
	return tmg.makeArray(tmg('.' + theClass));
}

/* COMMENT*/	
function getElementsByName(name) {
	return tmg.makeArray(tmg('[name=' + name + ']'));
}

/* COMMENT*/	
function getPageHeight(){
	var yScroll, windowHeight;

	if (window.innerHeight && window.scrollMaxY)
		yScroll = window.innerHeight + window.scrollMaxY;
	else if (document.body.scrollHeight > document.body.offsetHeight) // all but Explorer Mac
		yScroll = document.body.scrollHeight;
	else // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		yScroll = document.body.offsetHeight;
	
	if (self.innerHeight) // all except Explorer
		windowHeight = self.innerHeight;
	else if (document.documentElement && document.documentElement.clientHeight) // Explorer 6 Strict Mode
		windowHeight = document.documentElement.clientHeight;
	else if (document.body) // other Explorers
		windowHeight = document.body.clientHeight;
	
	return (yScroll < windowHeight) ? windowHeight : yScroll;
}

function convertToISO(formField) {
	// If a form field is read in javascript the encoding type in IE is UTF-8 and
	// in mozilla ISO (because javascript is set to ISO).
	// To solve te IE problem the value is put into this function and returned.
	// Now the value is also converted to ISO (like set in enctype for javascript) by IE !
	var result = formField;
    return result;		
}

/* this function is used for the animations of divs */
/* you can use animation with an instance of the object, or make an instance on runtime. preferable the 
   first option because of the getHiddenHeight call if we do not know the element height */
/* TODO: NEED MORE COMMENT HERE */
function animation(elementId, properties) {
	/* store the properties in the options array */
	var options = [];
	for (i in properties) options[i] = properties[i];
	
	/* declare the element */
	this.element		= document.getElementById(elementId); // use getelementbyid because id contains a . (dot)
	this.redraw			= options['redraw'] != null ? options['redraw'] : 50; /* in millis */
	this.duration		= options['duration'] != null ? options['duration'] : 500; /* in millis */
	this.animationType	= options['animationType'] != null ? options['animationType'] : 'easeInOut'; /* lineair | easeIn | easeOut | easeInOut | null */
	/* set elementHeight to default if not given, set to null if it is zero */
	this.elementHeight	= options['height'] != null ? options['height'] : (getHeight(this.element) == 0) ? getHiddenHeight(this.element) : getHeight(this.element);
	this.elementWidth	= options['width'] != null ? options['width'] : (getRealWidth(this.element) == 0) ? getHiddenWidth(this.element) : getRealWidth(this.element);
	this.elementOpacity = options['opacity'] != null ? options['opacity'] : getOpacity(this.element);
	this.steps			= this.duration / this.redraw; // calculate the number of steps for animations
	this.vertical		= options['vertical'] != null ? options['vertical'] : true;
	this.horizontal		= options['horizontal'] != null ? options['horizontal'] : false;
	this.newHeight		= null;
	this.newWidth		= null;
	this.callback		= options['callback'];
	
	/* this function checks if the div needs to be hidden slowly or at once */
	this.hideDiv = function (speed) {
		
		/* if it is allready hidden, do nothing */
		if (!isCollapsed(this.element) && !widthCollapsed(this.element)) {
			
			/* set the newHeight for the animation */
			if (this.vertical) this.newHeight = 0;
			if (this.horizontal) this.newWidth = 0;
			
			/* if we want to animate slowly */
			if (speed == 'slow') {
				if (this.vertical) this.goHeight();
				if (this.horizontal) this.goWidth();
			/* make invisible sets it to zero too */
			} else collapse(this.element);
		}
	};
	
	/* COMMENT */
	this.showDiv = function (speed) {
		if (isCollapsed(this.element)) {
			this.toggleDiv(speed);
		}
	};
	
	/* COMMENT */
	this.toggleDiv = function (speed) {
		
		var elementOffsets	= getHiddenOffset(this.element, 'both');
		this.elementHeight	= elementOffsets[0];
		this.elementWidth	= elementOffsets[1];
		
		/* if the element is collapsed the new height is eighter the hiddenHeight or the elementHeight if that is available */
		if (isCollapsed(this.element)) {
			if (this.vertical) this.newHeight = this.elementHeight;
			if (this.horizontal) this.newWidth = this.elementWidth;
		/* else the newHeigt will be zero */
		} else {
			if (this.vertical) this.newHeight = 0;
			if (this.horizontal) this.newWidth = 0;
		}

		if (speed == 'slow') {
			if (this.vertical) this.goHeight();
			if (this.horizontal) this.goWidth();
		} else {
			if (!isLocked(this.element.id+'_height') && this.newHeight == 0) collapse(this.element);
			if (!isLocked(this.element.id+'_width') && this.newWidth == 0) collapseWidth(this.element);
			if (!isLocked(this.element.id+'_height') && !isLocked(this.element.id+'_width')) {
				if (this.vertical) {
					setHeight(this.element, this.newHeight);
					if (this.newHeight != 0) makeVisible(this.element);
				}
				if (this.horizontal) {
					setWidth(this.element, this.newWidth);
					if (this.newWidth != 0) makeVisible(this.element);
				}
			}
		}
	};

	/* this function is only for 'slow' animations */
	/* this function slowly fades the div in or out */
	this.fadeDiv = function (how) {
		
		currentOpacity = getOpacity(this.element);
		
		/* check if we need to fade in or out */
		how = (how == null) ? (currentOpacity == 0) ? 'in' : 'out' : how;
		
		/* check if the div isn't allready in the right state */
		if (!(currentOpacity == 0 && how == 'out') && (!(currentOpacity == 100 && how == 'in')) && !(isLocked(this.element.id+'_fade'))) {
			
			lock(this.element.id + '_fade');
			setTimeout("unlock('"+this.element.id+"_fade')", this.duration+20);
			
			/* set the timouts */
			for (i=0; i<=this.steps; i++)
				this.stepOpacity(((how == 'in') ? (100 / this.steps) * i : 100 - (100 / this.steps) * i));
		}

	};

	/* internal function for each step, sets the transparency */
	this.stepOpacity = function (opacity) {
		setTimeout("setTransparency( get ( '" + this.element.id + "'), " + opacity + ");", this.redraw * i);
	};

	/* this function is only for 'slow' animations */
	/* this function will make several setTimeouts (one for each step), these timeouts will redraw the div with the proper height */
	this.goHeight = function () {

		if (!isLocked(this.element.id+'_height')) {
			lock(this.element.id+'_height');
			setTimeout("unlock('"+this.element.id+"_height')", this.duration+20);
			var self = this;
			
			if (self.callback)
				setTimeout(function(){self.callback();}, this.duration+20);

			makeVisible(this.element);
			
			/* for performance do this here */
			this.stepsSqrt = Math.sqrt(this.steps);
			
			/* set the timeouts for the specific type */
			switch (this.animationType) {
				case 'lineair' : for (i=0; i<=this.steps; i++) this.stepHeight((this.elementHeight / this.steps) * i); break;
				case 'easeIn' : for (i=0; i<=this.steps; i++) this.stepHeight((this.elementHeight/this.steps/this.steps) / this.steps*i*i*i); break;
				case 'easeOut' : for (i=0; i<=this.steps; i++) this.stepHeight(Math.sqrt( i ) * this.elementHeight / this.stepsSqrt); break;
				case 'easeOut2' : for (i=0; i<=this.steps; i++) this.stepHeight(2 * this.elementHeight * ( (i / this.steps) -0.5 * i*i/this.steps/this.steps )); break;
				case 'easeInOut' : for (i=0; i<=this.steps; i++) this.stepHeight(((this.elementHeight / 2) + (this.elementHeight / 2) * Math.sin((Math.PI / this.steps) * (i-(this.steps/2))))); break;
				/* default without timeouts */
				default : this.stepHeight(this.elementHeight); break;
			}
		} else {
//			alert('sorry locked');
		}
	};

	/* this function is only for 'slow' animations */
	/* this function will make several setTimeouts (one for each step), these timeouts will redraw the div with the proper height */
	this.goWidth = function () {

		if (!isLocked(this.element.id+'_width')) {
			lock(this.element.id+'_width');
			setTimeout("unlock('"+this.element.id+"_width')", this.duration+20);

			/* for performance do this here */
			this.stepsSqrt = Math.sqrt(this.steps);
			
			/* set the timeouts for the specific type */
			switch (this.animationType) {
				case 'lineair' : for (i=0; i<=this.steps; i++) this.stepWidth((this.elementWidth / this.steps) * i); break;
				case 'easeIn' : for (i=0; i<=this.steps; i++) this.stepWidth((this.elementWidth/this.steps/this.steps) / this.steps*i*i*i); break;
				case 'easeOut' : for (i=0; i<=this.steps; i++) this.stepWidth(Math.sqrt( i ) * this.elementWidth / this.stepsSqrt); break;
				case 'easeOut2' : for (i=0; i<=this.steps; i++) this.stepWidth(2 * this.elementWidth * ( (i / this.steps) -0.5 * i*i/this.steps/this.steps )); break;
				case 'easeInOut' : for (i=0; i<=this.steps; i++) this.stepWidth(((this.elementWidth / 2) + (this.elementWidth / 2) * Math.sin((Math.PI / this.steps) * (i-(this.steps/2))))); break;
				/* default without timeouts */
				default : this.stepHeight(this.elementWidth); break;
			}
		}
	};

	/* internal function for each step, sets the new height */
	this.stepHeight = function(thisHeight) {
		
		/* invert the thisHeight if the newHeight is zero */
		thisHeight = parseInt( (this.newHeight == 0) ? this.elementHeight - thisHeight : thisHeight );
		
		/* we can't set the div to zero because of ie5.5, so we make it invisible with height set to 1px,
		   make sure the div is visible */
		
		if (thisHeight != 0) {
			if(this.newHeight == thisHeight) {
				setTimeout("setHeight( get ( '" + this.element.id + "'), null);", this.redraw*i);
			} else {
				setTimeout("makeVisible( get ( '"+ this.element.id + "') );", this.redraw*i);
				setTimeout("setHeight( get ( '" + this.element.id + "'), " + thisHeight + ");", this.redraw*i);
			}
		}
		else setTimeout("collapse( get ( '" + this.element.id + "') );", this.redraw*i);
	};

	/* internal function for each step, sets the new height */
	this.stepWidth = function(thisWidth) {
		
		/* invert the thisHeight if the newHeight is zero */
		thisWidth = parseInt( (this.newWidth == 0) ? this.elementWidth - thisWidth : thisWidth );
		
		/* we can't set the div to zero because of ie5.5, so we make it invisible with height set to 1px,
		   make sure the div is visible */
		
		if (thisWidth != 0) {
			if(this.newWidth == thisWidth) {
				setTimeout("setWidth( get ( '" + this.element.id + "'), null);", this.redraw*i);
			} else {
				setTimeout("makeVisible( get ( '"+ this.element.id + "') );", this.redraw*i);
				setTimeout("setWidth( get ( '" + this.element.id + "'), " + thisWidth + ");", this.redraw*i);
			}
		}
		else setTimeout("collapseWidth( get ( '" + this.element.id + "') );", this.redraw*i);
	};

	/* hide the div if it needs to be invisible onload */
	if (options['hidden']) {
		setHeight(this.element, 0);
	}
	
	/* hide the scrollbars for this div if it is hidden or toggled slowly */
	setOverflow(this.element, 'hidden');
	
	/* make these events available to the rest of the document */
	this.sweetToggle	= function () { this.fadeDiv(); this.toggleDiv('slow') };
	this.sweetHide		= function () { this.fadeDiv('out'); this.hideDiv('slow'); };
	this.sweetShow		= function () { this.showDiv('slow'); this.fadeDiv('in'); };
	this.fade			= function (how) { this.fadeDiv(how); };
	this.toggle			= function (speed) { this.toggleDiv(speed); };
	this.show			= function (speed) { this.showDiv(speed); };
	this.hide			= function (speed) { this.hideDiv(speed); };
}





/***************************************/
/* old functions, do we need these ??? */
/***************************************/

/* COMMENT */
function refresh() {
	now = new Date();
	location.href = location.href+'&tijd='+now.getTime();
	location.reload();
	return true;
}

/* COMMENT */
function logout() {
	var exp = new Date();
	if (confirm('Weet u zeker dat u wilt uitloggen?\nUw huidige Speurderinvoer raakt daarbij verloren.')) {
		document.location = 'http://'+getDomain()+'/servlet/SpeurderOrderServlet?state=logout';
	}
	return false;
}

/* COMMENT */
function winkelwagentje() {
	document.location = 'http://'+getDomain()+'/servlet/SpeurderOrderServlet?state=basket&amp;useraction=show';
	return false;
}

/* COMMENT */
function selectTab(tabid) {
	for (var walk=1;walk<=tabcount;walk++){
		get('tab'+walk).className="";
		noDisplay('page'+walk);
	}
	get('tab'+tabid).className="tabselected";
	get('tab'+tabid).blur();
	display('page'+tabid);
}

/* COMMENT */
function getDomain() {
	var loc = ''+window.location;
	var i = loc.indexOf('http://');
	if (i>=0) loc = loc.substring(i+7);
	var i = loc.indexOf('/');
	if (i>=0) loc = loc.substring(0,i);
	return loc;
}

/* here are 6 functions for opening popups, we need one function to do this all people */
function myCommandPopup(command, id) {
	myCommandPopup(command, id, 680, 600);
}
function myCommandPopup(command, id, width, height) {
	var features = 'scrollbars=yes,menubar=no,resizable=yes,width='+width+',height='+height;
	win = window.open("/servlet/beheer/CommandServlet?command="+command+"&id="+id,"popup",features);
	win.focus();
}
function myUrlPopup(url, width, height) {
	var features = 'scrollbars=no,menubar=no,resizable=yes,width='+width+',height='+height;
	win = window.open(url,"popupUrl",features);
	win.focus();
}
function myUrlPopupWithScrollbars(url, width, height) {
	var features = 'scrollbars=yes,menubar=no,resizable=yes,width='+width+',height='+height;
	win = window.open(url,"popupUrl",features);
	win.focus();
}
function MM_openBrWindow(theURL,winName,features) {
	window.open(theURL,winName,features);
}
function defaultOpen(theURL, winName) {
	window.open(theURL,winName,'scrollbars=yes,menubar=no,resizable=yes,width=720,height=400');
}

/* TODO: IS THIS STILL USED ? I don't think so because it didn't work */
function fadeInObject(element) {
	fadeIn(element.id, 0, 20);
}

/* COMMENT */
/* TODO: IS THIS STILL USED ? I don't think so because it didn't work */
/* almost obsolete, use animation function instead */
function fadeIn(id, opacity, step) {
	if (get(id)) {
		element = get(id);
		if (opacity <= 100) {
			setOpacity(element, opacity);
			opacity += step;
			window.setTimeout("fadeIn('"+id+"',"+opacity+","+step+")", 40);
		}
	}
}

/* COMMENT */
/* TODO: IS THIS STILL USED ? */
/* almost obsolete, use animation function instead */
function setOpacity(id, opacity) {
	opacity = (opacity == 100) ? 99.999 : opacity;
	element = get(id);
	
	/* IE/Win */
	if (opacity>99) element.style.filter = "";
	else element.style.filter = "alpha(opacity="+opacity+")";
	
	/* Safari<1.2, Konqueror */
	element.style.KHTMLOpacity = opacity/100;
	
	/* Older Mozilla and Firefox */
	element.style.MozOpacity = opacity/100;
	
	/* Safari 1.2, newer Firefox and Mozilla, CSS3 */
	element.style.opacity = opacity/100;
}
 
/* COMMENT */
/* TODO: IS THIS STILL USED ? */
function lightdown(id, selected) {
	if (id!=selected) setClass(get(id), 'rollout');
}



/********************************************/
/*   the following functions are obsolete   */
/*         we need to get rid of it         */
/********************************************/

/* obsolete, do not use this anymore. use display(element) instead */
/* show does not describe what it actually does, so we need to get rid of it */
/* TODO: IS THIS STILL USED ? */
function show(id) {
	display(get(id));
}

/* obsolete, do not use this anymore. use noDisplay(element) instead */
/* hide does not describe what it actually does, so we need to get rid of it */
/* TODO: IS THIS STILL USED ? */
function hide(id) {
	noDisplay(get(id));
}

/* obsolete, do not use this anymore. use display(element) instead */
/* showElement does not describe what it actually does, so we need to get rid of it */
/* TODO: IS THIS STILL USED ? */
function showElement(element) {
	display(element);
}

/* obsolete, do not use this anymore. use noDisplay(element) instead */
/* hideElement does not describe what it actually does, so we need to get rid of it */
/* TODO: IS THIS STILL USED ? */
function hideElement(element) {
	noDisplay(element);
}


/* obsolete, do not use this anymore. use get(id) instead */
/* TODO: THIS IS STILL BEGING USED, PLEASE GRADUALLY PHASE OUT */
function getElement(id) {
	if (id.indexOf('$') != -1)
		return document.getElementById(id);
	return get(id);
}

/* obsolete, do not use this animore. use background(element, color) instead */
/* TODO: IS THIS STILL USED ? */
function lightup(id) {
	setClass(get(id), 'rollover');
}

/* obsolete, do not use this anymore. use background(element, '#E5F1F6') instead */
/* TODO: IS THIS STILL USED ? */
function hilite(element) {
	background(element, '#E5F1F6');
}

/* obsolete, do not use this anymore. use background(element, color) instead */
/* TODO: IS THIS STILL USED ? */
function unhilite(element, color) {
	background(element, color);
}

/**
	 * this function will set the right seconds counter for the preview image loader
*/
function updatePreviewTimer(){

    if (isLocked('previewTimer')) {
        get('previewImageLoader').innerHTML = get('previewImageLoader').innerHTML - 0 + 1;
        setTimeout(updatePreviewTimer, 1000);
    }
    
}

function showPreviewWithTimer(url){

	lock('previewTimer');
	get('previewImageLoader').innerHTML = 0;
	setTimeout(updatePreviewTimer, 1000);
	removeClass(get('previewImgLoader'), 'hidden');

	image = new Image();
	image.src = url;

	image.onload = function(){

		unlock('previewTimer');

		get('lppreviewimg').style.background = 'url(' + url + ') no-repeat';
		if (IE) {
			// IE only
			get('lppreviewimg').style.width = image.width + 'px'; 
			get('lppreviewimg').style.height = image.height + 'px';
			get('previewcontainer').style.height =  image.height + 'px';
			get('previewcontainer').style.width =  image.width + 'px';
			get('previewImgOverlay').style.height = image.height;
			get('previewImgOverlay').style.width = image.width;
		}else {
			get('lppreviewimg').style.width = image.naturalWidth + 'px'; 
			get('lppreviewimg').style.height = image.naturalHeight + 'px';
			get('previewcontainer').style.height =  image.naturalHeight + 'px';
			get('previewcontainer').style.width =  image.naturalWidht + 'px';
			get('previewImgOverlay').style.height = image.naturalHeight + 'px';
			get('previewImgOverlay').style.width = image.naturalWidth + 'px';
		}

		removeClass(get('lppreviewimg'), 'hidden');
		addClass(get('previewImgLoader'), 'hidden');
	}
}

function openBrochure() {
	return;
	//var windowprops = "left=50,top=50,width=600,height=400,menubar=no,toolbar=no,titlebar=no,status=no";
	//preview = window.open("", "brochure", windowprops);
}

function getDomain(){
    var loc = '' + window.location;
    var i = loc.indexOf('http://');
    if (i >= 0) 
        loc = loc.substring(i + 7);
    var i = loc.indexOf('/');
    if (i >= 0) 
        loc = loc.substring(0, i);
    return loc;
}

var Unselectable = {
 
	enable : function(e) {
		var e = e ? e : window.event;
		if (e.button != 1) {
			
			if (e.target) var targer = e.target;
			else if (e.srcElement) var targer = e.srcElement;
			
			if (targer && targer.parentNode && targer.parentNode.parentNode && ( 
					targer.parentNode.id === 'productbarholder' ||
					targer.parentNode.className === 'c_h' || 
					targer.parentNode.className === 'c_r' ||
					
					targer.parentNode.parentNode.id === 'productbarholder' ||
					targer.parentNode.parentNode.parentNode.id === 'productbarholder' ||
					targer.parentNode.parentNode.className == 'c_h' || 
					targer.parentNode.parentNode.className == 'c_r' ||
					(targer.parentNode.parentNode.parentNode && targer.parentNode.parentNode.parentNode.className == 'c_h')))
						return false;

		}
	},
 
	disable : function () { return true; }
 
}
 
if (typeof(document.onselectstart) != "undefined") {
	document.onselectstart = Unselectable.enable;
} else {
	document.onmousedown = Unselectable.enable;
	document.onmouseup = Unselectable.disable;
}


/* DECLARATIONS */
var debugTimer = new Date();

var togglers, optiontogglers, acties;
var myDiv = optiontogglersIds = optiontogglersEffects = [];
var togglersEffects = togglersIds = [];
var effects					= [];
var currentAnimationId		= 1;

/* SETTINGS */
var countryCodes="|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|fi|fj|fk|fm|fo|fr|fx|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zr|zw|com|biz|edu|gov|int|mil|net|org|arpa|nato|info|eu|";
var currentActionAnimation	= 'algemeen';
var actionDisplayTime		= 5;	/* in millis */
var delayTime				= 1;			/* in millis */
var loopTime				= ((2 * delayTime) + actionDisplayTime);
var animationLock			= false;
var hcClusterArray			= []; 
var hdcClusterArray			= []; 
var maand = { 1:'januari', 2:'februari', 3:'maart', 4:'april', 5:'mei', 6:'juni', 7:'juli', 8:'augustus', 9:'september', 10:'oktober', 11:'november', 12:'december' };
var dagvandeweek = { 1:'maandag', 2:'dinsdag', 3:'woensdag', 4:'donderdag', 5:'vrijdag', 6:'zaterdag', 7:'zondag'};
var months		= ['jan','feb','mrt','apr','mei','jun','jul','aug','sep','okt','nov','dec'];
var fullMonths	= ['januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december'];

function checkEmail(email){
	var at;
	var c;
	var pos;
	
	if(email.indexOf(' ') != -1) {
		return "een e-mail adres mag geen spaties bevatten";
	}
	if(email.indexOf(',')!=-1){
		if(email.toLowerCase().indexOf('compuserve.com')!=-1)
			return "in een compuserve-adres dient u de komma's door punten te vervangen";
		else
			return "een e-mail adres mag geen komma's bevatten";
	}
	at=email.indexOf('@');
	if(at==0)
		return "er staat niets voor het @-teken";
	else if(at==-1)
		return "een e-mail adres hoort een @-teken te bevatten";
	c=email.charAt(at+1).toLowerCase();
	if((c<'a'||c>'z')&&(c<'0'||c>'9'))
		return "achter het @-teken hoort een letter of cijfer te staan";
	if(email.indexOf('..',at)!=-1)
		return "achter het @-teken staan twee punten achter elkaar";
	for(pos=at+1;pos<email.length;pos++){
		c=email.charAt(pos).toLowerCase();
		if((c<'a'||c>'z')&&(c<'0'||c>'9')&&c!='.'&&c!='-')
			return "het e-mail adres bevat het ongeldige teken '"+c+"'";
	}
	pos=email.lastIndexOf('.');
	if(pos==-1)
		return "de domeinnaam bevat geen punt";
	c=email.substring(pos+1,email.length);
	if(countryCodes.indexOf('|'+c.toLowerCase()+'|')==-1)
		return "er bestaan geen domeinnamen die eindigen op ."+c;
	return null;
}

function stopScrollInterval() {
	if (typeof(activeScrollInterval)!="undefined") {
		clearInterval(activeScrollInterval);
	}
}
   
function stopAutoscrollInterval() {
	clearInterval(activeAutoscrollInterval);
}

function setOnclick(element, onclickEvent) {
	element.onclick = function() { eval(onclickEvent); };
}

function GetInnerSize () {
	var x,y;
	if (self.innerHeight) // all except Explorer
	{
		x = self.innerWidth;
		y = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight)
		// Explorer 6 Strict Mode
	{
		x = document.documentElement.clientWidth;
		y = document.documentElement.clientHeight;
	}
	else if (document.body) // other Explorers
	{
		x = document.body.clientWidth;
		y = document.body.clientHeight;
	}
	return [x,y];
}

function showPreviewTip(element,id, version, kolommen) {
	
	if (!kolommen || kolommen == null || kolommen=='undefined') {
		kolommen="1";
	}
	var tipwidth=180;
	var imagewidth=173;
	if (kolommen!="1") {
		tipwidth=300;
		imagewidth=280;
		
	}
	var extraoffsetX=30;
	var extraoffsetY=15;
	var offset = $(element).position();
	$('#previewdiv').remove();
	var extraHtml='<a class="pointer" onclick="$(this).parent().remove();return false;">';
	extraHtml+=	'<img src="/img/iconen/close.gif" alt="sluit dit voorbeeld" title="sluit" style="margin:4px;float:right;" border="0"></a>';
	extraHtml+= '<h3 style="margin:5px">Order:' + id + ' - '+kolommen+' koloms</h3>';
	extraHtml+= '<div style="position:absolute;margin-left:80px;margin-top:0px;" id="spindiv"><img src="/img/loader.gif"></div>';
	extraHtml+= '<p><img style="border:1px solid black;margin:3px;width:'+imagewidth+'px;" alt="Advertentievoorbeeld" title="Advertentievoorbeeld" onload="$(\'#spindiv\').remove();" src="/servlet/PreviewServlet?id=' + id + '&v='+version+'&cache=true"></p>';
		
	var newx = Math.round(offset.left);
	var newy = Math.round(offset.top);
	
	var innerSize=GetInnerSize();
	if ((GetInnerSize()[0]/2)<newx) {
		newx-=(tipwidth+extraoffsetX);
	}else {
		newx+=(extraoffsetX);
	}
	newy+=extraoffsetY;
	var previewdiv = $('<div id="previewdiv" style="background:url(\'/img/bgblue.jpg\')"/>').addClass('previewdiv').html(extraHtml).css({'left': (newx)+'px','top' : newy+'px', 'width': tipwidth+'px'}).css('width','500');
	$('#content').append(previewdiv);
	$('#previewdiv').css('width',tipwidth);
	return

}

function trackMouse(e) {
	
	mouse.scrollLeft = IE ? document.documentElement.scrollLeft : pageXOffset;
	mouse.scrollTop = IE ? document.documentElement.scrollTop : pageYOffset;
	
	// firefox does not need the scrolloffset to detect the mouse position
	mouse.x = IE ? (event.clientX + mouse.scrollLeft) : e.pageX;
	mouse.y = IE ? (event.clientY + mouse.scrollTop) : e.pageY;
	
//	if (mouse.tooltip && mouse.tooltipInitialized != true) {
		
		if (mouse.tooltip ) {
		if (mouseDiv == null) return;

		var newx = mouse.x + mouse.xoffset;
		var newy = mouse.y + mouse.yoffset;
		
		var innerWidth = (IE ? document.documentElement.clientWidth : window.innerWidth) + mouse.scrollLeft;
		var innerHeight = (IE ? document.documentElement.clientHeight : window.innerHeight) + mouse.scrollTop;
		
		// IE5.5
		if (document.documentElement.clientWidth == 0) innerWidth += document.body.clientWidth;
		if (document.documentElement.clientHeight == 0) innerHeight += document.body.clientHeight;
		
		if (newx < 0) newx = 0;
		else if (innerWidth < (newx + mouseDiv.offsetWidth + 30)) newx = innerWidth - mouseDiv.offsetWidth - 30;
		 
		if (newy < 0) newy = 0;
		else if (innerHeight < (newy + mouseDiv.offsetHeight + 30)) newy = innerHeight - mouseDiv.offsetHeight - 30;
		
		mouseDiv.style.left = newx + 'px';
		mouseDiv.style.top = newy + 'px';
		
		mouse.tooltipInitialized = true;
	}
}

function tooltip(element, title, text, xoffset, yoffset) {
	
	if (!mouse.mouseovertooltip && mouse.tooltip != true) {
		if (mouseDiv == null) return;
		if (xoffset == null) xoffset = 15;
		if (yoffset == null) yoffset = 15;
		
		mouse.tooltip = true;
		mouse.xoffset = xoffset;
		mouse.yoffset = yoffset;
		
		get('mouseDivHeader').innerHTML = title;
		get('mouseDivContent').innerHTML = text;

		fadeTooltipIn(mouseDiv);

		element.oldonmouseout = element.onmouseout;
		
		element.onmouseout = function(){
			mouse.tooltip = false;
			setTimeout(fadeTooltipOut, 15);
			this.onmouseout = this.oldonmouseout;
		}
	}
}


function stepTooltipFade(fadein) {
	
	if (fadein) mouse.currentFadescale += 2;
	else mouse.currentFadescale -= 2;
	
	if (mouse.currentFadescale < 0) mouse.currentFadescale = 0;
	else if (mouse.currentFadescale > 10) mouse.currentFadescale = 10;
	
	setTransparency(mouseDiv, mouse.currentFadescale * 10);

	if (mouse.currentFadescale >= 10 || mouse.currentFadescale <= 0) clearInterval(mouse.tooltipanimation);
	if (mouse.currentFadescale <= 0) mouseDiv.style.display = 'none';
	
	if (mouse.currentFadescale == 0 )mouse.tooltipInitialized = false; 
	
}

function fadeTooltipIn() {
	clearInterval(mouse.tooltipanimation);
	mouse.currentFadescale = getOpacity(mouseDiv) / 10;
	if (mouse.currentFadescale == '') mouse.currentFadescale = 0;
	stepTooltipFade(true);
	mouseDiv.style.display = '';
	display(mouseDiv,true);
	mouse.tooltipanimation = setInterval('stepTooltipFade(true)', 15);
}

function fadeTooltipOut() {
	if (mouse.mouseovertooltip != true && mouse.tooltip == false) {
		clearInterval(mouse.tooltipanimation);
		mouse.currentFadescale = getOpacity(mouseDiv) / 10;
		stepTooltipFade();
		display(mouseDiv,true);
		mouse.tooltipanimation = setInterval('stepTooltipFade()', 15);
	}
}

function hideTooltip() {
	if (mouse.mouseovertooltip != true && mouse.tooltip == false) {
		noDisplay(mouseDiv,true);
		//fadeOut(mouseDiv);
//		get('mouseDivHeader').innerHTML = '';
//		get('mouseDivContent').innerHTML = '';
	}
}

function optionToggle(cl) {
	optionsAnimations = getElementsByClassName(cl);

	var temp = function(el) {
		el.checked = false;
		var slider = get(el.id.replace('_toggler', '_slider') );
		display(slider, 'block');
		
		optiontogglersIds[optiontogglersIds.length] = el.id;
		
		var anim = new animation(slider.id, {hidden:true, animationType:'lineair'} );

		optiontogglersEffects[el.id] = anim;
		
		getSlider = function () { return this.anim; }
		function toggle() { anim.toggle('slow');  }
		function show() { anim.showDiv('slow');  }

		function isVisible() { return (slider.style.height.replace('px', '') >= 1 || slider.style.height == '') ? true : false; }
		var oldOnclick = el.onclick;

		var newOnclick = function() {
			
			/* check if we are not already animating */
			if (!isLocked(cl)) {
			
				if (oldOnclick !== undefined) oldOnclick();
						
				/* lock and unlock this group */
				lock(cl);
				setTimeout('unlock(\''+cl+'\')', delayTime);

				/* loop through all the optiontogglers */
				for (walk=0; walk<optiontogglersIds.length; walk++){
					currenttoggler = optiontogglersIds[walk];
					if (el.id == currenttoggler) { 
						id = currenttoggler.replace('_toggler', '').replace('c_','');
						
						this.checked = true;
						show();
					} else {
						togglerid = currenttoggler.replace('_toggler', '').replace('c_','');
						if (calendars[togglerid]) calendars[togglerid].active = false;
						get(currenttoggler).checked = false;
						currentslider = get(currenttoggler.replace('_toggler', '_slider'));
						if(!isCollapsed(currentslider)) optiontogglersEffects[optiontogglersIds[walk]].hideDiv('slow');
					}
				}
			} else {
				if(isCollapsed(get(this.id.replace('_toggler', '_slider')))) this.checked = false;
				return false;
			}
			
		};		
		el.onclick = newOnclick;
	};
	for (optionAnimation in optionsAnimations) {
		temp(optionsAnimations[optionAnimation]);
	}
}

function togglersById(id) {
	var togglers = [];
	togglers[0] = get(id);
	generateTogglers(togglers);
	return true;
}

function togglers(className) {
	var togglers = getElementsByClassName(className);
	generateTogglers(togglers);
}

function generateTogglers(togglers) {

	temp = function(el) {
		el.checked = false;
		var sliderId = el.id.replace('_toggler', '_slider');
		var slider = get(sliderId);
		//alert(sliderId + document.location.href);
		
		if (slider == undefined) {
			debug('slider voor ' + el.id + ' niet gevonden.' );
			//return false;
		} else {
			togglersIds[togglersIds.length] = el.id;
			var anim = new animation(slider.id, {hidden:true});
			togglersEffects[el.id] = anim;
			
			
			function toggle() { anim.toggle('slow');  }
			function show() { anim.show('slow'); }

			var currentOnclick = el.onclick;

			el.onclick = function() { 
				
				if (!isLocked(el.id)) {
					lock(el.id);
					setTimeout('unlock(\''+el.id+'\')', delayTime+50);
					
					display(slider, 'block');
					if (hasClass(el, 'openOnly')) show();
					else toggle();
					
					if (currentOnclick != undefined) currentOnclick();
				} else {
					return false;
				}
			};
		}
	}
	
	for (toggler in togglers) {
		temp(togglers[toggler]);
	}
}

var ActionBar = function(element) {
			
	var items		= [];
	var elements	= element.childNodes;
	var activeActionItem;
	var looptime	= 500;
	var pausetime	= 7000;
	var refreshrate	= 15;
	var end = 15;

	function _init() {
		for (var walk = 0, len = elements.length; walk < len; walk++)
			if (elements[walk].className === 'actionitem')
				items[items.length] = new ActionItem(elements[walk]);
	}
	
	function _next() {
		if (items && items!=null && items[activeActionItem]!=null) {
			items[activeActionItem].scrollDown();
			activeActionItem = items[activeActionItem+1] == undefined ? 0 : activeActionItem + 1;
		}

	}
	
	var ActionItem = function(node) {

		var animationStartId;
		var animationStopId;
		var animationPauseId;
		var starttime;
		var currenttime;
	   
		// functions for showing
		this.scrollDown = function () {
			setTransparency(node, 0);
			node.style.top		= '0px';
			node.style.display	= 'block';
			starttime			= (new Date()).getTime();
			animationStartId	= setInterval(step, refreshrate);
		}
		
		function step() {
			
			currenttime = (new Date()).getTime();
			var looptimePercent		= (currenttime - starttime) / looptime;
			if (currenttime < starttime + looptime) {
				var animationPercent= Math.sin( looptimePercent * Math.PI / 2 );
				node.style.top		= end * animationPercent + 'px';
				setTransparency(node, parseInt( animationPercent * 100 ) ); //*100
			} else {
				clearInterval(animationStartId);
				node.style.top		= end + 'px';
				setTransparency(node, 100);
				setTimeout(hide, pausetime);
			}
		}
		
		// functions for hiding
		function hide() {
			animationStopId	= setInterval(hideStep, refreshrate);
		}
		
		function hideStep() {
			currenttime = (new Date()).getTime();
			if (currenttime < starttime + pausetime + (2 * looptime)) {
				var looptimePercent		= (currenttime - (starttime + looptime + pausetime)) / looptime;
				var animationPercent	= Math.sin( looptimePercent * Math.PI / 2 )
				setTransparency(node, 100 - parseInt(animationPercent * 100) ); //parseInt + *100
			} else {
				clearInterval(animationStopId);
				setTransparency(node, 0);
				node.style.display		= 'none';
				_next();
			}
		}
	}

	this.activate = function() {
		element.style.display	= 'block';
		activeActionItem		= 0;
		_next();
	};
	
	_init();

}

/* ACTION TICKER ANIMATION */
function doTickerAnimation(action, currentId) {

	var actionNumberDivs = get('actieHolder_'+action).childNodes.length;
	if (!IE) actionNumberDivs = (actionNumberDivs-1)/2;
	
	if (currentAnimationId == currentId) {
		setOpacity('actie_'+action, 100);
		setOpacity('actieHolder_'+action, 100);
		setHeight(get('actieHolder_'+action), null);
		makeVisible(get('actie_'+action));
		
		for (i=0; i < actionNumberDivs; i++) {
			/* display the div */
			setTimeout("showTickerAction(get('actie_"+action+"_"+i+"'), '"+currentId+"')", i * loopTime);
				
			/* fade in */
			setTimeout("toggleTheDiv(myDiv['"+action+"']["+i+"], '"+currentId+"')", i * loopTime);
				
			/* go down a bit */
			setTimeout("scroll('actie_"+action+"_"+i+"', 12, '"+currentId+"')", i * loopTime);
				
			/* fade out and set it to the top */
			setTimeout("resetDiv(myDiv['"+action+"']["+i+"], 'actie_"+action+"_"+i+"', '"+currentId+"')", i * loopTime + actionDisplayTime);
		}
		
		/* recursive call to do it again */
		setTimeout("doTickerAnimation('"+action+"', '"+currentId+"')", loopTime * (actionNumberDivs));
	}
}


/* FOR ANIMATION OF THE ACTIONS */
function scroll(scrollDiv, end, currentId) {
	if (currentAnimationId == currentId) {
		var huidigeHoogte = (get(scrollDiv).style.top == '') ? '0px' : get(scrollDiv).style.top;
		var hoogte = parseInt(huidigeHoogte.replace('px', ''));
		hoogte = (hoogte === NaN) ? 0 : hoogte;
		if (hoogte < end) {
			get(scrollDiv).style.top = (hoogte + 1) + 'px';
			setTimeout("scroll('"+scrollDiv+"', "+end+", '"+currentId+"')",40); // repaint every 40 millis
		}
	}
}


/* FOR ANIMATION OF THE CALENDARS */

function scrollFromTop(id, to) {
	var huidigeHoogte = get(id).scrollTop;
	if (huidigeHoogte < to) {
		get(id).scrollTop = huidigeHoogte + 3;
		setTimeout("scrollFromTop('"+id+"', "+to+")",15); // repaint every 40 millis
	} else if (huidigeHoogte > to) {
		get(id).scrollTop = huidigeHoogte - 3;
		setTimeout("scrollFromTop('"+id+"', "+to+")",15); // repaint every 40 millis
	} else {
		unlock(id);
	}
}


/* TOGGLE THE ACTION DIVS */

function toggleTheDiv(animation, currentId) {
	if (currentAnimationId == currentId) animation.fade();
}


/* FADE OUT AND SET THE CURRENT ACTION TO THE TOP */
function resetDiv(div, el, currentId) {
	if (currentAnimationId == currentId) {
		toggleTheDiv(div, currentAnimationId);
		setTimeout("resetToTop('"+el+"')", delayTime);
	}
}


/* USER CLICKED ANOTHER ACTION */
function actionClick(action) {
	if (!isLocked('animationLock')) {
		lock('animationLock');
		setTimeout("unlock('animationLock')", delayTime);
		if (currentActionAnimation!=action) {
			currentActionAnimation=action;
			currentAnimationId++;
			doTickerAnimation(action, currentAnimationId);
			hideAllExcept(action);
		}
	}
}

/* HIDE ALL THE ACTIONS EXCEPT THE PARAMETER */

function hideAllExcept(action) {
	for (element in effects) {
		if (getRealWidth(get('actieHolder_'+element)) == 400) {
			if (element != action) {
				effects[element].hide('slow');
			}
		}
	}
	effects[action].show('slow');
}


/* set the div to the top and do no display it */

function resetToTop(element) {
	get(element).style.top = '0px';
	noDisplay(get(element));
}

/* MAKE SURE IT IS VISIBLE */

function showTickerAction(element, currentId) {
	if (currentAnimationId == currentId) { 
		display(element, 'block');
	}
}

function animate(element, properties) {
	return new animation(element);
}

/* COMMENT */
function sweetToggle(elementId) {
	sweet = new animation(elementId);
	sweet.toggle('slow');
	sweet.fade();
}

/* COMMENT */
function sweetToggleObject(element) {
	element.toggle('slow');
	element.fade();
}



/* COMMENT */
function hideModal() {

	noDisplay(get('modalWindowContainer'));
	noDisplay(get('transparencyLayer'));
}

/**
 * @param {Object} username
 * @param {Object} password
 */
function handleLogin(username, password, redirectcommand) {
	
	var url = '/servlet/CommandServlet?command=checklogin&account=yes&call=ajax';
	// escape(username) added for & support in username, check with handel&wandel
	var postdata = 'username='+escape(username)+'&password=' + password.replace(/\+/g, '%2B');	
	var options = {
		'onSuccess': function(req, responseXML, responseText) {
			// Send a logon call to omniture
			s.events="event7";
			initOmniture();
			checkLogin(responseXML, redirectcommand);
		}
	};
	asyncHandleRequest(url, postdata, options); 
}

function checkLogin(xml, redirectcommand) {
	
	var validator = xml.getElementsByTagName('failed');
	
	if (validator.length == 0) { // user is valid
		
		var username		= getUniqueNode(xml, 'username');
		var customertype	= getUniqueNode(xml, 'customertype');
		var companyname		= getUniqueNode(xml, 'companyname');
		var initials		= getUniqueNode(xml, 'initials');
		var tussenvoegsel	= getUniqueNode(xml, 'tussenvoegsel');
		var surname			= getUniqueNode(xml, 'surname');
		var lastlogin		= getUniqueNode(xml, 'lastlogin');
		var lastloginip		= getUniqueNode(xml, 'lastloginip');
		var lastloginproxyip= getUniqueNode(xml, 'lastloginproxyip');
		
		var adverteren = (zakelijk == true) ? "zakelijk" : "particulier";
		
		if (subdomain=='hc' || customertype != adverteren || breadcrumbs.type == "START" || (page == "speurder maken" && viacode == "MRV")) {
			reloadAfterLogin = true;
		}
		
		if (redirectcommand != null) {
			if (redirectcommand=='registeredusercommand') {
				window.location.href = '/mijn-account/' ;
			} else {
				window.location.href = '/servlet/CommandServlet?command='+redirectcommand ;
			}
			return;
		} else if (reloadAfterLogin) {
			window.location.reload();
			return;
		} else {
			//update user interface 
			tmg('.logged_in').get(0).html('<li>welkom <span style="font-weight:bold" title="laatste bezoek: '+lastlogin+'">'+initials+' ' + 
				(tussenvoegsel && tussenvoegsel != 'null' ? tussenvoegsel : '') + ' ' + surname + '</span>' +
				(companyname ? ' van <span style="font-weight:bold;">' + companyname + '</span>' : '') + '</li>' +
				'<li><a href="/loguit/' + '" title="log uit" class="loguit">log uit</a></li>');
			
			var li = document.createElement('li');
			li.innerHTML = '<a href="/mijn-account/">mijn account</a>';
			tmg('#header').find('ul')[0].appendChild(li);
			
			setHtml(get('heeftaleenaccount'), 'welkom<br />' + initials + '. ' + surname);
			addClass(get('needtologin'), 'hidden');
			tmg('#login').hide();
//			removeClass(get('laatstebezoek'), 'hidden');
//			setHtml(get('laatstebezoek'), 'laatste bezoek: ' + lastlogin);
//			get('laatstebezoek').setAttribute('title', 'uw ip adres van het laatste bezoek was: '+ lastloginip);
			removeClass(get('loguitlink'), 'hidden');
			// also update new kind of login (see breadcrumbs)
			if (tmg('#loginOptions').html()) {
				var newhtml = 'welkom <strong>' + initials + '. ' + surname + '</strong>';
				if (companyname) {
					newhtml += '<br/><span class="small">' + companyname + '</span>';
				}
				newhtml += '<p id="loguitlinkbreadcrumbs"><a href="/mijn-account/" title="Mijn account">mijn account</a> - ';
				newhtml += '<a href="/servlet/CommandServlet?command=logout" title="log uit">log uit</a> - ';
				newhtml += '<a href="$href" id="beginopnieuwbutton">begin opnieuw</a></p>';
				tmg('#loginOptions').html(newhtml);
				tmg('#rightColumn').toggle();
				
			}
			hide('breadcrumb_registreer');
		}
	} else {
		var failnum = getUniqueNode(xml, 'failnum'); 
		var falmsg = getUniqueNode(xml, 'failmsg');
		//update user interface		
		if (failnum && failnum == 4) 
			alert('Uw medewerker account staat op \'uit dienst\'. U kan niet meer inloggen');
		else {
			get('wachtwoordvergetenlink').style.color = 'darkred';		
			alert('uw gebruiksnaam en/of wachtwoord is niet geaccepteerd');
		}
		return false;
	}
}

/*
 * extra functie voor modalCategoryWindow
 * derde argument geeft aan in hoeveel kolommen de tekst gezet moet worden
 * default is 2
 */
function modalCategoryWindowCols(rubriekid, groepid, name, numcols, prevgroep, formaat, calendarid, forceShowRubriek, uitgevernaam) {
	setClass(get('modalWindowIcon'), name.toLowerCase());	
	handleCategoryRequest(rubriekid, groepid, numcols, prevgroep, formaat, calendarid, forceShowRubriek, uitgevernaam);
}

function modalCategoryWindow(rubriekid, groepid, name, prevgroep, formaat, calendarid, forceShowRubriek, uitgevernaam) {
	if (!prevgroep || prevgroep==null || typeof(prevgroep)=='undefined')
		prevgroep=-1;
	modalCategoryWindowCols(rubriekid, groepid, name, 3, prevgroep, formaat, calendarid, forceShowRubriek, uitgevernaam);
	//trackPage('/speurder/kies-krant/'+uitgevernaam+'/');
}

function startTripledealBetaling(betaalmethodeId, speurderId){
		
	var result = false;
	var xml = defaultHandleRequest('/servlet/CommandServlet?command=findbetaalredirecturl', 'bmId=' + betaalmethodeId + "&spId=" + speurderId );
	/* get the categories from the xml */
	
	if (xml != null) {
		var status = xml.getElementsByTagName("status")[0].firstChild.nodeValue;
		
		if (status != -1) {
			result = true;
			self.name = 'betalenmainwindow';
			redirecturl = xml.getElementsByTagName("redirecturl")[0].firstChild.nodeValue;
			var w = window.open(redirecturl, 'betaal', 'status=yes,toolbar=yes,scrollbars=yes,resizable=yes,menubar=no,width=550,height=500');
			w.focus();
		}
	}
	 
	return result;
}

function betalingVerwerkt(betaalmethodeId, speurderId, speurderNummer, actietype, via) {
	// Controleert of de betaling verwerkt is van de sessie basket en zo ja start het betalen verwerkt scherm.
	var siteurl = '';
	var userloggedin = '';
	var userbeheer = '';
	var ordernummer = '';	
	var speurdernummer = '';	
	var ip_basket = '';
	var xml = defaultHandleRequest('/servlet/CommandServlet?command=isbetalingverwerkt', 'bmId=' + betaalmethodeId + '&speurdernummer=' + speurderNummer + '&spId=' + speurderId + '&actietype=' + actietype); 
	
	/* get the categories from the xml */	   
	if (xml != null) {
		var status = xml.getElementsByTagName("status")[0].firstChild.nodeValue;  
		var errormsg="";
		if (xml.getElementsByTagName("errormsg")[0].firstChild!=null)
 			errormsg = xml.getElementsByTagName("errormsg")[0].firstChild.nodeValue;	 
		siteurl = xml.getElementsByTagName("siteurl")[0].firstChild.nodeValue;
		userpostpaid = xml.getElementsByTagName("userpostpaid")[0].firstChild.nodeValue;
		if (userpostpaid == null) {
			userpostpaid = 'false';
		}			 
		
		userloggedin = xml.getElementsByTagName("userloggedin")[0].firstChild.nodeValue;
		if (userloggedin == null) {
			userloggedin = 'false';
		}
		
		if (xml.getElementsByTagName("userbeheer")[0] != undefined) {
			userbeheer = xml.getElementsByTagName("userbeheer")[0].firstChild.nodeValue;  			 

			if (userbeheer == null) {
				userbeheer = 'false';
			} else if (xml.getElementsByTagName("ordernummer")[0] != undefined) {
				ordernummer = xml.getElementsByTagName("ordernummer")[0].firstChild.nodeValue;
					
				if (xml.getElementsByTagName("speurdernummer")[0] != undefined) {
					speurdernummer = xml.getElementsByTagName("speurdernummer")[0].firstChild.nodeValue;
				}				
			}
		}		
		
		if (xml.getElementsByTagName("ip_basket")[0] != undefined) {
			ip_basket = xml.getElementsByTagName("ip_basket")[0].firstChild.nodeValue;
		}
	}	 
	
	 // Status 1 = niet brs, ok (-1 = not ok)
	 // status 100 = brs, ok (-100 = not ok)

	if ( status == 1 ) {		
			// Geen brs betaling en gelukt: redirect.
			// Opmerking: bij brs betaling wordt redirect in paymentsubmitted gedaan.		   
			var command = 'http://' + siteurl + '/servlet/CommandServlet?command=betalingverwerkt&status=' + status  + '&userloggedin=' + userloggedin + '&userbeheer=' + userbeheer + '&ordernummer=' + ordernummer + '&speurdernummer=' + speurdernummer + '&actietype=' + actietype 
			+ '&userpostpaid=' + userpostpaid + '&siteurl=' + siteurl + '&via='+via + "&remotebetalen="+remotebetalen + "&ip_basket=" + ip_basket;
			window.location = command;						
			window.focus();		
	}  else if ( (status == -100) || (status == -1) ) {
			// Fout bij betaling (via brs of niet via brs)
			var command = 'http://' + siteurl + '/speurder/betalen/?errormsg=' + errormsg ;
			window.location = command;						
			window.focus();					
	}
	
	return siteurl;
}

function postcodeCompletion(theForm, postcode, huisnummer) {
		var xml = defaultHandleRequest('/servlet/CommandServlet?command=findstreetcommand',
			   'postcode='+escape(postcode) + '&huisnummer='+escape(huisnummer));			   
		if (xml) {
			var address = xml.getElementsByTagName("address")[0];
			if (address || address.childNodes.length > 0) {
				var street = address.getElementsByTagName("street")[0];
				var city = address.getElementsByTagName("city")[0];
				theForm.adres.value = street.childNodes[0].nodeValue;
				theForm.woonplaats.value = city.childNodes[0].nodeValue;
			}
		}
		trackPage('/registreer/postcodezoek/');
}

function postcodeBonCompletion(theForm, postcode, huisnummer) {
		var xml = defaultHandleRequest('/servlet/CommandServlet?command=findstreetcommand',
			   'postcode='+escape(postcode) + '&huisnummer='+escape(huisnummer));			   
		if (xml) {
			var address = xml.getElementsByTagName("address")[0];
			if (address || address.childNodes.length > 0) {
				var street = address.getElementsByTagName("street")[0];
				var city = address.getElementsByTagName("city")[0];
				theForm.bonadres.value = street.childNodes[0].nodeValue;
				theForm.bonwoonplaats.value = city.childNodes[0].nodeValue;
			}
		}
		trackPage('/registreer/postcodezoek/');
}

function fillModalWithCategories(xml, rubriekid, groepid, numcols, prevgroep, formaat, calendarid, forceShowRubriek, uitgevernaam) {	
	
	/* buildHtml will be the return string */
	var buildHtml	= '';	
	/* get the categories from the xml */
	var error = xml.getElementsByTagName("error")[0];
	var statuscode = -1;
	if ( (error != null) && (error != undefined) ) {
		var status = error.getElementsByTagName('status')[0];		
		if ( (status != null) && (status != undefined) ) {
			statuscode = status.firstChild.nodeValue;
		}
	}
	
	if (statuscode == 20) {
		setError("Uw heeft nog geen hoofdrubriek gekozen, Klik op <a href='/speurder/'>deze link</a> om de hoofdrubriek opnieuw te selecteren");
		return false; 
	} else if (statuscode != -1) {
		var statusmsg = error.getElementsByTagName("msg")[0];
		if ((statusmsg != null) && (statusmsg != undefined) && (status.firstChild.nodeValue != '') &&
				 (status.firstChild.nodeValue != 'none') ) {
			setError(error.getElementsByTagName("msg")[0].firstChild.nodeValue);
			return false;
		} else {
			setError("Er is geen hoofdrubriek gekozen, Klik op <a href='/speurder/'>deze link</a> om de hoofdrubriek te selecteren");
			hideModal();
			return false;
		}										
	} 

	var categories	= xml.getElementsByTagName("hcat");	
	var len			= xml.getElementsByTagName("hcat").length;
	var aantalSubrubrieken = 0;
	if (uitgevernaam == undefined) {
		uitgevernaam = '';
	}
	
	/* loop throug the categories */
	for (i=0; i<len; i++) {
				
		/* this is the 'hoofdrubriek' */
		var parentId	= categories[i].childNodes[getNode(0)].firstChild.nodeValue;		
		var parentName	= '';
		if (categories[i].childNodes[getNode(1)].firstChild != null) {
			parentName = categories[i].childNodes[getNode(1)].firstChild.nodeValue
		} 
		
		/* get all the children from the 'hoofdrubriek' */
		var children	= categories[i].childNodes[getNode(2)].childNodes;
		var childrenLen	= children.length;
		
		if (!IE) {
			childrenLen = (childrenLen-1)/2;
		}
		
		buildHtml		+= '\r\n\t<h2>' + parentName + '</h2>\r\n';
		buildHtml		+= '\t<div class="column">\r\n';

		/* prepare for column calculations */
		var col = 0;
		var colincr = Math.ceil(childrenLen / numcols); /* aantal items in eerste kolom */
		if ( colincr < 5 ) {
			colincr = 5;
		}
		var colend = colincr - 1;
		var extraparam='';
		if (prevgroep && prevgroep!=null && typeof(prevgroep)!='undefined' && prevgroep!=-1 && prevgroep!=groepid ){
			// resets the speurdermaken when the rubriek has been changed and the editor is a lp editor
			extraparam='&reset=true';
		}

		/* loop throug the 'rubrieken' */
		for (walk=0; walk<childrenLen; walk++) {
			var id		=  children[getNode(walk)].childNodes[getNode(0)].firstChild.nodeValue;
			var naam	=  children[getNode(walk)].childNodes[getNode(2)].firstChild.nodeValue;
			
			/* add the links to the return string*/
			if (page=="kies hoofdrubriek") {
				buildHtml	+= '\t\t<a onclick="document.location.href=\'/speurder/maken/?rubriek='+ id +'&groepid='+groepid+'\';" title="Geef een advertentie op in de subrubriek '+naam+'.">' + naam + '</a>\r\n';
				aantalSubrubrieken += 1;
			} else {
				if (formaat == undefined) {
					buildHtml	+= '\t\t<a href="/speurder/maken/?groepid=' + groepid
						+ '&rubriek='+id+extraparam+'" title="Geef een advertentie op in de rubriek '+naam+'.">' + naam + '</a>\r\n';			
				} else {
					//buildHtml	+= '\t\t<a href="/servlet/CommandServlet?command=setsubrubriek&formaat=' + formaat + '&groepid=' + groepid
					//	+ '&rubriekid=' + id + extraparam  
					//	+ '" title="Geef een advertentie op in de subrubriek '+naam+'.">' + naam + '</a>\r\n';				
					buildHtml	+= '\t\t<a onclick="setRubriek(\''+formaat+'\', \''+ id +'\', \''+ calendarid +'\', \''+ uitgevernaam +'\');" title="Geef een advertentie op in de subrubriek '+naam+'.">' + naam + '</a>\r\n';
					aantalSubrubrieken += 1;
				}
			}
			if ( walk == colend ) {
				buildHtml += '</div><div class="column">';
				col++;
				colincr = Math.ceil( (childrenLen-walk-1)/(numcols-col) );
				if ( colincr < 5 ) {
					colincr = 5;
				}
				colend += colincr;
			}
		}
		
		buildHtml		+= '\t</div>\r\n'
	}

	/* eerst controleren op de specials */
	if (groepid == 2 && inArray(geldigeActies, 'SECRETARESSEDAG')) // algemeen
		var heading = '<div class="margin"><span class="bold blue"> verras uw secretaresse met een Speurder en een gratis bloemetje</span>'
				+ '<br />Selecteer onder Felicitaties, Secretaressedag of <a style="display:inline;" href="/servlet/CommandServlet?command=speurdermaken&groepid=2&rubriek=01LQ">klik hier</a>'
				+ '<br />Deze secretaressedag actie sluit op 16 april om 13:00 uur.</div>';
	else if (groepid == 6 && inArray(geldigeActies, 'KONINGINNEDAG')) // algemeen
		var heading = '<div class="margin"><span class="bold orange"> Koninklijke korting op Koninginnedag!</span>'
				+ '<br />25% korting op al uw Speurders in de Woonkrant van de Telegraaf op Koninginnedag!</div>';
	else if (groepid == 3 && zakelijk == true && inArray(geldigeActies, 'CABRIOACTIE')) // algemeen
		var heading = '<div class="margin"><span class="bold blue"> Het wordt steeds leuker op de weg!</span>'
				+ '<br />Plaats uw Speurder in de Cabrio- en coup&eacute;special in De Telegraaf van 25 april met een gratis doorplaatsing naar zaterdag 26 april.</div>';
	
	/* nu controleren op de winkels */
	else
		var heading = '';
		
	// Alleen rubriek window indien:
	// 1. subrubrieken van de uitgever > 1
	// 2. Nog geen plaatsingen gezet (anders is rubriek al gekozen)
	// 3. Indien calendar 59 (echo rotterdam) : nog geen plaatsingen bij calendar hc gekozen. 
	// 4. indien calendar hc                  : nog geen plaatsingen bij calendar 59 gekozen.
	var publisher = formaat;	
	if (publisher !='HC' && publisher !='HDC' && typeof(calendars)!="undefined") {				
		publisher = calendars[calendarid].publisher;
	}
	
	if ( aantalSubrubrieken > 1 && (typeof(publishers)=="undefined" || (!publishers[publisher] 
	        || (!publishers[publisher].hasRubriek && (!rubriekid || rubriekid.length==0 )) || (forceShowRubriek == true) )) ) {		
		modalRubriekWindow(uitgevernaam, heading + buildHtml);		
	} else if ( (calendarid != '') && (calendarid != 'null') ) {				
		// verberg modal window
		hideModal();

		// activate calendar
	    if (calendarid == 'hc') {
			disableActions(); 			
			if (!hcClustersSet) {
			 	modalHcWindow();
			    window.location='#';  												 					
			}	else {						 	
				display(get('HcSelect_slider'), this.checked);
			}  					 	
		} else if (calendarid == 'hdc') {
				disableActions(); 				
				if (!hdcClustersSet) {
					 modalHdcWindow(); 
					 window.location='#';  
				} else { 
					display(get('HdcSelect_slider'), this.checked); 
				}
		} else if (calendarid == 1022) { 			 
			recalcUberKorting();
	    } else if (calendarid >= 1000) {			
			activateCalendar(calendarid, true); 
			showOptionToggler(calendarid);					
		} else {			
			activateCalendar(calendarid, true); 
			showSelectCalendar(calendarid);
		}	
		recalc();	
	}			 
}




function fillDivWithCategories(xml, groepid, numcols, prevgroep, formaat, calendarid, forceShowRubriek, uitgevernaam) {	
	
	/* buildHtml will be the return string */
	var buildHtml	= '';	
	/* get the categories from the xml */
	var error = xml.getElementsByTagName("error")[0];
	var statuscode = -1;
	if ( (error != null) && (error != undefined) ) {
		var status = error.getElementsByTagName('status')[0];		
		if ( (status != null) && (status != undefined) ) {
			statuscode = status.firstChild.nodeValue;
		}
	}
	
	if (statuscode == 20) {
		setError("Uw heeft nog geen hoofdrubriek gekozen, Klik op <a href='/speurder/'>deze link</a> om de hoofdrubriek opnieuw te selecteren");
		return false; 
	} else if (statuscode != -1) {
		var statusmsg = error.getElementsByTagName("msg")[0];
		if ((statusmsg != null) && (statusmsg != undefined) && (status.firstChild.nodeValue != '') &&
				 (status.firstChild.nodeValue != 'none') ) {
			setError(error.getElementsByTagName("msg")[0].firstChild.nodeValue);
			return false;
		} else {
			setError("Er is geen hoofdrubriek gekozen, Klik op <a href='/speurder/'>deze link</a> om de hoofdrubriek te selecteren");
			hideModal();
			return false;
		}										
	} 

	var categories	= xml.getElementsByTagName("hcat");	
	var len			= xml.getElementsByTagName("hcat").length;
	var aantalSubrubrieken = 0;
	if (uitgevernaam == undefined) {
		uitgevernaam = '';
	}
	
	/* loop throug the categories */
	for (i=0; i<len; i++) {
				
		/* this is the 'hoofdrubriek' */
		var parentId	= categories[i].childNodes[getNode(0)].firstChild.nodeValue;		
		var parentName	= '';
		if (categories[i].childNodes[getNode(1)].firstChild != null) {
			parentName = categories[i].childNodes[getNode(1)].firstChild.nodeValue
		} 
		
		/* get all the children from the 'hoofdrubriek' */
		var children	= categories[i].childNodes[getNode(2)].childNodes;
		var childrenLen	= children.length;
		
		if (!IE) {
			childrenLen = (childrenLen-1)/2;
		}
		
		buildHtml		+= '\r\n\t<h2>' + parentName + '</h2>\r\n';
		buildHtml		+= '\t<div class="column">\r\n';

		/* prepare for column calculations */
		var col = 0;
		var colincr = Math.ceil(childrenLen / numcols); /* aantal items in eerste kolom */
		if ( colincr < 5 ) {
			colincr = 5;
		}
		var colend = colincr - 1;
		var extraparam='';
		if (prevgroep && prevgroep!=null && typeof(prevgroep)!='undefined' && prevgroep!=-1 && prevgroep!=groepid ){
			// resets the speurdermaken when the rubriek has been changed and the editor is a lp editor
			extraparam='&reset=true';
		}

		var showkorting=false;
		/* loop throug the 'rubrieken' */
		for (walk=0; walk<childrenLen; walk++) {
			var id		=  children[getNode(walk)].childNodes[getNode(0)].firstChild.nodeValue;
			var naam	=  children[getNode(walk)].childNodes[getNode(2)].firstChild.nodeValue;
			if (id!='99ZZ' || sdesk!='') {
				
				var extrapre='';
				var extrapost='';
				if (groepid==10 && naam.indexOf('Kennismaking')>-1) {
					extrapost='<font color=red><b> *</b></font>';
					showkorting=true;
				}
        if (groepid==8) {
					showkorting = true;
				}
				/* add the links to the return string*/
				buildHtml	+= '\t\t<a onclick="document.location.href=\'/speurder/maken/?rubriek='+ id +'&groepid='+groepid+'\';" title="Geef een advertentie op in de subrubriek '+naam+'.">'+extrapre + naam + extrapost+'</a>\r\n';


				aantalSubrubrieken += 1;
				if ( walk == colend ) {
					buildHtml += '</div><div class="column">';
					col++;
					colincr = Math.ceil( (childrenLen-walk-1)/(numcols-col) );
					if ( colincr < 5 ) {
						colincr = 5;
					}
					colend += colincr;
				}
			}
		}

		buildHtml		+= '\t</div>\r\n';
			if (showkorting) {
				if (groepid==10) {
					buildHtml		+= '\t<div class=module style="width:250px;float:right;color:red;">*50% korting op: BasisSpeurder, TekstSpeurder en TekstSpeurder met layout</div>\r\n';
				}
				if (groepid == 8) {
					buildHtml += '<div class="module" style="width:250px;float:right;"><p>Voor de winkel Erotiek gelden de regels van het Erotiekconvenant. Verplicht vermelden van vergunningnummer, KVK nummer of BTW nummer met postcode. Uitgezonderd zijn de rubrieken: 0906-lijnen, SMS-diensten, Mobiele Video\'s 18+ en Postorders</p></div>';
				} 
				/*
				else {
					if (groepid==2) {
						buildHtml		+= '\t<div class=module style="width:250px;float:right;color:red;">Tot eind mei 2 speurders plaatsen, 1 betalen én 25% korting in deze rubriek voor instellingen met het CBF-Keurmerk of CBF-Certificaat.<a onclick="document.location.href=\'http://www.cbf.nl/Database_goede_doelen/1_Goededoelen.php?Type=CBFKeur\'" href="http://www.cbf.nl/Database_goede_doelen/1_Goededoelen.php?Type=CBFKeur" target="_blank">CBF-website</a></div>\r\n';
					}
				}
				*/
			}
	}
	/* eerst controleren op de specials */
	if (groepid == 2 && inArray(geldigeActies, 'SECRETARESSEDAG')) // algemeen
		var heading = '<div class="margin"><span class="bold blue"> verras uw secretaresse met een Speurder en een gratis bloemetje</span>'
				+ '<br />Selecteer onder Felicitaties, Secretaressedag of <a style="display:inline;" href="/servlet/CommandServlet?command=speurdermaken&groepid=2&rubriek=01LQ">klik hier</a>'
				+ '<br />Deze secretaressedag actie sluit op 16 april om 13:00 uur.</div>';
	else if (groepid == 6 && inArray(geldigeActies, 'KONINGINNEDAG')) // algemeen
		var heading = '<div class="margin"><span class="bold orange"> Koninklijke korting op Koninginnedag!</span>'
				+ '<br />25% korting op al uw Speurders in de Woonkrant van de Telegraaf op Koninginnedag!</div>';
	else if (groepid == 3 && zakelijk == true && inArray(geldigeActies, 'CABRIOACTIE')) // algemeen
		var heading = '<div class="margin"><span class="bold blue"> Het wordt steeds leuker op de weg!</span>'
				+ '<br />Plaats uw Speurder in de Cabrio- en coup&eacute;special in De Telegraaf van 25 april met een gratis doorplaatsing naar zaterdag 26 april.</div>';
	
	/* nu controleren op de winkels */
	else
		var heading = '';
		
	// Alleen rubriek window indien:
	// 1. subrubrieken van de uitgever > 1
	// 2. Nog geen plaatsingen gezet (anders is rubriek al gekozen)
	// 3. Indien calendar 59 (echo rotterdam) : nog geen plaatsingen bij calendar hc gekozen. 
	// 4. indien calendar hc                  : nog geen plaatsingen bij calendar 59 gekozen.
	var publisher = formaat;	
	if (publisher !='HC' && publisher !='HDC' && typeof(calendars)!="undefined") {		
		publisher = calendars[calendarid].publisher;
	}
	tmp=buildHtml;

	
	var obj=document.getElementById('subrubriekdiv'+groepid);
	try {
		obj.innerHTML=tmp;
	} catch (ex) {
	}
}


function Publisher(name, options) {
	
	// validate
	if (options == undefined) return false;
	if (options.rubriekGekozen == undefined) options.rubriekGekozen = false;
	
	// place default values in object
	this.hasRubriek = options.rubriekGekozen;
	
}

function setRubriek(formaat, rubriekid, calendarid, uitgevernaam) {	
	
	var extraparam = '';
	var url = '/servlet/CommandServlet?command=setsubrubriek&formaat=' + formaat + '&calendarid=' + calendarid 
		+ '&groepid=' + groepid + '&rubriekid=' + rubriekid + extraparam;
	if ( (uitgevernaam != undefined) && (uitgevernaam != null) ) {
		url += '&uitgevernaam=' + uitgevernaam;
	}
	
	var postdata = null;
	var options = {onSuccess:function(req){
		handleSetRubriek(req.responseXML)
	}};
	asyncHandleRequest(url, postdata, options);
	trackPage("/speurder/kies-krant/subrubriek/"+rubriekid);
}

function handleSetRubriek(xml) {
	
	/* get the categories from the xml */
	var responseXML	= xml.getElementsByTagName("response")[0];
	var calendarId = responseXML.getElementsByTagName("calendarid")[0];	

	var error = responseXML.getElementsByTagName("error")[0];
	if ( (error != null) && (error != undefined)&& (calendarId != null) && (calendarId != undefined)) {
		var status = error.getElementsByTagName('status')[0];		
		if ( (status != null) && (status != undefined) ) {
			var statuscode = status.firstChild.nodeValue;
			if (statuscode == 20) {
				setError('uw sessie is verlopen'); 
			} else if (statuscode != -1) {
				var statusmsg = error.getElementsByTagName("msg")[0];
				if ((statusmsg != null) && (statusmsg != undefined) && (status.firstChild.nodeValue != '') &&
						 (status.firstChild.nodeValue != 'none') ) {
					setError(error.getElementsByTagName("msg")[0].firstChild.nodeValue);
					return false;
				} else {
					setError('Er is een communicatiefout opgetreden, probeert u het nogmaals');
					hideModal();
					return false;
				}										
			} else {
				var formaatnaam = responseXML.getElementsByTagName("formaatnaam")[0].firstChild.nodeValue;
				var uitgevernaam = '';
				if ( (responseXML.getElementsByTagName("uitgevernaam")[0].firstChild != null) && (responseXML.getElementsByTagName("uitgevernaam")[0].firstChild != undefined)) {
					 uitgevernaam = responseXML.getElementsByTagName("uitgevernaam")[0].firstChild.nodeValue;						
				}				
									
				var calid = calendarId.firstChild.nodeValue;
				var rubriekomschrijving = responseXML.getElementsByTagName("rubriekomschrijving")[0];
				var hoofdrubrieknaam = responseXML.getElementsByTagName("hoofdrubrieknaam")[0];				
				var groepnaam = responseXML.getElementsByTagName("groepnaam")[0];				
				
				if ( (calid != '') && (calid != 'null') && (rubriekomschrijving !=null) && (rubriekomschrijving != undefined) ) {
					// verberg modal window
					
					hideModal();				
					// activate calendar
				    if (calid == 'hc') {
						disableActions(); 
						showSelectCalendar(0); 
						if (!hcClustersSet) {
						 	modalHcWindow();
  						    window.location='#';  												 					
						}	else {						 	
							display(get('HcSelect_slider'), this.checked);
						}  					 	
					} else if (calid == 'hdc') {
						disableActions(); 
						showSelectCalendar(0); 
						if (!hdcClustersSet) {
							 modalHdcWindow(); 
							 window.location='#';  
					    } else { 
							display(get('HdcSelect_slider'), this.checked); 
						} 
					} else if (calid == 1022) { 			 
						recalcUberKorting();						
					} else if (calid >= 1000) {						  		
						activateCalendar(calid, true); 
						showOptionToggler(calid);			
					} else {
						activateCalendar(calid, true); 
						showSelectCalendar(calid, true);
					}	
					
					// Recalc opnieuw
					recalc();
														
					// Update the publisher(s)					
					if (formaatnaam == 'HDCRCO') {
						publishers['DDT'].hasRubriek = true;
						publishers['SPI'].hasRubriek = true;
						publishers['HDC'].hasRubriek = true;						
					} else {
						publishers[formaatnaam].hasRubriek = true;				
					}		
														
					// update de user interface 
					var rubriekTekst = '';
					
					
					if ( (groepnaam !=null) && (groepnaam != undefined)) {
						rubriekTekst += groepnaam.firstChild.nodeValue + ' / ';
					}
					if ((hoofdrubrieknaam !=null) && (hoofdrubrieknaam != undefined)) {
						rubriekTekst += hoofdrubrieknaam.firstChild.nodeValue + ' / ';
					}
					
				
					rubriekTekst += rubriekomschrijving.firstChild.nodeValue;
					setHtml(get('c_' + calid + '_rubriek'), rubriekTekst);					
					
					if (calid == 'hc') {
						// Zet ook Echo rotterdam
						setHtml(get('c_59_rubriek'), rubriekTekst);	 
					} else if (calid == '59') {
						// Zet ook hc rubriek
						setHtml(get('c_hc_rubriek'), rubriekTekst);
					}					
					
					
					return true;
				} else {
					setError('Er is een communicatiefout opgetreden, probeert u het nogmaals (calendar ' + calid + ' bestaat niet)' );
					return false;
				}
			}

	    } else {
			setError('Er is een communicatiefout opgetreden, probeert u het nogmaals');		
			return false;
		}
	} else {
		setError('Er is een communicatiefout opgetreden, probeert u nogmaals');		
		return false;
	}
}


/* the request handler for getting categories*/
/* extended with second argument, numcols: number of columns desired */
function handleCategoryRequest(rubriekid, groepid, numcols, prevgroep, formaat, calendarid, forceShowRubriek, uitgevernaam) {	
	
	var url = '/servlet/CommandServlet?command=findcategoriescommand';
	var postdata = '&groepid='+groepid+'&view=xml';
	if (formaat != undefined) {
		postdata += '&formaat=' + formaat;	
	}
	if (rubriekid != undefined) {
		postdata += '&rubriek=' + rubriekid;	
	}
	
	var options = { 'onSuccess': function( req, xml, response){
		if (page=="kies hoofdrubriek") {					
			fillDivWithCategories(req.responseXML, groepid, 5, prevgroep, formaat, calendarid, forceShowRubriek, uitgevernaam);
		} else {
			fillModalWithCategories(req.responseXML, rubriekid, groepid, numcols, prevgroep, formaat, calendarid, forceShowRubriek, uitgevernaam);

		}
	} , 'onFailure': function( req, xml, response){
		setError("Er is nog geen hoofdrubriek geselecteerd, Klik op <a href='/speurder/'>deze link</a> om de hoofdrubriek te selecteren ");
	} };
	
	if (page=="kies hoofdrubriek") {			
		options.get=true;
		url +=postdata ;
		postdata = null ;
	} else {
		options.get=false;
	}
	
	asyncHandleRequest(url, postdata, options);
	return;
}

function handlePriceIndication(async) {

	
	if (refreshcountprijsindicatie != refreshcount) {
		// A real update was requested
		
		if (async == null) 
			async = false;
		url = '/servlet/CommandServlet?command=prijsindicatie' + '&refresh=' + refreshcount;
		/* get the xml */
		if (async) {
			// only do the call for caching 
			var req = asyncHandleRequest(url, '', {
				'onSuccess': function(r, xml, txt){
				
				}
			})
		}
		else {
			var xml = defaultHandleRequest(url);
			
			if (xml == null) 
				return;
			
			/* controleer eerst of de Ajax-call wel iets zinnigs heeft teruggegeven */
			var test = xml.getElementsByTagName("DDTprijs");
			
			if (test.length > 0) {
				/* get the categories from the xml */
				var error = xml.getElementsByTagName("error")[0];
				if (error != null) {
					var status = error.getElementsByTagName("status")[0].firstChild.nodeValue;
					var msg = error.getElementsByTagName("msg")[0].firstChild.nodeValue;
					if (status == 20) {
						/* sessie verlopen: verwijs terug naar voorpagina */
						var command = '/?errormsg=' + msg ;
						window.location = command;
						window.focus();
						return;
					}
				}
				var status = error[0]
				var DDTPrice = xml.getElementsByTagName("DDTprijs")[0].firstChild.nodeValue;
				var specialPrice = DDTPrice;
				if (xml.getElementsByTagName("specialprijs")[0] != null) {
					specialPrice = xml.getElementsByTagName("specialprijs")[0].firstChild.nodeValue;
				}
				var DDTMm = xml.getElementsByTagName("DDTmm")[0].firstChild.nodeValue;
				var specialMm=DDTMm;
				if (xml.getElementsByTagName("specialmm")[0]!=null) {
					specialMm = xml.getElementsByTagName("specialmm")[0].firstChild.nodeValue;
				}

				if (check('mmIndicationSpecial')) 
					setHtml(get('mmIndicationSpecial'), specialMm);
				
				setPriceIndication(xml,'HDC108');
				setPriceIndication(xml,'HDC108','HDC108REGIONAAL');
				setPriceIndication(xml,'EC');
				setPriceIndication(xml,'EC','ECLOKAAL');
				setPriceIndication(xml,'HDC9011');
				setPriceIndication(xml,'HDC12');
				setPriceIndication(xml,'HDC1014');
				setPriceIndication(xml,'M14');
				setPriceIndication(xml,'MHC');
				setPriceIndication(xml,'WHC');
				setPriceIndication(xml,'DDT');
				setPriceIndication(xml,'DDT','DDTLANDELIJK');
				setPriceIndication(xml,'SPI');
					
			}
			refreshcountprijsindicatie = refreshcount;
		}
	}
}

function setPriceIndication(xml,clustername, targetdiv) {
	if (targetdiv==null)
	{
		targetdiv=clustername;
	}
	if(check('priceIndication'+clustername) && check('mmIndication'+clustername) ) {
		if (xml.getElementsByTagName(clustername + "mm")[0] != undefined && xml.getElementsByTagName(clustername + "prijs")[0] != undefined) {
			var tmpMm = xml.getElementsByTagName(clustername + "mm")[0].firstChild.nodeValue;
			var tmpPrice = xml.getElementsByTagName(clustername + "prijs")[0].firstChild.nodeValue;
			setHtml(get('priceIndication' + targetdiv), tmpPrice);
			setHtml(get('mmIndication' + targetdiv), tmpMm);
		} else {
			debug("Cluster " + clustername + " komt niet voor in de prijsindicatie XML")
		}
	}
}

function setPriceIndications(xml) {
		
	if (refreshcountprijsindicatie != refreshcount) {
		var test = xml.getElementsByTagName("DDTprijs");
		
		if (test.length > 0) {
			var DDTPrice = xml.getElementsByTagName("DDTprijs")[0].firstChild.nodeValue;
			var specialPrice = DDTPrice;
			if (xml.getElementsByTagName("specialprijs")[0] != null) {
				specialPrice = xml.getElementsByTagName("specialprijs")[0].firstChild.nodeValue;
			}
			var DDTMm = xml.getElementsByTagName("DDTmm")[0].firstChild.nodeValue;
			var specialMm=DDTMm;
			if (xml.getElementsByTagName("specialmm")[0]!=null) {
				specialMm = xml.getElementsByTagName("specialmm")[0].firstChild.nodeValue;
			}
			
			if (check('mmIndicationSpecial')) 
				setHtml(get('mmIndicationSpecial'), specialMm);
			
			setPriceIndication(xml,'HDC108');
			setPriceIndication(xml,'HDC108','HDC108REGIONAAL');
			setPriceIndication(xml,'EC');
			setPriceIndication(xml,'EC','ECLOKAAL');
			setPriceIndication(xml,'HDC9011');
			setPriceIndication(xml,'HDC12');
			setPriceIndication(xml,'M14');
			setPriceIndication(xml,'MHC');
			setPriceIndication(xml,'WHC');
			setPriceIndication(xml,'DDT');
			setPriceIndication(xml,'DDT','DDTLANDELIJK');
			setPriceIndication(xml,'SPI');
			
			if ((DDTMm < 9 && numcolumns == 1) || (DDTMm < 6 && numcolumns == 2)) {
				var minMmsSpans = getElementsByClassName('minMms');
				for (span in minMmsSpans) {
					minMmsSpans[span].innerHTML = numcolumns == 2 ? '6' : '9';
				}
				removeClass(get('tooFewMms'), 'hidden');
			} else {
				addClass(get('tooFewMms'), 'hidden');
			}
				
		}
		refreshcountprijsindicatie = refreshcount;		
	}
}

function updateSpeurderMakenPreview(synchronous) {
	var result = false;
	synchronous = synchronous || true;
	
	return result;
}
	
function setPriceToPay(xml) {
	
	if (tmg(xml).find('status').text() != -1) {
		setError(tmg(xml).find('msg').text());
	}
	
	var bruto = tmg(xml).find('brutoprijs').text();
//	tmg('#breadcrumbproperty_prijsex').html(bruto == 'zie prijsindicatie' ? bruto : 'Prijs (ex BTW): ' + bruto);
	
	var korting = tmg(xml).find('kortingenprijs').text();
//	if (korting == '0,00')
//		tmg('#breadcrumbproperty_korting').addClass('hidden');
//	else
//		tmg('#breadcrumbproperty_korting').removeClass('hidden').html('Uw korting: &euro; ' + korting.replace('-', ''));

	var prijsex = tmg(xml).find('brutoprijsrestantbedrag').text();
//	if (prijsex == 0)
//		tmg('#breadcrumbproperty_restantex').addClass('hidden');
//	else
//		tmg('#breadcrumbproperty_restantex').removeClass('hidden').html('Restant (excl. BTW): &euro; ' + prijsex);
	
	tmg('#breadcrumbproperty_restantex').addClass('hidden');
	tmg('#breadcrumbproperty_korting').addClass('hidden');
	tmg('#breadcrumbproperty_korting').addClass('hidden');
	
}

function updatePreview() {
	if (typeof(uploadLPMateriaal)!="undefined" && uploadLPMateriaal) {
		if (completeImage_location) {
			if (completeImage_location.length == 0) {
				alert("U heeft geen materiaal opgegeven, via 'bladeren' kunt u materiaal toevoegen");
				return false;
			}
		}
		
		// if there is no image do nothing
		if (get('previewimg').src && (get('previewimg').src).length>0  ) {
			stateUpdate(false, true);
			handlePriceIndication();
		}
	} else {
		stateUpdate(false, true);
		handlePriceIndication();
	}
	
	return false;
}

function updatePrijsOnderBetalen() {
	xml = defaultHandleRequest('/servlet/CommandServlet?command=getprice', '');
	var error = xml.getElementsByTagName("error")[0];
	if (error != null) {
		var status = error.getElementsByTagName("status")[0].firstChild.nodeValue;
		var msg = error.getElementsByTagName("msg")[0].firstChild.nodeValue;
		if (status == 20) {
		   /* sessie verlopen: verwijs terug naar voorpagina */
		   var command = '/?errormsg=' + msg;
		   window.location = command;						
		   window.focus();	 
		   return false;				
  	   }
	}
	
	setClass(kortingOnderBetalen, 'hidden');
	setClass(prijsOnderBetalen, 'hidden');
	setClass(prijsOnderBetalenRestant, 'hidden');	
	
	if (xml.getElementsByTagName('status')[0].firstChild.nodeValue != 0) {
		if (xml.getElementsByTagName('brutoprijs')[0].firstChild.nodeValue == 'zie prijsindicatie') {
			tmg('.breadcrumb_prijsex').html('');
		} else {	
			var prijsweergave = '<div class="breadcrumb_prijsex_highlight module small" style="padding:1px !important;border-width: 3px; width: 244px; margin-top: 0px; height: 56px; float: right; margin-bottom: 1px;">';
			prijsweergave += 'Basisprijs: <b>&euro; ' + xml.getElementsByTagName('brutoprijs')[0].firstChild.nodeValue + '</b>';
			
			var korting = xml.getElementsByTagName('kortingenprijs')[0].firstChild.nodeValue;
			if (korting && (korting != '0,00') && (korting != '-0,00') ) {
				if (korting.indexOf('-') == 0) {
					korting = korting.replace('-', '');			
					prijsweergave += '<br/>Uw korting: <b>&euro; ' + korting + '</b>';
				} else {
					prijsweergave += '<br/>Toeslag <b>&euro; ' + korting + '</b>';
				}
			}
			
			var reedsbetaald = xml.getElementsByTagName('reedsbetaald')[0].firstChild.nodeValue;
			
			
			var tebetalen = xml.getElementsByTagName('brutoprijsrestantbedrag')[0].firstChild.nodeValue;
			if (tebetalen != 0) {
				
				if (reedsbetaald && (reedsbetaald != '0,00')) {
					if ( /^-/.test(tebetalen) ) {
						prijsweergave += '<br/> Te ontvangen: <b>&euro; ' + tebetalen + '</b>';
					} else {
						prijsweergave += '<br/> Nog te betalen: <b>&euro; ' + tebetalen + '</b>';
					}
					prijsweergave += ' (voldaan: <b>&euro; ' + reedsbetaald + '</b>)';
				} else {
					if ( /^-/.test(tebetalen) ) {
						prijsweergave += '<br/> Te ontvangen: <b>&euro; ' + tebetalen + '</b>';
					} else {
						prijsweergave += '<br/> Te betalen: <b>&euro; ' + tebetalen + '</b>';
					}
				}
			}
			
			prijsweergave += '<br/><span style="font-size:9px">prijzen zijn exclusief BTW</span></div>';
			tmg('.breadcrumb_prijsex').html('' + prijsweergave);
			$('.breadcrumb_prijsex_highlight').effect('highlight', {}, 2000);
		}		
	} 
}

function controleerOverlappendeClusters() {
	
	// Temp disable tot release do 16-08-2010
	if (get('melding_overlappende_clusters') && (get('melding_overlappende_clusters') !== undefined)) {
		tmg.loadJson('/servlet/CommandServlet?command=getoverlappendeclusters', null, function( json ) {
			
			if (json.error) {
				setError(COMMUNICATION_ERROR);
				return;
			}		
			var msg;		
			if (json.length > 0) {			
				msg = '<strong>Het verspreidingsgebied v.d. volgende kranten overlappen:</strong><ul class="clusterwarning">';
				jQuery.each(json.overlappende_clusters, function( walk, cluster ) {
					//console.log(cluster.cluster_x);
					//console.log(cluster.cluster_y);
					msg += "<li>" + cluster.cluster_x + ' overlapt met ' + cluster.cluster_y + "</li>";			
				});
				msg += "</ul>"
				setHtml(get('melding_overlappende_clusters'), msg);			
			} else {
				setHtml(get('melding_overlappende_clusters'), '');		
			}
		}, 	false, null);
	}
	
	return;
}

	
/*
function toggleBackground(blinkerid) {
//rgb blauw 221 240 255
//	for (j=100; j<=240; j+=4)
//		setTimeout("getElementById('"+blinkerid+"').style.backgroundColor = 'rgb(221, "+j+", "+(j+15)+")'", ((j-100)*3));

// van rood naar wit
	for (j=100; j<=255; j+=4)
		setTimeout("get('"+blinkerid+"').style.backgroundColor = 'rgb(255, "+j+", "+j+")'", ((j-100)*3));

}
*/

/*
function toggleColor(blinkerid) {
	for (j=0; j<=255; j+=4)
		setTimeout("get('"+blinkerid+"').style.color = 'rgb(0, 0, "+j+")'", j*3);
	for (j=255; j>=0; j-=4)
		setTimeout("get('"+blinkerid+"').style.color = 'rgb(0, 0, "+j+")'", (750-(j*3))+750);
}
*/

var Scroller = function() {
   
	this.self = this;
   
	function init() {

		get('buttonleft').onmousedown = function() {
			stopAutoscrollInterval();
			updateProductbarOffset();
			self.from			   = get('productbar').scrollLeft;
			self.to				 = self.from - 219;
			self.start			  = (new Date()).getTime();
			self.einde			  = self.start + 500;
			activeAutoscrollInterval = setInterval(scrollSlow, 20); //fps
		};
		get('buttonright').onmousedown = function() {
			stopAutoscrollInterval();
			updateProductbarOffset();
			self.from			   = get('productbar').scrollLeft;
			self.to				 = self.from + 219;
			self.start			  = (new Date()).getTime();
			self.einde			  = self.start + 500;
			activeAutoscrollInterval = setInterval(scrollSlow, 20); //fps
		};
		get('slider').onmouseover = function(){
			updateProductbarOffset();
			this.oldBackgroundImage = this.style.background;
			this.style.backgroundImage = 'url(\'/img/slider/slider_background_over.gif\')';
			this.onmouseout = function() {
				this.style.backgroundImage = this.oldBackgroundImage;
			}
		};
		get('slider').onmousedown = function() {
			stopAutoscrollInterval();
			updateProductbarOffset();
//			this.style.backgroundImage = 'url(\'/slider/slider_background_down.gif\')';
			mouse.startx			= mouse.x;
			mouse.scrollx		   = parseInt(get('productbar').scrollLeft);
			activeScrollInterval	= setInterval(scrollDiv, 20);
		};
		get('scrollbar').onmousedown = function() {
			stopAutoscrollInterval();
			updateProductbarOffset();
			
			self.from			   = get('productbar').scrollLeft;
			self.slideroffset	   = get('slider').offsetLeft;
			self.start			  = (new Date()).getTime();
			self.einde			  = self.start + 300;
			
			//verschil tussen muis en huidige slider positie
			var moved			   = parseInt(mouse.x - self.productbaroffset - (self.slideroffset - self.productbaroffset) - self.sliderwidth/2);
			
			var factor			  = moved / (self.productbarwidth - (self.sliderwidth));
		   
			self.to				 = self.from + (self.holderwidth - self.productbarwidth) * factor;
			activeAutoscrollInterval = setInterval(scrollSlow, 20); //fps
		};
		
		if (get('holder').offsetWidth <= get('productbar').offsetWidth) {
			addClass(get('scrollbarholder'), 'hidden');
		} else {
			var productbar				= get('productbar');
			self.buttonwidth			= get('buttonleft').offsetWidth;
			self.productbarwidth		= productbar.offsetWidth;
			self.productbarscrollleft	= productbar.scrollLeft;
			self.holderwidth			= get('holder').offsetWidth;

			get('slider').style.width = '218px'; //parseInt(0.50*((self.productbarwidth / self.holderwidth) * self.productbarwidth)) + 'px';
			
			self.sliderwidth		= get('slider').offsetWidth;
			
			// default scroll 2 producten vanaf links
			if (self.productbarscrollleft == 0) {
				var scrollerstartpos;
				if (speurderrubriek == 6) { // wonen
					scrollerstartpos = 10 * 219;
				} else if (speurderrubriek == 12) { // personeel
					scrollerstartpos = 10 * 219;
				} else {
					scrollerstartpos = 2 * 219;
				};
				get('productbar').scrollLeft = scrollerstartpos;
				self.productbarscrollleft = scrollerstartpos;
			}
			updateProductbarOffset();
			updateSlider();

			get('slider').style.visibility = 'visible';
		}
	}
	   
	function scrollDiv() {
		var moved = (mouse.x - mouse.startx);
		var factor = moved / (this.productbarwidth - this.sliderwidth);
		var newleft = (this.holderwidth - this.productbarwidth) * factor;
		var newscrollleft = newleft + mouse.scrollx;
		this.productbarscrollleft = newscrollleft;
		get('productbar').scrollLeft = newscrollleft;
		updateSlider();
	}
	
	function updateSlider() {
		
		var newscrollleft = this.productbarscrollleft;
		var factor = newscrollleft / (this.holderwidth - this.productbarwidth);
		var newleft = this.productbaroffset + (this.productbarwidth - this.sliderwidth) * factor;
		
		if (newleft < this.productbaroffset) newleft = this.productbaroffset;
		else if (newleft > (this.productbaroffset + this.productbarwidth - this.sliderwidth)) newleft = (this.productbaroffset + this.productbarwidth - this.sliderwidth);
		
		get('slider').style.left = newleft + 'px';
	}
   
	function scrollSlow() {
		var currenttime = (new Date()).getTime();
	   
		if (this.einde - currenttime >= 0) {
			var timepassed	= currenttime - this.start;
			var looptime	  = this.einde - this.start;
			var p			 = timepassed / looptime;
			var diff		  = (this.to - this.from) * Math.sin(p*Math.PI/2);
			var newscrollleft = parseInt(diff + this.from);
			this.productbarscrollleft = newscrollleft;
			get('productbar').scrollLeft = newscrollleft;
			updateSlider();
		} else {
			get('productbar').scrollLeft = this.to;
			this.productbarscrollleft = this.to;
			updateSlider(this.to);
			stopAutoscrollInterval();
		}
	}
	
	function updateProductbarOffset() {
		var productbar = get('productbar');
		valueL = 0;
		do {
			valueL += productbar.offsetLeft || 0;
			productbar = productbar.offsetParent;
			if (productbar) {
				if (productbar.tagName == 'BODY') break;
				var p = productbar.style.position;
				if (p == 'relative' || p == 'absolute') break;
			}
		} while (productbar);

		this.productbaroffset   = valueL;

	}
	this.init = init;
};

/* page kies krant specific */
function modalPublisherWindow(publisher, uitgevernaam) {
	var title = ' selecteren';
	
	if (publisher && publisher == 'hdc') {
		get('modalHcWindowHolder').style.display = 'none';
		get('modalHcWindowHolder').style.visibility = 'hidden';
		get('modalRubriekWindowHolder').style.display = 'none';
		get('modalRubriekWindowHolder').style.visibility = 'hidden';
		get('modalHdcWindowHolder').style.display = 'block';
		get('modalHdcWindowHolder').style.visibility = 'visible';
		title = 'titel' + title;	
	} else if (publisher && publisher == 'hc') {
		get('modalHdcWindowHolder').style.display = 'none';
		get('modalHdcWindowHolder').style.visibility = 'hidden';
		get('modalRubriekWindowHolder').style.display = 'none';
		get('modalRubriekWindowHolder').style.visibility = 'hidden';
		get('modalHcWindowHolder').style.display = 'block';
		get('modalHcWindowHolder').style.visibility = 'visible';
		title = 'regio' + title;	
	} else if (publisher && publisher == 'rubriek' && get('modalHcWindowHolder') && get('modalHdcWindowHolder')&&get('modalRubriekWindowHolder')) {
		get('modalHcWindowHolder').style.display = 'none';
		get('modalHcWindowHolder').style.visibility = 'hidden';
		get('modalHdcWindowHolder').style.display = 'none';
		get('modalHdcWindowHolder').style.visibility = 'hidden';
		get('modalRubriekWindowHolder').style.display = 'block';
		get('modalRubriekWindowHolder').style.visibility = 'visible';
		title = 'subrubriek' + title; 
	}
	
	if ( (uitgevernaam != undefined) && (uitgevernaam != null) && (uitgevernaam != '')) {
		title = title + ' voor ' + uitgevernaam;
	}
	
	setHtml(get('modalWindowHeaderTitle'), title);
	showModal();
}

function showModal() {
	var layer = get('transparencyLayer');
	if (layer!=null) {
		setWidthPercent(layer, 100);
		setHeight(layer, getPageHeight());
		display(layer, 'block');
	}
	display(get('modalWindowContainer'), 'block');
	window.location = '#';
}
function modalWindow(title, content) {
	setHtml(get('modalWindowHeaderTitle'), title);
	setHtml(get('modalWindowContent'), content);
	showModal();
}

function modalHdcWindow() {
	modalPublisherWindow('hdc', 'HDC Media');
}
function modalHcWindow() {
	modalPublisherWindow('hc', 'Overige huis-aan-huiskranten');
}

function modalRubriekWindow(uitgever, content) {
	if (content == 'PRELOADER') setHtml(get('modalRubriekWindowHolder'), '<img src="/img/loader_large.gif" style="margin:50px 45%;"  width="30" height="30" />')
	else if (content !== undefined) setHtml(get('modalRubriekWindowHolder'), content);	
	modalPublisherWindow('rubriek', uitgever);
}

function setHcClusterType(type, subscription) {
	
	if (subscription) {
		
		setClass(get('the_midweekMapImage'), 'hidden');
		setClass(get('the_weekendMapImage'), 'hidden');
		
		if (type == 'weekend') {
			setClass(get('the_midweekSubscriptionMapImage'), 'hidden');
			setClass(get('the_weekendSubscriptionMapImage'), '');
		} else {
			setClass(get('the_weekendSubscriptionMapImage'), 'hidden');
			setClass(get('the_midweekSubscriptionMapImage'), '');
		}
	} else {
		
		setClass(get('the_midweekSubscriptionMapImage'), 'hidden');
		setClass(get('the_weekendSubscriptionMapImage'), 'hidden');
		
		if (type == 'weekend') {
			setClass(get('the_midweekMapImage'), 'hidden');
			setClass(get('the_weekendMapImage'), '');
		} else {
			setClass(get('the_weekendMapImage'), 'hidden');
			setClass(get('the_midweekMapImage'), '');
		}
	}
}

function hcClusterUnhighlight(clusterType) {
	setClass(get('hcMapHoverImage_'+clusterType), 'empty_'+clusterType+'Map');
}

function hdcClusterUnhighlight(clusterType) {
	setClass(get('hdcMapHoverImage'), 'empty_Map');
}

function publisherClusterHighlight(publisher, source, clusterType) {
	if (publisher == 'hc') {
		setClass(get(publisher + 'MapHoverImage_'+clusterType), clusters[publisher][source].naam);
	} else if (publisher == 'hdc') {
		setClass(get(publisher + 'MapHoverImage'), clusters[publisher][source].naam);
	}
	var returnString = '<strong>'+clusters[publisher][source]['omschrijving']+'</strong><br />';
	if (publisher == 'hc') {
		for (titel in clusters.hc[source].titels) {
			returnString += getShortWeekdayByWeekday(clusters.hc[source].titels[titel].publicatiedag) 
				+ ': ' + clusters.hc[source].titels[titel].omschrijving 
				+ ' (' + clusters.hc[source].titels[titel].oplage + ')<br />';
		}
		setHtml(get('HcSelectDistributiegegevens'), returnString);
	} else if (publisher == 'hdc') {
		for (titel in clusters.hdc[source].titels) {
			returnString += clusters.hdc[source].titels[titel].omschrijving 
			+ ' (' + clusters.hdc[source].titels[titel].oplage + ')<br />';
		}
		setHtml(get('HdcSelectDistributiegegevens'), returnString);
	}
}
function hcClusterHighlight(source, clusterType) {
	publisherClusterHighlight('hc', source, clusterType);
}
function hdcClusterHighlight(source) {
	publisherClusterHighlight('hdc', source);
}

function hcClusterSelectMap(source, clusterType) {
	if (check('HcSelect_'+source)) {
		var checkbox = get('HcSelect_'+source);
		setCheckbox(checkbox, !checkbox.checked);
	}
	hcClusterSelect(source, clusterType);
}
function hdcClusterSelectMap(source) {
	if (check('HdcSelect_'+source)) {
		var checkbox = get('HdcSelect_'+source);
		setCheckbox(checkbox, !checkbox.checked);
	}
	hdcClusterSelect(source);
}

function publisherSelectSource(publisher, source, clusterType) {
	var checkbox;
	var currentSelectedClusters;
	if (publisher == 'hc') {
		currentSelectedClusters = get('hcMapImageHolder_' + clusterType);
		checkbox = get('HcSelect_' + source);
	} else if (publisher == 'hdc') {
		currentSelectedClusters = get('hdcMapImageHolder');
		checkbox = get('HdcSelect_' + source);
	}
	if (checkbox && checkbox.checked == false) {
		setCheckbox(checkbox, false);
		if(check(publisher + 'ImageMap_'+source)) {
			currentSelectedClusters.removeChild(get(publisher + 'ImageMap_'+source));
		}
		return false;
	} else {
		var div="";
		if (typeof(currentSelectedClusters)!='undefined') {
			div = 
			'<div style="position:absolute; overflow:hidden; width:244px;height:'+currentSelectedClusters.style.height+'px;" id="' + publisher + 'ImageMap_'+source+'">';
			if (publisher == 'hc') {
				div +=	'	<img class="'+clusters[publisher][source].naam+'" src="/img/'+ publisher +'-map/'+ publisher.toUpperCase()+'-'+clusterType+'-selected.png" style="position:absolute;" />';
			} else if (publisher == 'hdc') {
				div += '	<img class="'+clusters[publisher][source].naam+'" src="/img/'+ publisher +'-map/HDC-selected.png" style="position:absolute;" />';
			}	
			div += '</div>';
			setHtml(currentSelectedClusters, div+getHtml(currentSelectedClusters));
		}
		
		setCheckbox(checkbox, true);
	}
}
function hcClusterSelect(source, clusterType) {
	publisherSelectSource('hc',source, clusterType)
}
function hdcClusterSelect(source) {
	publisherSelectSource('hdc',source)
}

function doCompletionFindCluster(formaat) {
	var postString = '';
	var zoekvalue = '';
	if ("HDC" == formaat) {
		zoekvalue = get('postcode_hdc').value;
	} else {
		zoekvalue = get('postcode_hc').value;
	}
	if (zoekvalue && !isNaN(trim(zoekvalue))) {
		postString = 'formaat=' + formaat + '&postcode=' + escape(zoekvalue) + '&rubriekid=' + subrubriek;
	} else {
		postString = 'formaat=' + formaat + '&plaatsnaam=' + escape(zoekvalue) + '&rubriekid=' + subrubriek;
	} 
	
	asyncHandleRequest('/servlet/CommandServlet?command=findclusters', postString, {
		'onSuccess' : function(r, responseXML, text) {
			if (responseXML) {					 
				var adverterencluster = responseXML.getElementsByTagName("adverterencluster")[0];					
				var clusteroptions = '';				
				for (var walk=0; walk < adverterencluster.childNodes.length ; walk++ ) {
					
					var clusterid = 0;
					var cluster = adverterencluster.getElementsByTagName("cluster")[walk];					
					var clusternaam = cluster.getElementsByTagName("clusternaam")[0].firstChild.nodeValue;					
					var clusteromschrijving = cluster.getElementsByTagName("clusteromschrijving")[0].firstChild.nodeValue;					
					var subscription = cluster.getElementsByTagName("subscription")[0].firstChild.nodeValue == "true";
					var subscriptionPrefix = subscription ? 'Subscription' : '';					
					var clustertype = '';
					if (cluster.getElementsByTagName("clustertype") && cluster.getElementsByTagName("clustertype")[0]
					        && cluster.getElementsByTagName("clustertype")[0].firstChild) {						
						clustertype = cluster.getElementsByTagName("clustertype")[0].firstChild.nodeValue;
					}										
					
					if ("HDC" == formaat) {
						for (cluster in clusters.hdc) if (clusters.hdc[cluster].naam == clusternaam) clusterid = cluster;
						var onclick = ' onclick="hdcClusterSelectMap(\''+clusterid + '\');"';
					
						clusteroptions += '<a href="javascript:void(0);"' + onclick +
							' onmouseover="hdcClusterHighlight(\''+clusterid + '\');"' +
							' onmouseout="hdcClusterUnhighlight(\''+clustertype + '\')"' +
							'>- ' + clusteromschrijving + ' (' + clustertype + ')</a>';
					} else {
						for (cluster in clusters.hc) if (clusters.hc[cluster].naam == clusternaam) clusterid = cluster;
						var onclick = ' onclick="optiontogglersEffects[\'HcSelect'+ subscriptionPrefix + ucFirst(clustertype) + 'Uitgaven_toggler\'].show(); '+
							'optiontogglersEffects[\'HcSelect'+ subscriptionPrefix + (clustertype == 'weekend' ? 'Midweek' : 'Weekend') + 'Uitgaven_toggler\'].hide();' +
							'optiontogglersEffects[\'HcSelect'+ (subscription ? '' : 'Subscription') + 'Weekend' + 'Uitgaven_toggler\'].hide();' +
							'optiontogglersEffects[\'HcSelect'+ (subscription ? '' : 'Subscription') + 'Midweek' + 'Uitgaven_toggler\'].hide();' +
							'setHcClusterType(\''+clustertype+'\', '+subscription+'); hcClusterSelectMap(\''+clusterid + '\', \''+clustertype + '\', '+subscription+');"';
					
						clusteroptions += '<a href="javascript:void(0);"' + onclick +
							' onmouseover="hcClusterHighlight(\''+clusterid + '\', \''+clustertype + '\', '+subscription+');"' +
							' onmouseout="hcClusterUnhighlight(\''+clustertype + '\', '+subscription+')"' +
							'>- ' + clusteromschrijving + ' (' + clustertype + ')</a>';
					}				
				}

				if ("HDC" == formaat) {
					setHtml(get('hdcFoundClustersByPostcodeList'), clusteroptions);
				} else {
					setHtml(get('hcFoundClustersByPostcodeList'), clusteroptions);
				}
			}
		},
		'onFailure' : function(r, status, statusText) {
			if (status == 204) {
				if ("HDC" == formaat) {
					setHtml(get('hdcFoundClustersByPostcodeList'), 'Geen clusters gevonden.');
				} else {
					setHtml(get('hcFoundClustersByPostcodeList'), 'Geen clusters gevonden.');
				}
			} else {
				alert('Er is een fout opgetreden in de communicatie met de server, probeer het nogmaals');
			}
		},
		timeoutMilliSecs : 2000,			
		'onFinish' : function() {
		}
	});

	return true;
}

function hideHcModal() {
	hideModal();
	setHtml(get('HcSelectDistributiegegevens'), 'selecteer eerst een distributiegebied');
	deactivateCalendar(1024);
	//document.modalWindowForm.postcode.value = '';
}

function hideHdcModal() {
	hideModal();
	setHtml(get('HdcSelectDistributiegegevens'), 'selecteer eerst een distributiegebied');
	deactivateCalendar(1024);
	//document.modalWindowForm.postcode.value = '';
}

function setHcClusters(newClusterArray) {
	
	for (var i = 0; i < newClusterArray.length; i++) {
		if (!inArray(hcClusterArray, newClusterArray[i])) addHcCluster(newClusterArray[i]);
	}

	hcClusterArray = newClusterArray;
}

function setHdcClusters(newClusterArray) {
	
	for (var i = 0; i < newClusterArray.length; i++) {
		if (!inArray(hdcClusterArray, newClusterArray[i])) addHdcCluster(newClusterArray[i]);
	}
	
	hdcClusterArray = newClusterArray;
}

function generateSchema(schemaId, schemaType, options) {
	//allowed schema's = RDP, DDT, SPI, EC, HC, HDC en WATERSPORT
	
	var result;
	
	if (!options) options = {};
	if (!options.days) {
		options.days = {};
		
		switch (schemaType) {
			case 'HDC' :
				// the days should allready been set in the options
				break;
			case 'HC' :
				// niet van toepassing, negeer
				break;
			case 'SPI' :
				options.days = calendars[2].days;
				break;
			case 'DDT' :
				options.days = calendars[1].days;
				break;
			default : 
				return false;
		}
	}	

	result = '<div id="schema' + schemaId + '_slider" class="slider herhalen">' + 
	'	<div class="module small">' +
	'		<h2 class="blue">' +
	'			<span class="right bold red" id="NoDaysSelected_' + schemaId + '"></span>' +
	'			1. herhalen' +
	'		</h2>' +
	'		<table border="0" cellspacing="2" cellpadding="0">' +
	'			<tr>' +
	'				<td>' +
	'					<input type="radio" name="doorplaatsen' + schemaId + '" value="multipleDaysPerWeek" id="OmDeWeken_' + schemaId + '" checked="checked" />' +
	'					<label for="OmDeWeken_' + schemaId + '">elke</label>' +
	'				</td>' +
	'				<td>' +
	'					<select id="OmDeWekenValue_' + schemaId + '" onchange="get(\'OmDeWeken_' + schemaId + '\').checked = true;" class="small">' +
	'						<option value="1">week</option>' +
	'						<option value="2">2 weken</option>' +
	'						<option value="3">3 weken </option>' +
	'						<option value="4">4 weken </option>' +
	'					</select>' +
	'				</td>' +
	'			</tr>';
if (schemaType == 'HC') {
	result += '			<input name="OmDeWekenDag_' + schemaId + '" checked="checked" value="1" type="checkbox" class="hidden" />';
} else if (schemaType == 'RDP') {
	result += '			<input name="OmDeWekenDag_' + schemaId + '" checked="checked" value="5" type="checkbox" class="hidden" />' +
	'					<input name="OmDeWekenDag_' + schemaId + '" checked="checked" value="6" type="checkbox" class="hidden" />';
}
if (schemaType == 'SPI' || schemaType == 'DDT' || schemaType == 'HDC') {
	result += '			<tr>' +
	'				<td valign="top" align="right">' +
	'					<img src="/img/hoekje_wit8.gif" alt="hoekje" />' +
	'				</td>' +
	'				<td>' +
	'					<table cellspacing="3" style="margin-top:0px;">' +
	'						<tr align="center">' +
	'							<td>ma</td>' +
	'							<td>di</td>' +
	'							<td>wo</td>' +
	'							<td>do</td>' +
	'							<td>vr</td>';
	if (schemaType == 'HDC') {
	result += '					<td>za</td>';
	} else if (schemaType == 'DDT') {
	result += '					<td>za</td>' +
	'							<td>zo</td>';
	}
	result += '						</tr>' +
	'						<tr>' +
	'							<td><input name="OmDeWekenDag_' + schemaId + '" value="1" type="checkbox" onchange="get(\'OmDeWeken_' + schemaId + '\').checked = true;" class="slimCheckbox" ' + ((inArray(options.days, 1)) ? '' : 'disabled="disabled"') + ' /></td>' +
	'							<td><input name="OmDeWekenDag_' + schemaId + '" value="2" type="checkbox" onchange="get(\'OmDeWeken_' + schemaId + '\').checked = true;" class="slimCheckbox" ' + ((inArray(options.days, 2)) ? '' : 'disabled="disabled"') + ' /></td>' +
	'							<td><input name="OmDeWekenDag_' + schemaId + '" value="3" type="checkbox" onchange="get(\'OmDeWeken_' + schemaId + '\').checked = true;" class="slimCheckbox" ' + ((inArray(options.days, 3)) ? '' : 'disabled="disabled"') + ' /></td>' +
	'							<td><input name="OmDeWekenDag_' + schemaId + '" value="4" type="checkbox" onchange="get(\'OmDeWeken_' + schemaId + '\').checked = true;" class="slimCheckbox" ' + ((inArray(options.days, 4)) ? '' : 'disabled="disabled"') + ' /></td>' +
	'							<td><input name="OmDeWekenDag_' + schemaId + '" value="5" type="checkbox" onchange="get(\'OmDeWeken_' + schemaId + '\').checked = true;" class="slimCheckbox" ' + ((inArray(options.days, 5)) ? '' : 'disabled="disabled"') + ' /></td>';
	if (schemaType == 'HDC') {
	result += '							<td><input name="OmDeWekenDag_' + schemaId + '" value="6" type="checkbox" onchange="get(\'OmDeWeken_' + schemaId + '\').checked = true;" class="slimCheckbox" ' + ((inArray(options.days, 6)) ? '' : 'disabled="disabled"') + ' /></td>';
	} else if (schemaType == 'DDT') {
	result += '							<td><input name="OmDeWekenDag_' + schemaId + '" value="6" type="checkbox" onchange="get(\'OmDeWeken_' + schemaId + '\').checked = true;" class="slimCheckbox" ' + ((inArray(options.days, 6)) ? '' : 'disabled="disabled"') + ' /></td>' +
	'							<td><input name="OmDeWekenDag_' + schemaId + '" value="7" type="checkbox" onchange="get(\'OmDeWeken_' + schemaId + '\').checked = true;" class="slimCheckbox" ' + ((inArray(options.days, 7)) ? '' : 'disabled="disabled"') + ' /></td>';
	}
	result += '						</tr>' +
	'					</table>' +
	'				</td>' +
	'			</tr>';
} else if (schemaType == 'EC') {
	result += '			<input name="OmDeWekenDag_' + schemaId + '" value="3" type="checkbox" checked="checked" class="hidden" />';
} else if (schemaType == 'WATERSPORT') {
	result += '			<input name="OmDeWekenDag_' + schemaId + '" value="6" type="checkbox" checked="checked" class="hidden" />';
}
	result += '			<tr>' +
	'				<td>' +
	'					<input type="radio" name="doorplaatsen' + schemaId + '" value="singleDayPerWeek" id="StoptNaDatum_' + schemaId + '" onclick="resetRadio(document.activeForm.OmDeWekenDag_' + schemaId + '); get(\'StoptNaDatum_' + schemaId + '\').checked = true;" />' +
	'					<label for="StoptNaDatum_'+schemaId+'">elke</label>' +
	'				</td>' +
	'				<td>' +
	'					<select id="OmHoeveelsteWeekValue_' + schemaId + '" onchange="resetRadio(document.activeForm.OmDeWekenDag_' + schemaId + '); get(\'StoptNaDatum_' + schemaId + '\').checked = true;" class="small">' +
	'						<option value="1">1ste</option>' +
	'						<option value="2">2e</option>' +
	'						<option value="3">3e</option>' +
	'						<option value="4">4e</option>' +
	'					</select>';
if (schemaType == 'SPI' || schemaType == 'DDT' || schemaType == 'HDC') {
	result += '					<select id="OmWeekdagValue_' + schemaId + '" onchange="resetRadio(document.activeForm.OmDeWekenDag_' + schemaId + '); get(\'StoptNaDatum_' + schemaId + '\').checked = true;" class="small">' +
	'						<option value="1">maandag</option>' +
	'						<option value="2">dinsdag</option>' +
	'						<option value="3">woensdag</option>' +
	'						<option value="4">donderdag</option>' +
	'						<option value="5">vrijdag</option>';
	if (schemaType == 'HDC') {
	result += '						<option value="6">zaterdag</option>';
	} else if (schemaType == 'DDT') {
	result += '						<option value="6">zaterdag</option>' +
	'						<option value="7">zondag</option>';
	}
	result += '					</select>' +
	'					van de maand';
} else if (schemaType == 'RDP' || schemaType == 'HC') {
	result += '					<select id="OmWeekdagValue_' + schemaId + '" class="hidden">' +
	'						<option value="5" selected="selected">5</option>' +
	'					</select>' +
	'					week van de maand';
} else if (schemaType == 'EC') {
	'					woensdag van de maand' +
	'					<select id="OmWeekdagValue_' + schemaId + '" style="display:none;">' +
	'						<option value="3" selected="selected">woensdag</option>' +
	'					</select>';
} else if (schemaType == 'WATERSPORT') {
	result += '					zaterdag van de maand' +
	'					<select id="OmWeekdagValue_' + schemaId + '" style="display:none;">' +
	'						<option value="6" selected="selected">zaterdag</option>' +
	'					</select>';
}
	result += '				</td>' +
	'			</tr>' +
	'		</table>' +
	'		<hr style="margin:10px 20px 10px 20px;" />' +
	'		<h2 class="blue">2. einddatum</h2>' +
	'		<table border="0" cellspacing="2" cellpadding="0">' +
	'			<tr>' +
	'				<td colspan="2">' +
	'					<input type="radio" name="doorplaatsen' + schemaId + 'Einde" value="stoptEindeJaar" id="StoptEindeJaar_' + schemaId + '" checked="checked" />' +
	'					<label for="StoptEindeJaar_' + schemaId + '">tot einde van dit jaar</label>' +
	'				</td>' +
	'			</tr>' +
	'			<tr>' +
	'				<td>' +
	'					<input type="radio" name="doorplaatsen' + schemaId + 'Einde" value="stoptEindeDatum" id="StoptEindeDatum_' + schemaId + '" />' +
	'					<label for="StoptEindeDatum_' + schemaId + '">tot en met</label>' +
	'				</td>' +
	'				<td>' +
	'					<select id="StoptEindeDatumDag_' + schemaId + '" onchange="get(\'StoptEindeDatum_' + schemaId + '\').checked = true;" class="small">' +
	'						<option value="1">1</option>' +
	'						<option value="2">2</option>' +
	'						<option value="3">3</option>' +
	'						<option value="4">4</option>' +
	'						<option value="5">5</option>' +
	'						<option value="6">6</option>' +
	'						<option value="7">7</option>' +
	'						<option value="8">8</option>' +
	'						<option value="9">9</option>' +
	'						<option value="10">10</option>' +
	'						<option value="11">11</option>' +
	'						<option value="12">12</option>' +
	'						<option value="13">13</option>' +
	'						<option value="14">14</option>' +
	'						<option value="15">15</option>' +
	'						<option value="16">16</option>' +
	'						<option value="17">17</option>' +
	'						<option value="18">18</option>' +
	'						<option value="19">19</option>' +
	'						<option value="20">20</option>' +
	'						<option value="21">21</option>' +
	'						<option value="22">22</option>' +
	'						<option value="23">23</option>' +
	'						<option value="24">24</option>' +
	'						<option value="25">25</option>' +
	'						<option value="26">26</option>' +
	'						<option value="27">27</option>' +
	'						<option value="28">28</option>' +
	'						<option value="29">29</option>' +
	'						<option value="30">30</option>' +
	'						<option value="31">31</option>' +
	'					</select>' +
	'					<select id="StoptEindeDatumMaand_' + schemaId + '" onchange="get(\'StoptEindeDatum_' + schemaId + '\').checked = true;" class="small">' +
	'						<option value="1">januari</option>' +
	'						<option value="2">februari</option>' +
	'						<option value="3">maart</option>' +
	'						<option value="4">april</option>' +
	'						<option value="5">mei</option>' +
	'						<option value="6">juni</option>' +
	'						<option value="7">juli</option>' +
	'						<option value="8">augustus</option>' +
	'						<option value="9">september</option>' +
	'						<option value="10">oktober</option>' +
	'						<option value="11">november</option>' +
	'						<option value="12">december</option>' +
	'					</select>' +
	'					<select id="StoptEindeDatumJaar_' + schemaId + '" onchange="get(\'StoptEindeDatum_' + schemaId + '\').checked = true;" class="small" disabled="disabled">';
			
	
		result += '	<option value="2010">2010</option>'; 

						
	
	result += '					</select>' +
	'				</td>' +
	'			</tr>' +
	'			<tr>' +
	'				<td>' +
	'					<input type="radio" name="doorplaatsen' + schemaId + 'Einde" value="stoptEindeNaKeer" id="StoptEindeNaKeer_' + schemaId + '" />' +
	'					<label for="StoptEindeNaKeer_' + schemaId + '">stopt over</label>' +
	'				</td>' +
	'				<td>' +
	'					<input type="text" id="EindeNaKeerValue_' + schemaId + '" onmouseup="get(\'StoptEindeNaKeer_' + schemaId + '\').checked = true;" onkeydown="get(\'StoptEindeNaKeer_' + schemaId + '\').checked = true;" value="10" style="width:20px;" class="small" />' +
	'					weken' +
	'				</td>' +
	'			</tr>' +
	'		</table>' +
	'		<input type="button" value="toepassen" onclick="if(saveScheme(\'' + schemaId + '\')) { togglersEffects[\'schema' + schemaId + '_toggler\'].sweetHide();  }" class="button right" />' +
	'		<input type="button" value="annuleer" onclick="togglersEffects[\'schema' + schemaId + '_toggler\'].sweetHide();" class="button small" />' +
	'	</div>' +
	'</div>';
	
	return result;
}

/**
 * this function will make a textarea grow based on the input length
 * @param {string} visiblename is the form element which is visible for the client
 */
function autogrow(id, maxsize) {
	
	if (!isLocked(id)) {
		lock(id);
		get(id).maxsize = maxsize - 1;
		tmg('#'+id).on('keydown', function(){
			if (this.maxsize < this.value.length) this.value = this.value.substring(0, this.maxsize);
			checkheight(this.id);
		});
		setTimeout('checkheight(\''+id+'\')', 400);
		setTimeout('unlock(\''+id+'\')', 400);
	}
}


/**
 * this function will get the height of the input in a textarea, this is mainly used for the autogrow
 * option on textarea's
 * @param {string} visiblename is the form element which is visible for the client
 */
function checkheight(id) {
	var textarea = tmg('#'+id);
	textarea.css('overflow', 'hidden');
	
	if (!check('autogrowDiv')) {
		var autogrowDiv					= document.createElement('div');
		autogrowDiv.id					= 'autogrowDiv';
		autogrowDiv.style.fontSize		= textarea.css('fontSize');
		autogrowDiv.style.fontFamily	= textarea.css('fontFamily');
		autogrowDiv.style.width			= textarea.css('width');
		autogrowDiv.style.padding		= textarea.css('padding');
		autogrowDiv.style.lineHeight	= textarea.css('lineHeight');
		autogrowDiv.style.overflow		= 'hidden';
		autogrowDiv.style.visibility	= 'hidden';
		autogrowDiv.style.position		= 'absolute';
		autogrowDiv.style.top			= 0;
		autogrowDiv.style.left			= -9999;
		
		// append the autogrow div to the body
		document.body.appendChild(autogrowDiv);
	}
	
	var dummy = get('autogrowDiv');
	
	// set the content of the textarea in the div with an extra new line
	dummy.innerHTML = textarea.value().replace(/\n/g, '<br />new') + '<br />new';
	
	// now set the height of the textarea
	if (textarea.css('height').replace('px', '') < dummy.offsetHeight + textarea.css('lineHeight').replace('px', '') * 1 || (dummy.offsetHeight < textarea.css('height').replace('px', '')))
		textarea.css('height', ((dummy.offsetHeight < 45) ? 45 : dummy.offsetHeight) + 'px');

}

function addPublisherCluster(publisher, clusterId, invisible) {
	
	if (!calendars[clusterId] || !calendars[clusterId].build) {
		var currentList		= get(publisher + 'SelectClusterlist');
		var listItem		= document.createElement("li");
		var clusterName;
		var clusterType;
		var publicatiedag;
		var clusterTypeSuffix = '';
		var uitgevernaam = '';
		if (publisher == 'Hc') {
			clusterName 	= clusters.hc[clusterId].omschrijving;
			clusterType 	= clusters.hc[clusterId].type;
			//Only one day for HC
			publicatiedag 	= [1];
			clusterTypeSuffix	= ' (' + clusterType + ')';
			uitgevernaam = 'Overige huis-aan-huiskranten';
		} else if (publisher == 'Hdc') {
			clusterName		= clusters.hdc[clusterId].omschrijving;
			clusterType		= clusters.hdc[clusterId].type;
			publicatiedag	= clusters.hdc[clusterId].publicatiedagen;
			uitgevernaam = 'HDC Media';
		}
		listItem.innerHTML = '';

		if (typeof subdomain !='undefined' && subdomain!='hc') {
			listItem.innerHTML = 
			'<input id="c_'+clusterId+'_toggler" type="checkbox" checked="checked" onclick="activateCalendar(\''+clusterId+'\', this.checked); showSelectCalendar(\''+clusterId+'\', this.checked); recalc();" />' +
			'<label for="c_'+clusterId+'_toggler">'+clusterName + clusterTypeSuffix + ' </label>' ;
		}
		listItem.innerHTML +=
			'<div id="c_'+clusterId+'_slider" class="module" style="display:none;">' +
			'	<div class="calendar clearfix">' +
			'		<div id="c_'+clusterId+'"></div>' +
	'				<div class="calendarLinks">' +
	/*'					<a href="javascript:modalRubriekWindow(\'' + uitgevernaam + '\');">wijzig&nbsp;rubriek</a><br/>' +*/
	'					<a href="javascript:void(0);" onclick="if (confirm(\'Weet u zeker dat u deze kalender wil leegmaken, uw geselecteerde plaatsingsdata worden hierbij gewist?\')) {resetCalendar('+clusterId+'); recalc();}" title="wis alle geselecteerde plaatsingsdata">wis&nbsp;data</a>' +
	'					<div id="schema' + clusterId + '_toggler"><br/><a title="selecteer meedere plaatsingsdata op basis van selectiecriteria" href="javascript:void(0);">herhaal</a></div>' + 
	'				</div>' +
			'	</div>' +
			'	<div>' + generateSchema(clusterId, publisher.toUpperCase(), {days:publicatiedag})+'</div>' +
			'</div>';
		currentList.insertBefore(listItem, currentList.childNodes[currentList.childNodes.length-((IE)?1:2)]);
		togglersById('schema'+clusterId+'_toggler');


		addCalendar(clusterId, {name:clusterName,publisher:publisher.toUpperCase(),days:publicatiedag,type:clusterType}); 
		makeCalendar(clusterId);
		if (publisher == 'hc') {
			hdcClusterSelectMap(clusterId);
		} else if (publisher == 'hdc') {
			hcClusterSelectMap(clusterId);
		}  
	}
	
	if ( ! invisible ) {
		calendars[ clusterId ].active = true;
		setCheckbox(get('c_'+clusterId+'_toggler'), true);
		display(get('c_'+clusterId+'_slider'), true);
	}
	
	// make sure Publisher Select is also visible and checked
	display(get(publisher + 'Select_slider'), true);
	setCheckbox(get(publisher + 'Select_toggler'), true);

}

function addHcCluster(clusterId) {
	addPublisherCluster('Hc', clusterId);
}
function addHdcCluster(clusterId) {
	addPublisherCluster('Hdc', clusterId);
}

function checkHcModal() {
	
	var hcClusters = [];
	var input = document.modalWindowForm.HcSelectRegios;
	var counter = 0;
	for (i=0; i<input.length; i++) {
		if (input[i].checked == true) {
			hcClusters[hcClusters.length] = input[i].value;
			counter++;
		}
	}
	
	if (counter == 0) {
		setHtml(get('HcSelectModalWindowErrorDiv'), 'selecteer minimaal één distributiegebied');
		return false;
	}
	
	setHcClusters(hcClusters);
	return true;
}

function checkHdcModal() {
	
	var hdcClusters = [];
	var input = document.modalWindowForm.HdcSelectRegios;
	var counter = 0;
	for (i=0; i<input.length; i++) {
		if (input[i].checked == true) {
			hdcClusters[hdcClusters.length] = input[i].value;
			counter++;
		}
	}
	
	if (counter == 0) {
		setHtml(get('HdcSelectModalWindowErrorDiv'), 'selecteer minimaal één distributiegebied');
		return false;
	}
	
	setHdcClusters(hdcClusters);
	return true;
}

var hcClustersSet = false;
var hdcClustersSet = false;

/* end kies krant specific */

/* Preview Functions */
var refreshcount 				= Math.ceil((Math.random())*1000);
var refreshcountbasketinfo		= 0;
var refreshcountprijsindicatie 	= 0;
var refreshcountsetlayout 		= 0;

function replacePreviewImage(imageObject, newSourceString) {
	newSourceString+="&refresh="+refreshcount;
	if (imageObject.src.indexOf(newSourceString)==-1) {
		removeClass(imageObject,'hidden');
		imageObject.src=newSourceString;
		imageObject.parentNode.style.height = imageObject.height + 'px';
		imageObject.parentNode.style.visibility = '';
	} else {
		debug("Discarding unnecessary image requests: The url " + newSourceString + " does not differ, the image " +  imageObject.id + " is not refreshed.", "IE Performance increase");
	}
}

function initTabs(tabgroup, options) {
	
	if (!options) options = {};
	if (options.horizontal == undefined) options.horizontal = true;
	if (options.mouseover == undefined) options.mouseover = false;
	if (options.transition == undefined) options.transition = 'normal';
	
	var hash = location.hash;
	var nodes = get(tabgroup).getElementsByTagName('a'), walk = nodes.length;
	var activenode;
	
	while (walk--) {
		nodes[walk].removeAttribute('href');
		
		nodes[walk].onclick = function() {
			selectTab(tabgroup, this.id.replace('link', ''), {transition:options.transition, updatehash:true});
		}
		nodes[walk].onmouseover = function() {
			if (options.mouseover) {
				selectTab(tabgroup, this.id.replace('link', ''), {transition:options.transition});
			}
			addClass(this.parentNode, 'hover');
		}
		nodes[walk].onmouseout = function() {
			removeClass(this.parentNode, 'hover');
		}
		if ('#'+nodes[walk].id.replace('link', '') == hash) {
			activenode = walk;
		}
		if (options.horizontal == false) {
			addClass(get(nodes[walk].id).parentNode, 'vertical');
			addClass(get(nodes[walk].id.replace('link', '-anchorfix')), 'vertical');
		}
	}
	
	selectTab(tabgroup, nodes[activenode ? activenode : 0].id.replace('link', ''), {transition:'normal'});
}

function selectTab(tabgroup, tabid, options) {
	
	if (!options) options = {};
	if (options.transition == undefined) options.transition = 'normal';
	if (options.updatehash == undefined) options.updatehash = false; 
	
	if (options.transition == 'slow') {
		
		// activate the new tab
		$('#' + tabid + 'link').parent().addClass('active').siblings().removeClass('active');
		
		// fade out the old tab div
		$('#' + tabid + '-anchorfix').addClass('active').siblings('.active').fadeOut(200, function() {
			// fade in the new tab
			$(this).siblings('.active').fadeIn(300);
		}).removeClass('active');
	} else {
		$('#' + tabid + '-anchorfix').show().addClass('active').siblings('div.tabdiv').hide().removeClass('active');
		$('#' + tabid + 'link').parent().addClass('active').siblings().removeClass('active');
	}
	if (options.updatehash) {
		
		var currentlocation = window.location.href;
		
		// replace the current hash
		if (currentlocation.indexOf('#') != -1) currentlocation = currentlocation.substring(0, currentlocation.indexOf('#'));
		
		window.location.replace(currentlocation + '#' + tabid);
	}
	
	if (typeof(fixCorners) != "undefined") {
		fixCorners(tabid);
	}
	
	trackPage(document.location.pathname+ "/"+tabid+"/");
}

var animationCarousel = false;

function clickCarousel(link) {
	
	var scrollamount = 470;
	var thescroller = $(link).siblings('div.carousel');
	
	var classes = $(link).attr('class').split(' ');
	
	for (thisclass in classes) {
		thisclass = classes[thisclass];
		if (thisclass.substring(0, 4) == 'link' && animationCarousel == false && !$(link).hasClass('active')) {
			animationCarousel = true;
			var imageHeight = $($('div img', thescroller).get(thisclass.substring(4, 5)-1)).height();
			thescroller.animate({scrollLeft: (thisclass.substring(4, 5)-1) * scrollamount + 'px', height:imageHeight+'px'}, 400, 'easeOutCubic', function(){
				animationCarousel = false;
			});
			$(link).addClass('active').siblings().removeClass('active');
			return;
		}
	}
}

/*
will make :
	<div class="carousel">
		<div class="holder">
			<div><img src="img1.jpg" />&nbsp;</div>
			<div><img src="img2.jpg" />&nbsp;</div>
		</div>
	</div>
from :
	<div class="carousel">
		<img src="img1.jpg" />
		<img src="img2.jpg" />
	</div>
*/
function initCarousel(carousel) {
	
	var scrollamount = 470;
	
	var currenthtml = $('.carousel', carousel).html();
	$('.carousel', carousel).html('<div class="holder">' + currenthtml + '</div>');
	$('.carousel img', carousel).wrap('<div></div>').after('&nbsp;');
	var number = $('a', carousel).length;
	$('.holder', carousel).css({width: (number == 0 ? 1 : number) * scrollamount});

	$('a', carousel).click(function() {
		clickCarousel($(this));
		
	});
}
function initCarousels(className) {
	$('.' + className).each(function(){
		initCarousel($(this));
	});
}


/* MARCO POPUP WINDOW */
function placeIt(id) {

	var x = 320, y = 200, theLeft, theTop;
	var el = get(id);
	
	if (document.documentElement) {
		theLeft = document.documentElement.scrollLeft;
		theTop = document.documentElement.scrollTop;
	} else if (document.body) {
		theLeft = document.body.scrollLeft;
		theTop = document.body.scrollTop;
	}

	el.style.left = theLeft + x + 'px' ;
	el.style.top = theTop + y + 'px' ;
}

function initModalWindowWithAjaxContent(){
	
	if (typeof $ == 'undefined') return false;
	
	$('a.modalpopup').click(function(){
		var temp = jQuery.ajax({
			url: $(this).attr('href'),
			async : false
		}).responseText;
		$('#modalWindowContent').html(
			temp
		).find('link').remove();
		showModal();
		return false;
	});
}

// this function determines whether the event is the equivalent of the microsoft
// mouseleave or mouseenter events.
function isMouseLeaveOrEnter(e, handler) {
	if (e.type != 'mouseout' && e.type != 'mouseover') return false;
	
	var reltg = e.relatedTarget ? e.relatedTarget : 
		e.type == 'mouseout' ? e.toElement : e.fromElement;
	
	while (reltg && reltg != handler)
		reltg = reltg.parentNode;
	
	return (reltg != handler);
}

function toggleProductSelect(how) {
	each(collection(get('selecteerproducttype').childNodes), function(el){
		if (el.tagName == 'DIV') {
			if (how == undefined) toggle(el);
			else display(el, how);
		}
	});
}
function setProductType(type){
	each(collection(get('selecteerproducttype').childNodes), function(el){
		if (el.tagName == 'h1') {
			el.innerHTML = '<a onclick="toggleProductSelect();">Selecteer een ander producttype</a>';
		}
	});
	toggleProductSelect(false);
}	


function toggleCheckbox(checkbox) {
	if (checkbox && typeof(checkbox)!="undefined") {
		if (checkbox.checked==true) {
			checkbox.checked=false;
		} else {
			checkbox.checked=true;
		}
	}
}

function setCookie(c_name, value, expiredays) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie = c_name+ "=" + escape(value) + ((expiredays==null) ? "" : "; expires="+exdate.toGMTString()) + '; path=/';
}

function getCookie(c_name) {
	if (document.cookie.length > 0) {
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1) {
			c_start = c_start + c_name.length + 1; 
			c_end = document.cookie.indexOf(";", c_start);
			if (c_end == -1)
				c_end = document.cookie.length;
			return unescape(document.cookie.substring(c_start, c_end));
		}
	}
	return "";
}

