window.onload = onbodyload;
window.onresize = onbodyresize;
window.onscroll = onScrollPage;
var h = 0;
var w = 0;
var xScroll, yScroll;
var limitsalesbystock = 0;
var showstockstatus = 0;
var mClicked = 0; //the last id that was clicked, to see if the user navigates history or not

var Root = 'http://www.kookwinkel.nl/';
var metabody_text;

osp_page = 1;
function onScrollPage(){
	//load next 30 items when necessary
	osp_el = document.getElementById('nextitems');
	osp_scrolled = document.documentElement.scrollTop || document.body.scrollTop;
	if (window.loaded && (findPosY(osp_el) - 500) < (osp_scrolled + h)){
		window.loaded = false;
		osp_el.innerHTML = '<img src="/img/loading.gif" alt="Laden volgende 30 artikelen" style="margin:12px;"/>';
		ajaxRun('/scripts/nextitems.asp',nextItemsReturn,'POST','type='+osp_el.title+'&id='+eval(osp_el.title+'id')+'&page='+(osp_page+1),false,true);
	}
}
function nextItemsReturn(xmlObj){
	if (xmlObj.readyState == 4){
		txt = xmlObj.responseText;
		nir_el = document.getElementById('nextitems');
		if (txt.indexOf('<content>') == -1){
			nir_el.innerHTML = txt; //this is most likely an errorpage
		}else{
			if (eval(txt.rat('nomore'))){
				removeDiv(nir_el);
			}else{
				nir_div = document.createElement('DIV');
				nir_div.innerHTML = txt.rat('content');
				document.getElementById('content').insertBefore(nir_div,nir_el.previousSibling)
				osp_page++;
				nir_el.innerHTML = '';
			}
			window.loaded = true;
		}
	}
}

//test browsing system
setInterval('checklocation();',100);
function checklocation(){
	if (window.loaded){
		checklocationid = document.location.href.substr(document.location.href.indexOf('#') + 1);
//		if (document.location.href.indexOf('#') == -1){
//		}
		if (checklocationid == document.location.href){ //get id from the current href
			checklocationid = parseInt(checklocationid.substr(checklocationid.indexOf('/webshop/') + 9));
		}
		if (parseInt(checklocationid) == checklocationid && !admin){
			if (checklocationid != id){
				document.getElementById('content').innerHTML = '<img src="/img/loading.gif" alt="Laden..."/>';
				id = checklocationid;
				ajaxRun('/scripts/pageloader.asp',pageloaderReturn,'POST','id='+id,false,true);
			}
		}else{
			if (checklocationid == 'winkelwagen' && id != 'winkelwagen'){
				loadScript('cart6-js');
				id = 'winkelwagen';
				ajaxRun('/scripts/shoppingcart.asp',showcartReturn,'POST','output=js',false,true);
			}else if (checklocationid == 'zoeken' && id != 'zoeken'){
				id = 'zoeken';
				ajaxRun('/scripts/searchloader.asp',searchloaderReturn,'POST','q='+escape(document.getElementById('searchform').elements['q'].value),false,true);
			}else if (checklocationid == 'more'){
				//ignore
			}
		}
	}
}
//end test
function enlargepic(epUrl){
	epWindow = window.open('/enlargepic.asp?'+escape(epUrl),"mywindow","width=10,height=10");
	epWindow.focus();
}

function epost(epostWhich){
	document.location.href='mailto:'+epostWhich.innerHTML; 
}

function onbodyload(){
	Root = document.location.href;
	Root = Root.substring(0,Root.indexOf('.nl')+4);
	if (!admin){
		if (document.getElementById('body')){
			document.getElementById('body').onselectstart = function () { return false; } // ie
			//document.getElementById('body').onmousedown = function () { return false; } // mozilla <-blocks forms, see css!
		}
	}

	if (window.innerHeight && window.scrollMaxY){	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	}else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	}else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	if (self.innerHeight){	// all except Explorer
		w = self.innerWidth;
		h = self.innerHeight;
	}else if (document.documentElement && document.documentElement.clientHeight){ // Explorer 6 Strict Mode
		w = document.documentElement.clientWidth;
		h = document.documentElement.clientHeight;
	}else if (document.body){ // other Explorers
		w = document.body.clientWidth;
		h = document.body.clientHeight;
	}
	//do other stuff
	runPage();
	//load topmenu
	tm = new tm();
	tm.create('Pannen,Messen,Keukengerei,Elektrisch,Fornuizen,Espresso,Tafelen');
	//activate admin stuff
	if (admin){
		try{
			adminStartup();
		}catch(e){
			alert('Couldn\'t start admin because of ' + e);
		}
		//checkchanges('init');
	}
	//set search
	var qField = document.getElementById('q');   
	qField.setAttribute('autocomplete', 'off');  
}
function runPage(){
	//social sharing
//	if (document.getElementById('socialsharing')){
//		el = document.getElementById('socialsharing');
//		if (id == 0){
//			page_href = document.location.href;
//		}else{
//			page_href = 'http://kookwinkel.nl/'+id;
//		}
//		el.innerHTML = '';
//		page_href_short = page_href;
//		page_id = parseInt(page_href.substr(page_href.indexOf('/webshop/') + 9));
//		if (page_id.toString() != 'NaN'){
//			page_href_short = 'www.kookwinkel.nl/' + page_id;
//		}

//		el.appendChild(document.createTextNode('Deel deze pagina: '));
//		el.appendChild(socialLink('Facebook','http://www.facebook.com/sharer.php?u='+page_href+'&t='+document.title,'/img/design/sm/icon_facebook.png'));
//		el.appendChild(socialLink('Twitter','http://twitter.com/home?status=Bekijk eens deze pagina op kookwinkel.nl! '+page_href,'/img/design/sm/icon_twitter.png'));
//		el.appendChild(socialLink('Hyves','http://www.hyves.nl/profilemanage/add/tips/?name='+document.title+' - Bekijk dit product op kookwinkel.nl&text=De online kookwinkel met het grootste assortiment! Bekijk dit product op '+page_href+'&type=12','/img/design/sm/icon_hyves.gif'));
//		el.appendChild(socialLink('Delicious','http://delicious.com/save?v=5&noui&jump=close&url='+page_href+'&title='+document.title+' op http://www.kookwinkel.nl','/img/design/sm/icon_delicious.gif'));
		//el.appendChild(socialLink('Email','/page_email.asp?id='+id,'/img/design/sm/icon_email.png'));
//	}
	articlepropertiesimagechosen();
	try{
		MojoZoom.init();
	}catch(e){
	}
	window.loaded = true;
	//go fetch stock information where needed
	if (limitsalesbystock + showstockstatus > 0){
		fetchStockInfo(id,arrProps); //load stock for item
	}
	for (iFetchStockInfo = 0; iFetchStockInfo < arrStock.length;iFetchStockInfo++){
		fetchStockInfo(parseInt(arrStock[iFetchStockInfo])); //load stock for subs
	}
	//if (id == 'shoppingcart'){
	if (document.getElementById('shoppingcart')){
		cartFetchStockInfoAll();
	}
	//sync menu: 1 find id's for path, 2 sequentially open id's
	//check if the id is not already open, for then syncing is not necessary
	if (mClicked != id){
		//do this only once, when there's a hash-id use that, else use the first id
		if (document.location.href.indexOf('#') == -1){ //there's no hash id
			ajaxRun('/scripts/menu_tracepath.asp',menu_tracepathReturn,'POST','itemid='+id,false,true);
		}else if(document.location.href.indexOf('#'+id) == document.location.href.indexOf('#')){ //this is the hash id we need to use
			ajaxRun('/scripts/menu_tracepath.asp',menu_tracepathReturn,'POST','itemid='+id,false,true);
		}
	}
}
function refreshUserData(){
	if (document.getElementById('addresses')){
		document.getElementById('addresses').innerHTML = '<img src="/img/loading.gif" />';
		ajaxRun('/scripts/shoppingcart_address.asp',shoppingcart_addressReturn,'POST','ajax=1',false,true);
	}
	if (document.getElementById('account')){
		document.getElementById('account').innerHTML = '<img src="/img/loading.gif" />';
		ajaxRun('/scripts/account.asp',accountReturn,'POST','ajax=1',false,true);
	}
}
function onbodyresize(){
	if (self.innerHeight){	// all except Explorer
		w = self.innerWidth;
		h = self.innerHeight;
	}else if (document.documentElement && document.documentElement.clientHeight){ // Explorer 6 Strict Mode
		w = document.documentElement.clientWidth;
		h = document.documentElement.clientHeight;
	}else if (document.body){ // other Explorers
		w = document.body.clientWidth;
		h = document.body.clientHeight;
	}
}

function onBodyUnload(){
	if (admin){
		return saveChanges();
	}
}

//************************
//******** Login *********
//************************

function loginuser(){
	return true; //ajax login doesn't work because of different subdomain the ajax is posting to, hence it is ignored
	if (!document.getElementById('loginuserDiv')){
		loginuserEl = document.createElement('DIV');
		loginuserEl.id = 'loginuserDiv';
		document.getElementById('login').appendChild(loginuserEl);
	}
	loginuserEl = document.getElementById('loginuserDiv');
	loginuserEl.innerHTML = '<div class="right"><img onclick="removeDiv(this.parentNode.parentNode);" style="cursor:pointer;" src="/img/buttons/remove_item.png" height="10" width="10" alt="Sluiten"/></div><hr/><form onsubmit="return formloginsubmit(this);" name="formloginuser" method="post"><div class="left">E-mail:</div><div class="right"><input type="text" autocomplete="off" name="un"/></div><div class="left">Wachtwoord:</div><div class="right"><input type="password" name="pw"/></div><div class="right"><input type="image" src="/img/buttons/logindiv_login.png" name="loginbutton"/></div></form><hr/><div id="create">Heeft u nog geen account?<br/><a href="/account.asp">Maak dan hier een account aan</a></div>';
	document.forms['formloginuser'].elements['un'].focus();
	return false;
}
function formloginsubmit(f){
	ajaxRun('https://secure.kookwinkel.nl/scripts/loginuser.asp',formloginsubmitReturn,'POST','un='+escape(f.un.value)+'&pw='+escape(f.pw.value)+'&ajax=1',false,true);
	return false;
}
function formloginsubmitReturn(xmlObj){
	if (xmlObj.readyState == 4){
		txt = xmlObj.responseText;
		if (txt.length < 10){
			if (eval(txt)){ //login succesful
				if (document.location.href.indexOf('loginuser.asp') != -1){
					document.location.replace('/loginuser.asp');
				}else{ //seperate login screen is not working because of https through ajax problem at the moment
					fnShowMsg('Inloggen gelukt!');
					document.getElementById('login').innerHTML = '<a href="/logoutuser.asp" onclick="return logoutuser();"><img src="/img/buttons/service_uitloggen.png" id="service_uitloggen" onmouseover="imageSwap(this,\'on\')" onmouseout="imageSwap(this,\'off\')"></a>';
					if (document.getElementById('loginuserDiv')){
						removeDiv(document.getElementById('loginuserDiv'));
					}
					refreshUserData();
				}
			}else{ //login failed
				if (txt == ''){ //probably ssl error, which might serve an empty page
					fnShowMsg('Er trad een fout op, kijk in uw adresbalk of de pagina beveiligd is (u ziet een slotje) en probeer het opnieuw.');
				}else{
					fnShowMsg('E-mail / wachtwoord combinatie is onbekend.',true);
				}
				if (document.forms['formlogin']){
					if (document.getElementById('loginuserDiv')){
						removeDiv(document.getElementById('loginuserDiv'));
					}
					f = document.forms['formlogin'];
					f.elements['pw'].value = '';
					f.elements['un'].focus();
					f.elements['un'].select();
				}else if (document.forms['formloginuser']){
					f = document.forms['formloginuser'];
					f.elements['pw'].value = '';
					f.elements['un'].focus();
					f.elements['un'].select();
				}
			}
			cartLoadCol();
			if (document.getElementById('shoppingcart')){
			//if (id == 'shoppingcart'){ //load shoppingcart
				ajaxRun('/scripts/shoppingcart.asp',showcartReturn,'POST','output=js',false,true);
			}
		}else{
			alert(txt); //.substring(2500));
		}
	}
}
function logoutuser(){
	ajaxRun('/scripts/logoutuser.asp',logoutuserReturn,'POST','ajax=1',false,true);
	return false;
}
function logoutuserReturn(xmlObj){
	if (xmlObj.readyState == 4){
		txt = xmlObj.responseText;
		if (eval(txt)){
			fnShowMsg('Uitloggen gelukt');
			document.getElementById('login').innerHTML = '<a href="/loginuser.asp" onclick="return loginuser();"><img src="/img/buttons/service_inloggen.png" id="service_inloggen" onmouseover="imageSwap(this,\'on\')" onmouseout="imageSwap(this,\'off\')"></a>';
			refreshUserData();
			cartLoadCol();
			if (document.getElementById('shoppingcart')){
			//if (id == 'shoppingcart'){ //load shoppingcart
				ajaxRun('/scripts/shoppingcart.asp',showcartReturn,'POST','output=js',false,true);
			}else{
				if (document.location.href.indexOf('loginuser.asp') != -1){
					setTimeout('document.location.replace(\'/loginuser.asp\');',1200);
				}else if (document.location.href.indexOf('secure.kookwinkel.nl') != -1){
					setTimeout('document.location.replace(\'/default.asp\');',1200);
				}
			}
		}else{
			alert(txt.substring(2500));
		}
	}
}

//********************************************
//*********** Promotional codes **************
//********************************************
enterCodeBoolean = false;
function enterCode(enterCodeString){
	if (enterCodeBoolean){
		showMsg('Een moment alstublieft.');
	}else{
		enterCodeBoolean = true;
		if (enterCodeString){
			ajaxRun('/scripts/entercode.asp',enterCodeReturn,'POST','ajax=1&entercode='+escape(enterCodeString),false,true);
		}else{
			//check if user is logged in
			ajaxRun('/scripts/account_check.asp',enterCodeReturn,'POST','ajax=1',false,true);
		}
	}
	return false;
}
function enterCodeReturn(xmlObj){
	if (xmlObj && xmlObj.readyState == 4){
		txt = xmlObj.responseText;
		ecrAuth = parseInt(txt.rat('auth'));
		ecrCode = parseInt(txt.rat('code'));
		if (ecrCode == 1){ //code was received, auth contains whether it was valid
			if (ecrAuth == 1){ //correct code received
				removeDiv(document.getElementById('showScrDiv'));
				fnShowMsg('Code correct ontvangen!');
				if (cart){
					//get totals
					cartGetTotals();
				}
				if (document.getElementById('cartsummary')){ //update the summary
					document.getElementById('cartsummary').innerHTML = 'Ververst winkelwagen...';
					ajaxRun('/scripts/cartsummary.asp',cartSummaryReturn,'POST','ajax=1',false,true);
				}
			}else{ //code not recognized, show warning
				fnShowWarning('Code niet (meer) geldig of verkeerd ingevoerd.');
			}
		}else{ //check if user is authenticated
			if (ecrAuth == 1){ //show screen to fill in code
				fnShowScr('<h3>Vul hier uw kortingscode in.</h3><form onsubmit="return enterCode(this.elements[\'entercode\'].value);"><p><input type="text" autocomplete="off" name="entercode"/> <input type="image" alt="OK" src="/img/buttons/ok.png"/></p></form>');
				try{
					document.getElementById('showScrDiv').childNodes[2].elements['entercode'].focus();
				}catch(e){

				}
			}else{ //show screen with message and link to login and register
				fnShowScr('<h3>U moet ingelogd zijn!</h3><p>Om uw kortingscode te kunnen gebruiken moet u een account hebben en ingelogd zijn.<br/><br/><a href="/account.asp">Maak een account</a> of <a href="/loginuser.asp" onclick="return loginuser();">log in op uw bestaande account.</a></p>');
			}
		}
		enterCodeBoolean = false;
	}
}
function cartSummaryReturn(xmlObj){
	if (xmlObj && xmlObj.readyState == 4){
		txt = xmlObj.responseText;
		document.getElementById('cartsummary').innerHTML = txt;
	}
}
function removeCode(removeCodeUserId,removeCodeId){
	ajaxRun('/scripts/removecode.asp?registereduserid='+removeCodeUserId+'&reductionschemeid='+removeCodeId,removeCodeReturn,'POST','ajax=1',false,true);
	return false;
}
function removeCodeReturn(xmlObj){
	if (xmlObj && xmlObj.readyState == 4){
		txt = xmlObj.responseText;
		if (eval(txt.rat('success'))){
			removeDiv(document.getElementById('code'+txt.rat('id')));
		}else{
			fnShowWarning(txt.rat('warning'));
		}
	}
}
//************************
//******* Content ********
//************************
function optout(ooLink){
	window.open(ooLink.href);
	return false;
}
function g(which,e){ //g = go, triggered by clicking somewhere in the item div or item_forlistview div
	if (!e) { e = event; }
	gSrc = (e.srcElement)?e.srcElement:e.target;
	if (gSrc.tagName == 'P' || gSrc.tagName == 'DIV' || gSrc.tagName == 'BUTTON'){ //do not go anywhere when clicking on the link (h3, img, span) or orderbutton (img)
		if (which.childNodes[0].href){
			document.location.href = which.childNodes[0].href;
			//l(which.childNodes[0]);
		}else{
			document.location.href = which.childNodes[0].childNodes[0].href;
			//l(which.childNodes[0].childNodes[0]);
		}
	}
}
function fnMoreInfo(boolMore){
	if (boolMore){
		elMetadescription = document.getElementById('metadescription');
		elMetadescription.childNodes[elMetadescription.childNodes.length - 1].style.display = 'none';
		document.getElementById('metabody').innerHTML = metabody_text + '<br/><br/><a href="#" onclick="return fnMoreInfo(false);">Verberg extra informatie.</a><br/><br/>';
		document.getElementById('metabody').style.display = 'block';
	}else{
		document.getElementById('metabody').style.display = 'none';
		elMetadescription = document.getElementById('metadescription');
		elMetadescription.childNodes[elMetadescription.childNodes.length - 1].style.display = 'block';
	}
	return false;
}
//2) make menu so it only tries to open a submenu once at a time to reduce traffic
function m(a,mSync){
	//return true; //short circuit
	if (!admin && (a.href.substr(7,4) == 'www.')){
		href = a.href;
		mItemid = parseInt(href.substring(href.lastIndexOf('/') + 1));
		mMenuid = parseInt(a.id.replace('m',''));
		if (document.getElementById('submenu'+mMenuid)){ //just close id
			document.getElementById('m'+mMenuid).style.backgroundImage = 'url(/img/x.gif)';
			removeDiv(document.getElementById('submenu'+mMenuid));
		}else{
			document.getElementById('m'+mMenuid).style.backgroundImage = 'url(/img/menuleft_up.png)'; //= '#ff0000';
			ajaxRun('/plugins/submenu.asp',submenuReturn,'POST','menuid='+mMenuid+'&itemid='+mItemid,false,true);
//			ajaxRun('/scripts/pageloader.asp',pageloaderReturn,'POST','id='+mItemid,false,true);
			//when syncing do not rederict to this page
			if (!mSync){
				mEventLabel = a.childNodes[0].innerHTML || a.innerHTML;
				_gaq.push(['_trackEvent', 'Menu_left', 'Open', mEventLabel]);
				mtprTxt = '';
				document.location.href = '#' + mItemid;
				mClicked = mItemid;
			}
//			document.location.href = Root + '#' + mItemid;
		}
		return false;
	}else{
		return true;
	}
}
function submenuReturn(xmlObj){
	if (xmlObj && xmlObj.readyState == 4){
		smrTxt = xmlObj.responseText;
		smrId = smrTxt.rat('id'); //id for _item_sub being unique for every menu item
		smrContent = smrTxt.rat('content');
		if (smrId == parseInt(smrId)){
			//remove all active icons
			smrPossibleMenuitems = document.getElementsByTagName('A');
			for (smri = 0;smri < smrPossibleMenuitems.length;smri++){
				smrTemp = smrPossibleMenuitems[smri].style.backgroundImage.replace(Root,'/');
				while (smrTemp.indexOf('\"') != -1){
					smrTemp = smrTemp.replace('\"','');
				}
				if (smrTemp == 'url(/img/menuleft_active.png)'){
					smrPossibleMenuitems[smri].style.backgroundImage = 'url(/img/x.gif)';
				}
			}
			if (smrContent.length > 1){
				smrMenuElement = document.getElementById('m'+smrId).parentNode; //document.getElementById('menu');
				smrSubMenu = document.createElement('DIV');
				smrSubMenu.className = 'submenu';
				smrSubMenu.id = 'submenu'+smrId;
				smrSubMenu.innerHTML = smrContent;
				smrMenuElement.insertBefore(smrSubMenu,document.getElementById('m'+smrId).nextSibling);
				synctoc(); //check if there's still some syncing to do, automatically
			}else{
				document.getElementById('m'+mMenuid).style.backgroundImage = 'url(/img/menuleft_active.png)'; //= '#ff0000';
			}
		}else{
			//alert(smrContent);//.substr(2500));
		}
	}
}

mtprTxt = ''; //synctoc string filled by ajax, shortened by syncing in synctoc func, called by submenuReturn
function menu_tracepathReturn(xmlObj){
	if (xmlObj && xmlObj.readyState == 4){
		mtprTxt = xmlObj.responseText; //format: itemid,itemidsub,id;itemid,itemidsub,id; etc. from table _item_sub
		synctoc();
//if (mtprTxt.length > 2500){
//	alert(mtprTxt.substring(2500));
//}else{
//	alert(mtprTxt);
//}
	}
}
function synctoc(){
	if (mtprTxt.length > 0){
		mtprMenuid = parseInt(mtprTxt);
		mtprTxt = mtprTxt.replace(mtprMenuid+',','');
		if (document.getElementById('m'+mtprMenuid)){ //if it's an item in a menu
			if (!document.getElementById('submenu'+mtprMenuid)){ //if the submenu isn't opened yet
				m(document.getElementById('m'+mtprMenuid),true); //true means this is auto syncing
			}else{
				synctoc();
			}
		}
	}
}

function l(a){
	return true; //short circuit this for now
	if (!isAdmin){
		href = a.href;
		hrefid = parseInt(href.substring(href.indexOf('webshop/') + 8));
//watch out, this is done by the watching function "checklocation"... is that good?
//		ajaxRun('/scripts/pageloader.asp',pageloaderReturn,'POST','id='+hrefid,false,true);
		document.location.href = '#' + hrefid; //Root + '#' + hrefid;
		return false;
	}else{
		return true;
	}
}
function s(a){ //loads site pages not in cms
	return true; //short circuit this for now
	if (!isAdmin){
		href = a.href.replace(Root,'');
		ajaxRun('/scripts/'+href,pageloaderReturn,'POST','ajax=1',false,true);
		return false;
	}else{
		return true;
	}
}
function pageloaderReturn(xmlObj){
	if (xmlObj && xmlObj.readyState == 4){
//window.scrollTo(0,0);
		txt = xmlObj.responseText;
		document.title = txt.rat('title');
		document.getElementById('content').innerHTML = txt.rat('content');
//alert(txt.rat('script'));
		try {
			eval(txt.rat('script'));
		}catch(e){
			fnShowWarning(e);
			document.getElementById('content').innerHTML = txt;
		}
		txt = null;
		runPage();
	}
}

function showcart(){
	return true; //short circuit this for now
	if (!isAdmin){
		document.location.href = Root + '#winkelwagen';
		return false;
	}else{
		return true;
	}
}
function showcartReturn(xmlObj){
	if (xmlObj && xmlObj.readyState == 4){
		document.title = 'Kookwinkelwagen';
		txt = xmlObj.responseText;
		try{
			eval(txt.rat('script'));
		}catch(e){
			//document.location.href='/shoppingcart.asp';
			alert(txt.rat('script'));
		}
		if (typeof(cartHTML) == 'function'){
			document.getElementById('content').innerHTML = cartHTML();
		}else{
			fnShowWarning('Script error.');
			document.getElementById('content').innerHTML = 'Er trad een fout op in het script, onze excuses. Probeer het eventueel nogmaals: <a href="javascript:;" onclick="return showcart();">toon winkelwagen</a>.<br/><br/>Of ga naar de <a href="shoppingcart.asp">kookwinkelwagen pagina</a>.';
		}
		//document.getElementById('cart').innerHTML = 'TEST';
	}
}

// ********* search **********
function searchloaderReturn(xmlObj){
	if (xmlObj && xmlObj.readyState == 4){
		txt = xmlObj.responseText;
		document.title = 'Zoeken';
		document.getElementById('content').innerHTML = txt;
	}
}
function src(){
	if (document.getElementById('srcsuggestions')){ //remove a suggestions box if it exists
		srcsuggestEl = document.getElementById('srcsuggestions').parentNode;
		srcsuggestEl.removeChild(document.getElementById('srcsuggestions'));
	}
	return true; //short circuit for now
	if (isAdmin){
		return true;
	}else{
		document.location.href = '#zoeken';
		return false;
	}
}
function socialLink(slName,slHref,slSrc){
	a = document.createElement('A');
	a.href = slHref;
	a.title = slName;
	a.onclick = new Function('return fnShare(this);');
	img = document.createElement('IMG');
	img.src = slSrc;
	img.alt = 'via '+slName;
	a.appendChild(img);
	return a;
}

//************************
//****** Functions *******
//************************

function loadScript(lsName){
	if (!document.getElementById(lsName)){
		loadscr = document.createElement('SCRIPT');
		loadscr.src = '/client/'+lsName.replace('-','.');
		loadscr.id = lsName;
		loadscr.type = 'text/javascript';
//		loadscr.onload = new Function('alert(2001)');
//		loadscr.onload = function(){
//			alert(2001);
//		}
		document.getElementsByTagName('head')[0].appendChild(loadscr);
	}
}
function removeDiv(removeDivWhich){
	try{
		removeDivParent = removeDivWhich.parentNode;
		removeDivParent.removeChild(removeDivWhich);
	}catch(e){
	
	}
}

function imageSwap(img,status) {
	if (status == 'on'){
		img.src = img.src.replace('.png','_over.png');
	}else{
		img.src = img.src.replace('_over.png','.png');
	}
}
function input_focus(if_which){
	if (if_which.name == if_which.value){
		if_which.value = '';
	}
}
function input_blur(ib_which){
	if (ib_which.value.replace(' ','') == ''){
		ib_which.value = ib_which.name;
	}
}

//** Shoppingcart **
function cartAddRow(addItemid,addQuantity){
	cartAddRowStr = 'ajax=1&itemid='+addItemid+'&quantity='+addQuantity;
	//get the properties
	for (icartAddRow = 0;icartAddRow < arrProps.length;icartAddRow++){
		if (arrProps[icartAddRow]){
			if ((typeof arrProps[icartAddRow]).toLowerCase() == 'number'){
				cartAddRowStr += '&property'+icartAddRow+'='+arrProps[icartAddRow];
			}else{ //this is a list of textboxes that can be filled in by the user
				for (icartAddRow2 in arrProps[icartAddRow]){
					carEl = document.forms['orderForm'].elements['propertyvalue'+icartAddRow2];
					if (carEl.title != carEl.value){
						cartAddRowStr += '&propertyvalue'+icartAddRow2+'='+escape(carEl.value);
					}
				}
			}
		}
	}
	ajaxRun('/scripts/cartAddRow.asp',cartAddRowReturn,'POST',cartAddRowStr,false,true);
	return false;
}
function cartAddRowReturn(xmlObj){
	if (xmlObj && xmlObj.readyState == 4){
		var txt = xmlObj.responseText;
		if (txt.substr(0,5) == 'ERROR'){
			//window.location.href = '#winkelwagen';
			//window.location.href = '/shoppingcart.asp';
			if (txt.indexOf('no property') != -1){
				fnShowScr('<b>Artikel toegevoegd</b>, maak alstublieft een keuze uit beschikbare opties voor dit artikel in <a href="/shoppingcart.asp">de winkelwagen</a>.');
			}else{
				fnShowWarning(txt);
			}
		}else{ //show cart in page
			document.getElementById('cart').innerHTML = txt;
			fnShowMsg(txt.substring(0,txt.indexOf('</span>')+7)+' toegevoegd.');
		}
	}
}
function cartLoadCol(){
	ajaxRun('/scripts/cartLoadCol.asp',cartLoadColReturn,'POST','',false,true);
	return false;
}
function cartLoadColReturn(xmlObj){
	if (xmlObj && xmlObj.readyState == 4){
		var txt = xmlObj.responseText;
		document.getElementById('cart').innerHTML = txt;
	}
}
//***********************************************
//Nieuwsbrief: inschrijven kolom links
function nieuwsbriefSubmit(nsform){
	ajaxRun('/scripts/nieuwsbrief.asp',nieuwsbriefSubmitReturn,'POST','ajax=1&E-mailadres='+nsform.elements['E-mailadres'].value+'&Naam='+nsform.elements['Naam'].value,false,true);
	return false;
}

function nieuwsbriefSubmitReturn(xmlObj){
	if (xmlObj && xmlObj.readyState == 4){
		var txt = xmlObj.responseText;
		if (txt.indexOf('Bedankt voor het aanmelden voor onze nieuwsbrief!') != -1){
			document.getElementById('formNieuwsbrief').innerHTML = '<div><br/><h3>Aanmelding gelukt</h3><br/>Bedankt voor het aanmelden voor onze nieuwsbrief!</div>';
		}else{
			fnShowWarning(txt);
		}
	}
}

//Nieuwsbrief: inschrijven op pagina zelf
function nieuwsbriefPageSubmit(nsform){
	ajaxRun('/scripts/nieuwsbrief.asp',nieuwsbriefPageSubmitReturn,'POST','ajax=1&E-mailadres='+nsform.elements['E-mailadres'].value+'&Naam='+nsform.elements['Naam'].value,false,true);
	return false;
}

function nieuwsbriefPageSubmitReturn(xmlObj){
	if (xmlObj && xmlObj.readyState == 4){
		var txt = xmlObj.responseText;
		if (txt.indexOf('Bedankt voor het aanmelden voor onze nieuwsbrief!') != -1){
			document.forms['formNieuwsbriefPage'].innerHTML = '<div><br/><h3>Aanmelding gelukt</h3><br/>Bedankt voor het aanmelden voor onze nieuwsbrief!</div>';
		}else{
			fnShowWarning(txt);
		}
	}
}

//Nieuwsbrief: uitschrijven
function nieuwsbriefUnsubscribeSubmit(nsform){
	ajaxRun('/scripts/nieuwsbrief_uitschrijven.asp',nieuwsbriefUnsubscribeSubmitReturn,'POST','ajax=1&E-mailadres='+nsform.elements['E-mailadres'].value,false,true);
	return false;
}

function nieuwsbriefUnsubscribeSubmitReturn(xmlObj){
	if (xmlObj && xmlObj.readyState == 4){
		var txt = xmlObj.responseText;
		if (txt.indexOf('U bent met succes afgemeld voor onze nieuwsbrief.') != -1){
			document.forms['formNieuwsbriefUitschrijven'].innerHTML = '<br/><h3>Afmelding gelukt</h3><br/>Uw emailadres is uit onze mailinglijst verwijderd.';
		}else{
			fnShowWarning(txt);
		}
	}
}

function fnShowReductionInfo(sriId){
	if (sriId > 0){
		ajaxRun('/scripts/showreductioninfo.asp',fnShowReductionInfoReturn,'POST','id='+sriId,false,true);
	}else{
		fnShowMsg('Speciale kortingsactie. Profiteer door op &quot;Bestel&quot; te drukken.',0);
	}
}
function fnShowReductionInfoReturn(xmlObj){
	if (xmlObj && xmlObj.readyState == 4){
		txt = xmlObj.responseText;
		fnShowScr(txt,0);
	}
}

function chooseProperty(choosePropertyid,choosePropertyvalueid){
	//unchoose current image, if any, before rechoosing all
	elCP = document.getElementById('prop'+choosePropertyid+'-'+arrProps[choosePropertyid]);
	if (elCP){
		elCP.className = null;
	}
	arrProps[choosePropertyid] = parseInt(choosePropertyvalueid);
	articlepropertiesimagechosen();
	//fetch new stock info for this combination
	if (limitsalesbystock + showstockstatus > 0){
		fetchStockInfo(id,arrProps);
	}
}
function articlepropertiesimagechosen(){
	for (iApic = 0;iApic < arrProps.length;iApic++){
		if (arrProps[iApic]){
			try{
				elApic = document.getElementById('prop'+iApic+'-'+arrProps[iApic]);
				elApic.className = 'chosen';
			}catch(e){
			
			}
		}
	}
}
function userfill(ufWhich){
	if (ufWhich.value == ufWhich.title){
		ufWhich.value = '';
	}
	ufWhich.className = 'userfilled';
	if (cart){
		ufWhich.parentNode.childNodes[ufWhich.parentNode.childNodes.length - 1].style.display = 'block';
	}
}
function userfilled(ufWhich){
	if (ufWhich.value == ''){
		ufWhich.value = ufWhich.title;
		ufWhich.className = 'userfill';
	}
}

//** Stock info **
function fetchStockInfo(){ //arguments itemid, divid (identifying layer for return message), and optional arrProps
	fetchStockInfoId = parseInt(fetchStockInfo.arguments[0]);
	var fsiProps = new Array();
	if (fetchStockInfo.arguments[1]){
		fsiProps = fetchStockInfo.arguments[1];
	}
	fsiStr = 'id='+fetchStockInfoId;
	for (iFsi = 0;iFsi < fsiProps.length;iFsi++){
		if (fsiProps[iFsi]){
			fsiStr = fsiStr + '&property' + iFsi + '=' + fsiProps[iFsi];
		}
	}
//alert(fsiStr);
	ajaxRun('/plugins/fetchStockInfo.asp',displayStockInfo,'POST',fsiStr,false,true)
}
function displayStockInfo(xmlObj){
	if (xmlObj && xmlObj.readyState == 4){
		//if(xmlObj.status == 200){
		var txt = xmlObj.responseText;
		//alert(txt.substr(2000));
		var id = parseInt(txt.replace('<id>',''));
		txt = txt.replace('<id>'+id+'</id>','');
		//if (txt.length > 2500){
		//	alert(txt.substr(2500));
		//}else{
		//	alert(txt);
		//}
		//alert(id+'\n'+txt);
		var elStock = null;
		var stockTableId = id;
		if (document.getElementById('stock'+id+'main')){
			elStock = document.getElementById('stock'+id+'main');
		}else if (document.getElementById('stock'+id+'sub')){
			elStock = document.getElementById('stock'+id+'sub');
		}
		if (elStock != null){
			elStock.innerHTML = txt;
		}
	}
	return;
}

//** Search function **
srcsuggestIndex = -1;
function catchtab(catchtabEvent){
	keyCode = catchtabEvent.keyCode || catchtabEvent.which;
	return keyCode != 9;
}
function srcsuggest(srcsuggestEvent,srcsuggestInput){
	keyCode = srcsuggestEvent.keyCode || srcsuggestEvent.which;
	if (keyCode == 40 || keyCode == 38){ //arrows: walk through
		srcsuggestEl = document.getElementById('srcsuggestions');
		if (srcsuggestEl.childNodes.length > 1){
			if (srcsuggestIndex >= 0){
				srcsuggestEl.childNodes[srcsuggestIndex].style.backgroundColor = '#f9f9f9';
			}
			if (keyCode == 40){
				srcsuggestIndex++;
				if (srcsuggestIndex > srcsuggestEl.childNodes.length - 2){
					srcsuggestIndex = 0;
				}
			}else{ //omhoog
				srcsuggestIndex--;
				if (srcsuggestIndex < 0){
					srcsuggestIndex = srcsuggestEl.childNodes.length - 2;
				}
			}
			srcsuggestEl.childNodes[srcsuggestIndex].style.backgroundColor = '#cecece';
			srcsuggestInput.value = srcsuggestEl.childNodes[srcsuggestIndex].title;
		}
	}else if (keyCode == 13){ //enter

	}else if (keyCode == 9){ //tab - because of catchtab focus is maintained to catch onkeyup event
		srcsuggestTmp = srcsuggestInput.value;
		srcsuggestInput.value = srcsuggestTmp + ' ';
		srcsuggestRemove();
	}else if (keyCode == 188){ //comma: interferes with ajax and is unnecessary anyway
		srcsuggestTemp = srcsuggestInput.value;
		srcsuggestInput.value = srcsuggestTemp.replaceAll(',','');
	}else if (keyCode == 27){ //escape
		srcsuggestRemove();
	}else{
		srcsuggestIndex = -1;
		ajaxRun('/scripts/srcsuggest.asp',srcsuggestReturn,'POST','input='+escape(srcsuggestInput.value),false,true);
	}
}
function srcsuggestRemove(){
	if (document.getElementById('srcsuggestions')){ //remove a suggestions box if it exists
		srcsuggestEl = document.getElementById('srcsuggestions').parentNode;
		srcsuggestEl.removeChild(document.getElementById('srcsuggestions'));
	}
}
function srcsuggestReturn(xmlObj){
	if (xmlObj && xmlObj.readyState == 4){
		txt = xmlObj.responseText;
		srcsuggestReturnArr = txt.split(',');
		if (srcsuggestReturnArr.length == 1){ //no suggestions (why length is 1 then, I don't fully grasp)
			srcsuggestRemove();
		}else{ //there are suggestions
			if (!document.getElementById('srcsuggestions')){ //create a suggestions box if it doesn't exist yet
				srcsuggestEl = document.createElement('DIV');
				srcsuggestEl.id = 'srcsuggestions';
				document.getElementById('searchform').appendChild(srcsuggestEl);
			}
			srcsuggestEl = document.getElementById('srcsuggestions');
			//srcsuggestEl.style.top = '65px';//(findPosY(srcsuggestEl.parentNode)) + 'px';
			//srcsuggestEl.style.left = '11px';
			//srcsuggestEl.style.width = (srcsuggestEl.parentNode.offsetWidth - 16) + 'px';
			//empty the div first
			while (srcsuggestEl.childNodes.length > 0){
				srcsuggestEl.removeChild(srcsuggestEl.childNodes[0]);
			}
			for (isrcsuggest=0;isrcsuggest<srcsuggestReturnArr.length;isrcsuggest++){
				srcsuggestDiv = document.createElement('DIV'); //replaceAll prototype under "prototype" header
				//srcsuggestDiv.onclick = new Function('srcsuggestchoose(\''+srcsuggestReturnArr[isrcsuggest].replaceAll('\\','\\\\').replaceAll('\'','\\\'')+'\');');
				srcsuggestDiv.onclick = new Function('srcsuggestchoose(this);');
				srcsuggestDiv.style.cursor = 'pointer';
				srcsuggestDiv.onmouseover = new Function('this.style.backgroundColor = \'#CECECE\';');
				srcsuggestDiv.onmouseout = new Function('this.style.backgroundColor = \'#f9f9f9\';');
				srcsuggestDiv.title = srcsuggestReturnArr[isrcsuggest];
				srcsuggestDiv.appendChild(document.createTextNode(srcsuggestReturnArr[isrcsuggest]));
				srcsuggestEl.appendChild(srcsuggestDiv);
			}
		}		
	}else{
		xmlObj = null;
	}
}
function srcsuggestchoose(which){
	document.getElementById('searchform').elements[0].value = which.innerHTML;
	document.getElementById('searchform').elements[0].focus();
	//src();
	document.getElementById('searchform').submit();
}


//** From Externals **

function printOrder(orderIdToPrint){
	orderWindow = window.open('printorder.asp?orderid='+orderIdToPrint,'orderWindow','width=400,height=400,resizable,scrollbars,status');
	orderWindow.focus();
}
//** General functionality **

function makeAmount(makeAmountInput){
	makeAmountInput = parseInt(makeAmountInput);
	try{
		return('&euro; '+(makeAmountInput / 100).formatMoney(2,',','.'));
	}catch(e){
		return '&euro; 0,00';
	}
}
function fnShowWarning(fnShowWarningTxt){
	if (!document.getElementById('showWarningDiv')){
		fnShowWarningEl = document.createElement('DIV');
		fnShowWarningEl.id = 'showWarningDiv';
		fnShowWarningEl.zIndex = 100; //99 = superpose
		fnShowWarningEl.style.position = 'absolute';
		document.getElementById('wrapper').appendChild(fnShowWarningEl);
	}
	fnShowWarningBox = document.getElementById('showWarningDiv');
	fnShowWarningBox.innerHTML = fnShowWarningTxt;
	positionLayer(fnShowWarningBox,360,getYOffset()+300,10);
	fade('showWarningDiv',128,50,50);
	setTimeout('fade(\'showWarningDiv\',0,-10);',1200);
}
var isShowingMsg = false;
function fnShowMsg(fnShowMsgTxt,isWarning){
	if (isWarning){
		fnShowWarning(fnShowMsgTxt)
	}else if (isShowingMsg){
		setTimeout('fnShowMsg(\''+fnShowMsgTxt+'\');',300);
	}else{
		isShowingMsg = true;
		if (!document.getElementById('showMsgDiv')){
			fnShowMsgEl = document.createElement('DIV');
			fnShowMsgEl.id = 'showMsgDiv';
			fnShowMsgEl.zIndex = 100; //99 = superpose
			fnShowMsgEl.style.position = 'absolute';
			document.getElementById('wrapper').appendChild(fnShowMsgEl);
		}
		fnShowMsgBox = document.getElementById('showMsgDiv');
		fnShowMsgBox.innerHTML = fnShowMsgTxt;
		positionLayer(fnShowMsgBox,360,getYOffset()+300,10);
		fade('showMsgDiv',128,100,50);
		setTimeout('fade(\'showMsgDiv\',0,-10);',1200);
		setTimeout('isShowingMsg=false;',1500);
	}
}
function fnShare(fnShareLink){
	//fnShowScr('<iframe src="'+fnShareUrl+'"></iframe>');
	window.open(fnShareLink.href);
	_gaq.push(['_trackEvent', 'Socialmedia', fnShareLink.title, document.title]);
	return false;
}
function fnShowScr(fnShowScrTxt,isWarning){
	if (!document.getElementById('showScrDiv')){
		fnShowScrEl = document.createElement('DIV');
		fnShowScrEl.id = 'showScrDiv';
		fnShowScrEl.style.position = 'absolute';
		document.getElementById('wrapper').appendChild(fnShowScrEl);
	}
	fnShowScrBox = document.getElementById('showScrDiv');
	if (isWarning){
		fnShowScrBox.className = 'warning';
	}else{
		fnShowScrBox.className = 'normal';
	}
	fnShowScrBox.innerHTML = '<div><img src="/img/design/buttons/x.png" alt="Sluiten" class="close" onclick="removeDiv(document.getElementById(\'showScrDiv\'));"/></div>' + fnShowScrTxt;
	//fnShowScrBox.onclick = new Function('removeDiv(this)');
	fnShowScrBox.onclick = function(e){
		var fnShowScrCaller;
		if (e){
			if (e.target.parentNode){ fnShowScrCaller = e.target.tagName; }
		}else{
			fnShowScrCaller = window.event.srcElement.tagName;
		}
		if (fnShowScrCaller == 'A'){
			removeDiv(this);
		}
	}
	positionLayer(fnShowScrBox,320,getYOffset()+310,10);
	fade('showScrDiv',128,100,50);
}


function RefreshImage_DEPRECATED(valImageId) { //CAPTCHA
	var objImage = document.images[valImageId];
	if (objImage == undefined) {
		return;
	}
	var now = new Date();
	objImage.src = objImage.src.split('?')[0] + '?x=' + now.toUTCString();
}

//** Positioning and stuff **
var mouseX = 0;
var mouseY = 0;
function getMouseXY(e){
	try{ //maybe the page isn't loaded yet
		if (document.all) { // grab the x-y pos.s if browser is IE
			mouseX = event.clientX + document.body.scrollLeft;
			mouseY = event.clientY + document.body.scrollTop;
		}else{  // grab the x-y pos.s if browser is NS
			mouseX = e.pageX;
			mouseY = e.pageY;
		}  
		return true;
	}catch(e){
		//alert(e);
	}
}
function getYOffset(){
	return window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop || 0;
}
function findPosX(obj){
	var curleft = 0;
	if (obj.offsetParent){
		while (obj.offsetParent){
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}else if (obj.x){
		curleft += obj.x;
	}
	return curleft;
}
function findPosY(obj){
	var curtop = 0;
	if (obj){
		if (obj.offsetParent){
			while (obj.offsetParent){
				curtop += obj.offsetTop;
				//curtop -= obj.scrollTop;
				obj = obj.offsetParent;
			}
		}else if (obj.y){
			curtop += obj.y;
		}
		return curtop;
	}
}
function positionLayer(lyr,x,y,z,limitX,limitY){ //document.zoekForm.q.value=lyr;
	if (!z){ z = 1; }
	if (typeof lyr == 'string'){ lyr = document.getElementById(lyr); }
	if (limitX){
		if (x + lyr.offsetWidth > w){
			xSubtract = x + lyr.offsetWidth - w;
			x = x - xSubtract;
		}
	}
	if (limitY){
		if (y + lyr.offsetHeight > h + getYOffset()){
			ySubtract = y + lyr.offsetHeight - (h + getYOffset());
			y = y - ySubtract;
		}
	}
	//hideSelectListsWhenNecessary(lyr,x,y); //currently unavailable
	lyr.style.left = x + 'px';
	lyr.style.top = y + 'px';
	lyr.style.zIndex = z;
}
//** fading **
var isFading = false;
var arrFading = new Array();
var fadeTimeout = false;
var fadeSpeed = 100;
function fade(fade_el,fade_target,fade_step,fade_current){
	if (window.loaded){
		if (!fade_el.id){ fade_el = document.getElementById(fade_el); } // input strings also
		if (fade_el){ //might be gone due to ajax
			(fade_target != -1)?arrFading[fade_el.id+'t'] = fade_target:fade_target = arrFading[fade_el.id+'t'];
			(fade_current)?arrFading[fade_el.id+'c'] = fade_current:fade_current = arrFading[fade_el.id+'c'];
			if (fade_current > 0){ fade_el.style.visibility='visible'; }
			if (Math.abs(fade_target-(Math.abs(fade_current)+fade_step)) < Math.abs(fade_target-Math.abs(fade_current))){
				fade_el.style.filter='alpha(opacity='+fade_current+')';
				fade_el.style.opacity=fade_current / 100;
				fade_el.style.MozOpacity=fade_current / 100;
				if (fade_target - fade_current == fade_step){ fade_step = fade_step + 1; }//bug when reaching exactly zero: fade loops
				fadeTimeout = setTimeout('fade(\''+fade_el.id+'\',-1,'+fade_step+','+(fade_current+fade_step)+')',fadeSpeed);
			}else{
				fade_current = fade_target;
				fade_el.style.filter='alpha(opacity='+fade_target+')';
				fade_el.style.opacity=fade_target / 100;
				fade_el.style.MozOpacity=fade_target / 100;
				arrFading[fade_el.id+'c']=fade_target; }
			if (fade_current == 0){ fade_el.style.visibility='hidden'; }
			if (fade_current == fade_target){
				isFading = false;
			}
		}
	}
}

//************************
//****** Left Menu *******
//************************
function menu(){
	this.items = new Array();
}
menu.prototype.add = function(addItemInput){ //input a menuItem
	this.items[this.items.length] = addItemInput; //menuItems can be entered multiple times with different "sub" ids / parents
}
menu.prototype.start = function(loadmenudiv){
	for (index = 0;index < this.items.length;index++){
		loadmenudiv.appendChild(this.items[index].plusminus());
		loadmenudiv.appendChild(this.items[index].a());
	}
}
menu.prototype.i = function(menuItemId){
	var iArr = new Array();
	for (index = 0;index < this.items.length;index++){
		if (this.items[index].id == menuItemId){
			iArr[iArr.length] = this.items[index];
		}
	}
	return iArr;
//	iArr = null;
}
function menuItem(itemid,itemt,itemidsub,subs){
	this.id = itemid;
	this.t = itemt;
	this.tlong = itemt;
	this.subid = itemidsub;
	this.subs = subs;
}
menuItem.prototype.a = function(){
	var div = document.createElement('DIV');
	var diva = document.createElement('A');
	diva.href = 'cms,'+this.id+','+this.tlong
	diva.title = this.tlong
	diva.onclick = new Function('return l(this)');
	div.appendChild(document.createTextNode(this.t));
	div.className = 'menu';
	div.onmouseover = new Function('this.className = \'menuOVER\';');
	div.onmouseout = new Function('this.className = \'menu\';');
	diva.appendChild(div);
	return diva;
}
menuItem.prototype.plusminus = function(){
	var div = document.createElement('DIV');
	div.className = 'menuOPEN';
	var diva = document.createElement('A');
	diva.style.clear = 'left';
	if (this.subs > 0){
		diva.title = 'Open';
		diva.href = 'javascript:;';
		diva.onclick = function(){
			alert('openclose'); //maak check of ie open of dicht is en doe ajaxrun naar openen of verwijder het onderliggende
		}
		div.appendChild(document.createTextNode('+'));
	}else{
		diva.title = '';
		div.appendChild(document.createTextNode('-'));
	}
	diva.appendChild(div);
	return diva;
}
menuItem.prototype.openclose = function(){
	alert('laden');
}
menuItem.prototype.parent = function(){

}
menuItem.prototype.children = function(){

}

//*************************
//******* Top menu ********
//*************************
tmTimeout = window.setTimeout('',500);
clearTimeout(tmTimeout);
function tm(){
	this.items = new Object;
	this.isActive = false;
	this.isFetching = false;
	this.whichFetching = null;
	this.waittime = 150; //msec
}
tm.prototype.create = function(tmcreateList){
	tmcreateel = document.getElementById('body');
	if (document.getElementById('submenu')){
		alert('Submenu bestaat al, dat moet niet kunnen.');
	}else{
		var tmcreateel2 = document.createElement('DIV');
		tmcreateel2.id = 'submenu';
		tmcreateel2.style.display = 'none';
		tmcreateel2.onmouseover = new Function('clearTimeout(tmTimeout);');
		tmcreateel2.onmouseout = new Function('tmTimeout = window.setTimeout(\'tm.hide();\','+this.waittime+')');
		tmcreateel.appendChild(tmcreateel2);
	}
	tmcreateel = document.getElementById('topmenu');
	tmcreateargs = tmcreateList.split(',');
	for (tmcreatei = 0;tmcreatei < tmcreateargs.length;tmcreatei++){
		tmcreateel.appendChild(tm.add(tmcreateargs[tmcreatei]));
	}
}
tm.prototype.add = function(tmAddWhich){
	tmAdda = document.createElement('A');
	tmAdda.href = '/menu/'+tmAddWhich.toLowerCase();
	//tmAdda.id = 'tm_'+tmAddWhich;
	tmAdda.onclick = new Function('return tmClick(this);');
	tmAdda.onmouseover = new Function('tm.hover(this);');
	tmAdda.onmouseout = new Function('tm.unhover(this);');
	//tmAdda.appendChild(document.createTextNode(tmAddWhich));
	//add button
	tmAddimg = document.createElement('IMG');
	tmAddimg.src = '/img/buttons/top_'+tmAddWhich.toLowerCase()+'.png';
	tmAddimg.alt = tmAddWhich;
	tmAdda.appendChild(tmAddimg);
	//add to array
	this.items[tmAdda] = new Object;
	this.items[tmAdda].a = tmAdda;
	this.items[tmAdda].content = false;
	//return link
	return tmAdda;
}
tm.prototype.hide = function(tmHideWhich){
	if (!this.isFetching){
		document.getElementById('submenu').style.display = 'none';
		//remove all actives
		for (tmHideA in this.items){
			this.items[tmHideA].a.childNodes[0].src = '/img/buttons/top_'+this.items[tmHideA].a.childNodes[0].alt.toLowerCase()+'.png';
		}
		//show rollover when clicked
		if (tmHideWhich){
			tmHideWhich.childNodes[0].src = '/img/buttons/top_'+tmHideWhich.childNodes[0].alt.toLowerCase()+'_over.png';
		}
		this.isActive = false;
	}
}
tm.prototype.show = function(tmShowWhich){
	if (!this.items[tmShowWhich].content){
		if (this.isFetching){
			//alert('is fetching');
			fnShowMsg('Working...');
		}else{
			this.isFetching = true;
			this.whichFetching = tmShowWhich;
			ajaxRun(tmShowWhich.href + '/content.html',tmShowReturn,'GET','',false,true);
		}
	}else{
		this.isActive = true;
		//remove all actives
		for (tmShowA in this.items){
			this.items[tmShowA].a.childNodes[0].src = '/img/buttons/top_'+this.items[tmShowA].a.childNodes[0].alt.toLowerCase()+'.png';
		}
		//show this as active
		tmShowWhich.childNodes[0].src = '/img/buttons/top_'+tmShowWhich.childNodes[0].alt.toLowerCase()+'_active.png';
		tmshowEl = document.getElementById('submenu');
		tmshowEl.style.display = 'block';
		tmshowEl.style.left = '-2000px'; //(findPosX(tmShowWhich) - 3) + 'px';
		tmshowEl.style.top = '129px';
		tmshowEl.style.zIndex = 3;
		switch (tmShowWhich.childNodes[0].alt){ //left (Pannen) and rightmost (Tafelen) menu items are special, layout wise
			case 'Pannen':
				tmshowEl.innerHTML = '<table class="shadow"><tr><td class="left">&nbsp;</td><td>'+this.items[tmShowWhich].content+'</td><td class="right">&nbsp;</td></tr><tr><td class="lowerleft"><img src="/img/design/shadow_lowerleft.png" alt=""/></td><td class="lower">&nbsp;</td><td class="lowerright"><img src="/img/design/shadow_lowerright.png" alt=""/></td></tr></table>';
				tmshowEl.style.left = (findPosX(tmShowWhich) - 1) + 'px';
				break;
			case 'Tafelen':
				tmshowEl.innerHTML = '<table class="shadow"><tr><td class="left">&nbsp;</td><td>'+this.items[tmShowWhich].content+'</td></tr><tr><td class="lowerleft"><img src="/img/design/shadow_lowerleft.png" alt=""/></td><td class="lower">&nbsp;</td></tr></table>';
				if (document.all){ //sorry, this must be implemented better but I'm running out of time
					tmshowEl.style.left = (w / 2 + 487 - tmshowEl.offsetWidth) + 'px';
				}else{
					tmshowEl.style.left = (w / 2 + 479 - tmshowEl.offsetWidth) + 'px';
				}
				break;
			default:
				tmshowEl.innerHTML = '<table class="shadow"><tr><td class="left">&nbsp;</td><td>'+this.items[tmShowWhich].content+'</td><td class="right">&nbsp;</td></tr><tr><td class="lowerleft"><img src="/img/design/shadow_lowerleft.png" alt=""/></td><td class="lower">&nbsp;</td><td class="lowerright"><img src="/img/design/shadow_lowerright.png" alt=""/></td></tr></table>';
				//do not exceed site width
				if (tmshowEl.offsetWidth + findPosX(tmShowWhich) > w / 2 + 493){
					if (document.all){ //sorry, this must be implemented better but I'm running out of time
						tmshowEl.style.left = (w / 2 + 483 - tmshowEl.offsetWidth) + 'px';
					}else{
						tmshowEl.style.left = (w / 2 + 474 - tmshowEl.offsetWidth) + 'px';
					}
				}else{
					tmshowEl.style.left = (findPosX(tmShowWhich) - 3) + 'px';
				}
		//switch ended
		}
	}
}
tm.prototype.hover = function(tmHoverWhich){
	clearTimeout(tmTimeout);
	if (this.isActive){
		this.show(tmHoverWhich);
	}else{
		tmHoverWhich.childNodes[0].src = '/img/buttons/top_'+tmHoverWhich.childNodes[0].alt.toLowerCase()+'_over.png';
	}
}
tm.prototype.unhover = function(tmUnhoverWhich){
	tmTimeout = window.setTimeout('tm.hide();',this.waittime);
	if (!this.isActive){ //change back immediately, else wait for the next active one so it remains active when hovering over submenu
		tmUnhoverWhich.childNodes[0].src = '/img/buttons/top_'+tmUnhoverWhich.childNodes[0].alt.toLowerCase()+'.png';
	}
}
function tmShowReturn(xmlObj){
	if (xmlObj.readyState == 4){
		//txt = xmlObj.responseText;
		//set content
		tm.items[tm.whichFetching].content = xmlObj.responseText;
		//show
		tm.show(tm.whichFetching);
		//statistics
		if (!admin){
			_gaq.push(['_trackEvent', 'Menu_top', 'Open', tm.whichFetching.childNodes[0].alt]);
		}
		//reset stuff
		tm.isFetching = false;
		tm.whichFetching = '';
	}
}
//handling of the menu
function tmClick(tmcWhich){
	tmcWhich.blur();
	if (tm.isActive){
		tm.hide(tmcWhich);
		//document.location.href = tmcWhich.href;
	}else{
		tm.show(tmcWhich);
	}
	//ajaxRun(tmcWhich.href + 'content.html',tmClickReturn,'POST','',false,true);
	return false;
}


//added functionality
if (!Object.keys){
	Object.keys = function(obj){
		var keys = new Array();
		for (k in obj){
			if (obj.hasOwnProperty(k)){
				keys.push(k);
			}
		}
		return keys;
	}
}

//**************************
//****** Prototype *********
//**************************
Number.prototype.formatMoney = function(c, d, t){var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;   return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); };

String.prototype.replaceAll = function(replaceAllWhat,replaceAllWith){
	var replaceAllTemp = this;
	var replaceAllIndex = replaceAllTemp.indexOf(replaceAllWhat);
	var replaceAllWithLength = replaceAllWith.length;
	var replaceAllWhatLength = replaceAllWhat.length;
	while (replaceAllIndex != -1){
		replaceAllTemp = replaceAllTemp.substring(0,replaceAllIndex) + replaceAllWith + replaceAllTemp.substring(replaceAllIndex + replaceAllWhatLength,replaceAllTemp.length);
		replaceAllIndex += replaceAllWithLength;
		replaceAllIndex = replaceAllTemp.indexOf(replaceAllWhat,replaceAllIndex);
	}
	return replaceAllTemp;
}

String.prototype.rat = function(ratTerm){ //rat = read a tag
	var ratText = this;
	return ratText.substring(ratText.indexOf('<'+ratTerm+'>'),ratText.indexOf('</'+ratTerm+'>',ratText.indexOf('<'+ratTerm+'>'))).replace('<'+ratTerm+'>','');
}
//************************
//******* AJAX! ********** PSV!!!!!!
//************************

function getHTTPObject() {
    if (typeof XMLHttpRequest != 'undefined') {
        return new XMLHttpRequest();
    }
    try {
        return new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            return new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {}
    }
    return false;
}
function ajaxRun(url, callback, method, qs, noAsync, passXMLObj){
	if(!noAsync){
		noAsync = false;
	}
	var xmlHttp = null;
	xmlHttp = getHTTPObject();
	if(xmlHttp == null){
		window.status = "Your browser does not support AJAX!";
		return;
	}
	//url = clientURL() + url;
	if(method=="GET"){
		url = url + "?" + qs;
	}
	// Check if we're passing the XML object to the callback function
	if(passXMLObj){
		var cb = callback;
		callback = function(){
			var xmlObj = xmlHttp;
			cb(xmlObj);
			return;
		}
	}
	// The magic happens next
	xmlHttp.open(method, url, !noAsync);
	xmlHttp.onreadystatechange = callback;
	if(method=="POST"){
		xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xmlHttp.send(qs);
	}else{
		xmlHttp.send(null);
	}
	return;
}

