// ---------------------------------------------------------------------- Wishlist
var req;
var reqTimeout;
 
function loadXMLDoc(url, id) {
  req = null;
  if (window.XMLHttpRequest) {
    try {
      req = new XMLHttpRequest();
    } catch (e){}
  } else if (window.ActiveXObject) {
    try {
      req = new ActiveXObject('Msxml2.XMLHTTP');
    } catch (e){
 		  try {
        req = new ActiveXObject('Microsoft.XMLHTTP');
      } catch (e){}
    }
  }
 
  if (req) {
    req.open("GET", url, true);
	  req.onreadystatechange = function(){
		  if (req.readyState == 4) {
    	  clearTimeout(reqTimeout);
     		if (req.status == 200) {
					document.getElementById('note'+id).innerHTML=req.responseText;
      	}
    	}
		}
    req.send(null);
    reqTimeout = setTimeout("req.abort();", 5000);
  }
}
function requestData(comment, regid, prodid, vendor, id)
{
  loadXMLDoc('/index.php?page=clientWishlist&action=addComment&comment='+document.getElementById(comment).value+'&regid='+regid+'&prodid='+prodid+'&vendor='+vendor, id);
}

// ---------------------------------------------------------------------- Ratings
function showRating(rating, initValue){
 $('ratingsMouseOver').removeClass('ratingsLarge1');
 $('ratingsMouseOver').removeClass('ratingsLarge2');
 $('ratingsMouseOver').removeClass('ratingsLarge3');
 $('ratingsMouseOver').removeClass('ratingsLarge4');
 $('ratingsMouseOver').removeClass('ratingsLarge5');

 $('state0').setStyle('display', 'none');
 $('state1').setStyle('display', 'none');
 $('state2').setStyle('display', 'none');
 $('state3').setStyle('display', 'none');
 $('state4').setStyle('display', 'none');
 $('state5').setStyle('display', 'none');

 $('ratingsMouseOver').addClass('ratingsLarge' + rating);
 $('ratingsMouseOver').addClass('ratingsLarge' + initValue);
 $('state' + rating).setStyle('display', 'block');
}

function setRating(rating, pageID){
 //alert('Je hebt ' + rating + 'points gegeven voor product ' + pageID) 

	$pageData	=	pageID.split('|');
	vendor	=	$pageData[0];
	prod_id	=	$pageData[1];

 	var url = '/ajax.php?request=productRating&rating='+escape(rating)+'&vendor='+escape(vendor)+'&prodid='+escape(prod_id);

	new Ajax(url, {
		method: 'get',
		update: $('reviewGive')
	}).request();

}
// ---------------------------------------------------------------------- Tooltip
function toolTips(){
  var toolTip = new Tips($$('.toolTip'));
}

// ---------------------------------------------------------------------- Ie png fix
function ie6PngFix(){
	if (document.all && document.styleSheets && document.styleSheets[0] &&
		document.styleSheets[0].addRule)
	{
		document.styleSheets[0].addRule('img', 'behavior: url(styles/iepngfix.htc)');
	}
}
// ---------------------------------------------------------------------- setTopsellersAccordion
function setTopsellersAccordion(){
	var topsellerAccordion = new Accordion('h4.atStartTS', 'div.atStartTS',	{
		show: 99,
		opacity: false,
		alwaysHide: true,
		onActive: function(toggler, element){
			toggler.className = "lb active"
			element.setStyle('display', 'block');
		},
		onBackground: function(toggler, element){
			toggler.className = 'lb nonActive'
			location.href = "#topsellerTop";
		}
	}, $('topsellerAccordion'));
}

// ---------------------------------------------------------------------- Set compare products page
function setCompareProducts(amount){
	if (amount > 3){
		$('container').addClass('wideCompare');
		newWidth = (170*2) + (amount*170);
		$('compareTable').setStyle('width', newWidth)
		}
	else if (amount == 3){
		$('container').addClass('wideCompare');
		newWidth = 680;
		$('compareTable').setStyle('width', newWidth)
		}
	else {
		newWidth = 510
		$('compareTable').setStyle('width', newWidth)
		}
	var coords = $('compareTable').getCoordinates();
	$('mainColumn').setStyles({height:coords['height']+100});
}
// ---------------------------------------------------------------------- newsAccordion
function setNewsAccordion(){
	var newsAccordion = new Accordion('h4.atStartTS', 'div.atStartTS',	{
		show: 0,
		opacity: false,
		alwaysHide: true,
		onActive: function(toggler, element){
			toggler.className = "lb active"
			element.setStyle('display', 'block');
		},
		onBackground: function(toggler, element){
			toggler.className = 'lb nonActive'
		}
	}, $('newsAccordion'));
}

// ---------------------------------------------------------------------- Refine pulldown
function togglePulldown(id) {
  var element = $(id);
  if(element.style.display == 'block')
    element.style.display = 'none';
  else
    element.style.display = 'block';
}


// ---------------------------------------------------------------------- Show image overlay
function showLargeImage(imagePath){
	Lightbox.show(imagePath);
	}
// ---------------------------------------------------------------------- Main nav

function hideAllNewsNav(){
	var NewsNav0 = new Fx.Slide('newsNav0');
	NewsNav0.toggle();
}


function setNewsNav(openItem, display){
	var accordion = new Accordion('div.atStart', 'ul.atStart',
	{
		show: openItem,
		display: false,
		alwaysHide: true,
		opacity: false,
		onActive: function(toggler, element){
			element.setStyle('display', 'block');
			hideAllNewsNav()
		},
		onBackground: function(toggler, element){
		}
	}, $('newsNav'));

	if (display != "")
		accordion.display(display);
}


function setMainNav(openItem, display){
	var accordion = new Accordion('div.atStart', 'ul.atStart',
	{
		show: openItem,
		display: false,
		alwaysHide: true,
		opacity: false,
		onActive: function(toggler, element){
			toggler.className = 'db active'
			element.setStyle('display', 'block');
			hideAllPreviewNav()
		},
		onBackground: function(toggler, element){
			toggler.className = 'db nonActive'
		}
	}, $('mainNav'));

	if (display != "")
		accordion.display(display);
}
// Hides all previewlinks in main navigation
function hideAllPreviewNav(){
	var navPreviewLink0 = new Fx.Slide('navPreviewLink0');
	navPreviewLink0.toggle();
	
	var navPreviewLink1 = new Fx.Slide('navPreviewLink1');
	navPreviewLink1.toggle();
	
	var navPreviewLink2 = new Fx.Slide('navPreviewLink2');
	navPreviewLink2.toggle();

	try {
		for (i=3;i<20;i++) {
			var navPreviewLink = new Fx.Slide('navPreviewLink' + i);
			navPreviewLink.toggle();
		}
	} catch (err) {

	}
}
// ---------------------------------------------------------------------- Home special slider
function setHomeSpecialSlider(){
	var homeSpecialSlides = new iCarousel("homeSpecialSlidesContainer", {
		idPrevious: "slidePrev",
		idNext: "slideNext",
		idToggle: "undefined",
		item: {
			klass: "slide",
			size: 510
		},
		animation: {
		rotate: {
		type: "auto",
		interval: 5000
		},
		type: "scroll",
		duration: 1000,
		amount:1
	}
});
$("slide0").addEvent("click", function(event){new Event(event).stop();homeSpecialSlides.goTo(0); $clear(homeSpecialSlides.timer)});  
$("slide1").addEvent("click", function(event){new Event(event).stop();homeSpecialSlides.goTo(1); $clear(homeSpecialSlides.timer)});  
$("slide2").addEvent("click", function(event){new Event(event).stop();homeSpecialSlides.goTo(2); $clear(homeSpecialSlides.timer)});  
$("slide3").addEvent("click", function(event){new Event(event).stop();homeSpecialSlides.goTo(3); $clear(homeSpecialSlides.timer)});  
}
// ---------------------------------------------------------------------- Product images
function setProductImages(){
	var myGallery = new gallery($('productImages'), {
		timed: true
	});
}
// ---------------------------------------------------------------------- Tabs
function showTabs(openTab) {
	var tabs = new mootabs("tabsContainer", {
		width: "510px",
		changeTransition: "none",
		mouseOverClass: "over",
		activateOnLoad:	openTab
	});
};

// ---------------------------------------------------------------------- Stepper for order button
function numericStepper(textFieldName, type, textFieldNameBottom){// adds or subtracts 1 to textfield value
	if(textFieldNameBottom == undefined){
		var textFieldIdBottom = "";		
	}
	else {
		var textFieldIdBottom = $(textFieldNameBottom);
	}
	var textFieldId = $(textFieldName);
	var textFieldValue = $(textFieldName).value;
	//
	if(textFieldId.value.match(/^[0-9]+$/)){// input is a number
		if (type == "plus"){// add 1
			textFieldId.value = parseInt(textFieldValue) + 1
				textFieldIdBottom.value = parseInt(textFieldValue) + 1
		}
		else if (type == "minus"){
			if (textFieldId.value <= 1 || textFieldIdBottom.value <= 1){// don't go lower then 1
				textFieldId.value = 1
					textFieldIdBottom.value = 1
			}
			else{// subtract 1
				textFieldId.value = parseInt(textFieldValue) - 1
					textFieldIdBottom.value = parseInt(textFieldValue) - 1
			}
		}
	}
	else{// input is not a number, set to 0
		textFieldId.value = 1
			textFieldIdBottom.value = 1
	}
}
function validateAmount(textFieldName){
	var textFieldId = $(textFieldName);
	if(textFieldId.value.match(/^[0-9]+$/)){
		return true;
	}
	else {
		textFieldId.value = 1
		return false;
	}
}
// ---------------------------------------------------------------------- show Full Description
function activateFullDescription(){
	var fullDescriptionSlide = new Fx.Slide('fullDescription');
	fullDescriptionSlide.hide();
	
	$('fullDescriptionShow').addEvent('click', function(e){
		e = new Event(e);
		fullDescriptionSlide.slideIn();
		$('fullDescriptionShow').style.display = 'none';
		$('fullDescriptionHide').style.display = 'block';
		e.stop();
	});
	$('fullDescriptionHide').addEvent('click', function(e){
		e = new Event(e);
		fullDescriptionSlide.slideOut();
		$('fullDescriptionShow').style.display = 'block';
		$('fullDescriptionHide').style.display = 'none';
		e.stop();
	});
}

// ---------------------------------------------------------------------- Toggle Account Detail
function hideAccountDetail(slideName){
	var accountDetail = new Fx.Slide(slideName);
	$(slideName).style.display = 'none';
}
function toggleAccountDetail(slideName){
	var accountDetail = new Fx.Slide(slideName);
	if ($(slideName).style.display == 'none'){
		$(slideName).style.display = 'block';
	}
	else{
		$(slideName).style.display = 'none';
	}

}

// ---------------------------------------------------------------------- Clears searchform and changes text color
function checkEntry(o,dTxt){
	if (!o.defTxt){
		o.defTxt = dTxt;
		o.onblur = function (){
			trimField(this);
			with (this){
				if (value == '' || value == defTxt){
					value = defTxt;
					o.style.color = '#a5acb2';
				}
			}
		}
	}
	if (o.value == o.defTxt){
		o.value = '';
		o.style.color = '#202b60';
	}
}
function trimField (o){
	var v = o.value.replace(/^ +| +$/g,'');
	o.value = v;
}
// ---------------------------------------------------------------------- Mouse-over images
function createMouseOvers(){
	var p = 0, d = document.images;
	prelImgs = new Array();
	for (var i = 0; i < d.length; i++){
		var o = d[i];
		if (o.src.indexOf('_out') != -1){
			var s = o.src, l = s.length, e = s.substring(l-4,l);
			o.outSrc = s;
			o.overSrc = s.substring(0,l-8)+'_over'+e;
			o.onmouseover = function(){this.src = this.overSrc;}
			o.onmouseout = function(){this.src = this.outSrc;}
			prelImgs[p] = new Image();
			prelImgs[p].src = o.overSrc;
			p++;
		}
	}
}

// ---------------------------------------------------------------------- Overlay position
function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
 return [scrOfY];
}


// ---------------------------------------------------------------------- Overlay HP trade in
function openOverlayHP(HPID, price){
	partnerID = 1181 // Central Point
	
	var myFx = new Fx.Style($('overlayHPTradeIn'), 'opacity').start(0,1);
	var myFx = new Fx.Style($('overlayHPTradeInBack'), 'opacity').start(0,0.8);
	var myFx = new Fx.Style($('overlayHPTradeInContent'), 'opacity').start(0,1);

	$('overlayHPTradeInBack').style.marginTop = getScrollXY() + 'px';
	$('overlayHPTradeInContent').style.top = getScrollXY() + 'px';
	
	window.onresize = function(){
	  $('overlayHPTradeInBack').style.marginTop = getScrollXY() + 'px';
	  $('overlayHPTradeInContent').style.top = getScrollXY() + 'px';
	}
	window.onscroll = function(){
	  $('overlayHPTradeInBack').style.marginTop = getScrollXY() + 'px';
	  $('overlayHPTradeInContent').style.top = getScrollXY() + 'px';
	}
	
	if(price == ''){
		if(partnerID == ''){
			$('HPFrame').src = 'http://www.inruil.hp3.nl/Default.aspx?HPProductNumber='+HPID
		}
		else{
			$('HPFrame').src = 'http://www.inruil.hp3.nl/Default.aspx?HPProductNumber='+HPID+'&PartnerID='+partnerID
		}
	}
	else{
		if(partnerID == ''){
			$('HPFrame').src = 'http://www.inruil.hp3.nl/Default.aspx?HPProductNumber='+HPID+'&Price='+price
		}
		else{
			$('HPFrame').src = 'http://www.inruil.hp3.nl/Default.aspx?HPProductNumber='+HPID+'&Price='+price+'&PartnerID='+partnerID
		}
	}
}
function closeOverlayHP(){
	var myFx = new Fx.Style($('overlayHPTradeIn'), 'opacity').start(1,0);
	var myFx = new Fx.Style($('overlayHPTradeInBack'), 'opacity').start(0.8,0);
	var myFx = new Fx.Style($('overlayHPTradeInContent'), 'opacity').start(1,0);
}


// ---------------------------------------------------------------------- Overlay Stock reminder
function openOverlayStockReminder(vendor, prodid){
	var myFx = new Fx.Style($('overlayStockReminder'), 'opacity').start(0,1);
	var myFx = new Fx.Style($('overlayStockReminderBack'), 'opacity').start(0,0.8);
	var myFx = new Fx.Style($('overlayStockReminderContent'), 'opacity').start(0,1);
	
  $('overlayStockReminderBack').style.marginTop = getScrollXY() + 'px';
	$('overlayStockReminderContent').style.top = getScrollXY() + 'px';

	window.onresize = function(){
	  $('overlayStockReminderBack').style.marginTop = getScrollXY() + 'px';
	  $('overlayStockReminderContent').style.top = getScrollXY() + 'px';
	}
	window.onscroll = function(){
	  $('overlayStockReminderBack').style.marginTop = getScrollXY() + 'px';
	  $('overlayStockReminderContent').style.top = getScrollXY() + 'px';
	}
	
	var url  = '/ajax.php?request=stockReminder&vendor='+encodeURIComponent(vendor)+'&prodid='+encodeURIComponent(prodid);

 	new Ajax(url, {
		method: 'get',
		update: $('stockReminderFormContainer')
	}).request();

}

function closeOverlayStockReminder(){
	var myFx = new Fx.Style($('overlayStockReminder'), 'opacity').start(1,0);
	var myFx = new Fx.Style($('overlayStockReminderBack'), 'opacity').start(0.8,0);
	var myFx = new Fx.Style($('overlayStockReminderContent'), 'opacity').start(1,0);
}

function performStockReminder(name,email,mob,prodid,vendor){
  var url      = '/ajax.php?request=stockReminder&performRequest=1';
  var proceed  = true;

	var reg = /^[a-z0-9._%-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i;
	var msg = "";
	
	if (reg.test(email) == false) {
		proceed = 'false';
		msg = "U heeft geen (correct) email-adres ingevoerd";
	}
	
	if (name == '') {
		proceed = false;
	}
	if (mob == 'Mobiel tel.') {
		mob = '';
	}
	url += '&stockFormNaam='+name+'&stockFormEmail='+email+'&stockFormMobile='+mob+'&vendor='+vendor+'&prodid='+encodeURIComponent(prodid);

	if (proceed == true) {
		alert ('Bedankt voor het inschrijven van de voorraadherrinering. U ontvangt een email/sms van ons zodra het product weer op voorraad is.');
		new Ajax(url, {
			method:       'get'
		}).request();
	} else {
		if (msg != "") {
			alert (msg)
		}
	}
}

function performOverlayStockReminder(obj){
  obj.disabled = true;
  var url      = '/ajax.php?request=stockReminder';
  var form     = $('stockReminderForm');
  var proceed  = true;

  for (i=0; form.elements[i]; i++) {
   if (form.elements[i].name && form.elements[i].value){
     url += '&' + form.elements[i].name + '=' + escape(form.elements[i].value);
   }

    if (form.elements[i].className.indexOf("fValidate['required']") > -1) {
      if (form.elements[i].value.length > 0)  {
        form.elements[i].style["border"] = "#0c0";
      } else {
        form.elements[i].style["border"] = "#e70000 1px solid";
        proceed  = false;
      }
		}
	}

	if (proceed) {
		new Ajax(url, {
			method:       'get',
			update:       $('stockReminderFormContainer')
		}).request();
	} else {
	  obj.disabled = false;
	}
}

// ---------------------------------------------------------------------- Overlay position
function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
					//Netscape compliant
					scrOfY = window.pageYOffset;
					scrOfX = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
					//DOM compliant
					scrOfY = document.body.scrollTop;
					scrOfX = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
					//IE6 standards compliant mode
					scrOfY = document.documentElement.scrollTop;
					scrOfX = document.documentElement.scrollLeft;
	}
	return [scrOfY];
}

// ---------------------------------------------------------------------- Check YouTube URL
function validateYouTube(){
   //check for valid youtube address
  if ($('submitYouTubeForm').submitYouTubeURL.value.match('http://') == 'http://' && $('submitYouTubeForm').submitYouTubeURL.value.match('.youtube.com/watch') == '.youtube.com/watch'){
 $('submitYouTubeForm').imageCheckYouTube.src = '/images/icons/specstrue.gif';
   // alert("goed zo");
 return true
  } else {
 $('submitYouTubeForm').imageCheckYouTube.src = '/images/icons/specsfalse.gif';
    $('submitYouTubeForm').submitYouTubeURL.value = '';
    $('submitYouTubeForm').submitYouTubeURL.focus();
 //alert("niet goed");
    return false
  }
}

// ---------------------------------------------------------------------- refresh captcha
function refreshCaptcha(){
	var url    = '/ajax.php?request=captcha';

	document.getElementById('captcha_block').innerHTML = "";

	time    =       new Date();
	url += '&hash='+ time.getTime();
	url += Math.random();

	new Ajax(url, {method: 'get', 
									update: $('captcha_block')}).request()
}


// ---------------------------------------------------------------------- Check user Youtube
function checkUserYoutube(obj){

	var url = '/ajax.php?request=getYoutube&mode=user';

	obj.disabled = true;
	var form     = document.getElementById('submitYouTubeForm');
	var proceed  = true;

	var reg_email = /^[a-z0-9._%-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i;

	for (i=0; form.elements[i]; i++) {
		if (form.elements[i].name && form.elements[i].value){
			url += '&' + form.elements[i].name + '=' + escape(form.elements[i].value);
		}

		if (form.elements[i].className.indexOf("fValidate['email']") > -1 && form.elements[i].value.length > 0) {
			var check_mail = reg_email.test(form.elements[i].value);
			if (!check_mail) {
				proceed = false;
				form.elements[i].style["border"] = "#e70000 1px solid";
//			  document.getElementById('userEmailError').style.visibility = 'visible';
			}else{
				form.elements[i].style["border"] = "rgb(219, 223, 230) 1px solid";
//				document.getElementById('userEmailError').style.visibility = 'hidden';
			}
		}else{
			form.elements[i].style["border"] = "rgb(219, 223, 230) 1px solid";
//			document.getElementById('userEmailError').style.visibility = 'hidden';
		}

		if (form.elements[i].className.indexOf("fValidate['required']") > -1) {
			if (form.elements[i].value.length > 0)  {
				form.elements[i].style["border"] = "rgb(219, 223, 230) 1px solid";
			} else {
				form.elements[i].style["border"] = "#e70000 1px solid";
				proceed  = false;
			}
		}

	}
	if (proceed) {
		new Ajax(url, {
			method: 'get',
			onComplete: function(){
/*				if (this.response.text.indexOf('success') > -1){
					alert('Uw YouTube video is nu gekoppeld aan het product. Bezoekers kunnen uw video nu via onze site bekijken.');
					document.getElementById('video_url').value = '';
					document.getElementById('user_email').value = '';
				}else{
					alert('Helaas is er iets mis gegaan. Controleer de rode velden en probeer opnieuw.');
				}*/
//				setTimeout("refreshCaptcha()",1000);
				obj.disabled = false;
			},
			update: $('submitYouTubeFormContainer')
		}).request();
	}else{
		obj.disabled = false;	  
	}

}

function setIframeSrc(iframeNode, src) {
	alert(getIframeDocument(iframeNode).location);
	alert(getIframeDocument(iframeNode));
  getIframeDocument(iframeNode).location.replace(src)
	}

function getIframeDocument(iframeNode) {
  if (iframeNode.contentDocument) return iframeNode.contentDocument
	  if (iframeNode.contentWindow) return iframeNode.contentWindow.document
		  return iframeNode.document
			}
// ---------------------------------------------------------------------- Overlay Password reminder
function openOverlayPasswordReminder(e_mail){
	var myFx = new Fx.Style($('overlayPasswordReminder'), 'opacity').start(0,1);
	var myFx = new Fx.Style($('overlayPasswordReminderBack'), 'opacity').start(0,0.8);
	var myFx = new Fx.Style($('overlayPasswordReminderContent'), 'opacity').start(0,1);

	var url  = '/ajax.php?request=passwordReminder';
	try {
		if (e_mail.length > 1) {
			url += '&passwordFormEmail='+e_mail+'&letter=send';
		}
	} catch (err) {}	

	new Ajax(url, {
		method: 'get',
		update: $('passwordReminderFormContainer')
	}).request();

}

function closeOverlayPasswordReminder(){
	var myFx = new Fx.Style($('overlayPasswordReminder'), 'opacity').start(1,0);
	var myFx = new Fx.Style($('overlayPasswordReminderBack'), 'opacity').start(0.8,0);
	var myFx = new Fx.Style($('overlayPasswordReminderContent'), 'opacity').start(1,0);
}

function performOverlayPasswordReminder(obj){
	obj.disabled = true;
	var url      = '/ajax.php?request=passwordReminder';
	var form     = $('passwordReminderForm');
	var proceed  = true;

	for (i=0; form.elements[i]; i++) {
		if (form.elements[i].name && form.elements[i].value){
			url += '&' + form.elements[i].name + '=' + escape(form.elements[i].value);
		}
	
		if (form.elements[i].className.indexOf("fValidate['required']") > -1) {
			if (form.elements[i].value.length > 0)  {
				form.elements[i].style["border"] = "#0c0";
			} else {
				form.elements[i].style["border"] = "#e70000 1px solid";
				proceed  = false;
			}
		}
	}

	if (proceed) {
		new Ajax(url, {
			method:       'get',
			update:       $('passwordReminderFormContainer')
		}).request();
	} else {
		obj.disabled = false;
	}	
}


// ---------------------------------------------------------------------- Overlay NewsLetter
function openOverlayNexway(Ordernumber, Volgnr){
  var myFx = new Fx.Style($('overlayNexway'), 'opacity').start(0,1);
  var myFx = new Fx.Style($('overlayNexwayBack'), 'opacity').start(0,0.8);
  var myFx = new Fx.Style($('overlayNexwayContent'), 'opacity').start(0,1);
  var url  = '/ajax.php?request=clientNexwayDownload&ordernumber='+Ordernumber+'&volgnr='+Volgnr;

	$('overlayNexwayBack').style.marginTop = getScrollXY() + 'px';
	$('overlayNexwayContent').style.top = getScrollXY() + 'px';

	window.onresize = function(){
		$('overlayNexwayBack').style.marginTop = getScrollXY() + 'px';
		$('overlayNexwayContent').style.top = getScrollXY() + 'px';
	}
	window.onscroll = function(){
		$('overlayNexwayBack').style.marginTop = getScrollXY() + 'px';
		$('overlayNexwayContent').style.top = getScrollXY() + 'px';
	}


	time    =       new Date();
	url += '&random='+ time.getTime();
	url += Math.random();

  new Ajax(url, {
    method: 'get',
    update: $('NexwayFormContainer')
  }).request();

}

function closeOverlayNexway(){
  var myFx = new Fx.Style($('overlayNexway'), 'opacity').start(1,0);
  var myFx = new Fx.Style($('overlayNexwayBack'), 'opacity').start(0.8,0);
  var myFx = new Fx.Style($('overlayNexwayContent'), 'opacity').start(1,0);
}
// ---------------------------------------------------------------------- Overlay NewsLetter
function openOverlayNewsLetter(){
  var myFx = new Fx.Style($('overlayNewsLetter'), 'opacity').start(0,1);
  var myFx = new Fx.Style($('overlayNewsLetterBack'), 'opacity').start(0,0.8);
  var myFx = new Fx.Style($('overlayNewsLetterContent'), 'opacity').start(0,1);
  var url  = '/ajax.php?request=newsLetter';

  new Ajax(url, {
    method: 'get',
    update: $('newsLetterFormContainer')
  }).request();

}

function closeOverlayNewsLetter(){
  var myFx = new Fx.Style($('overlayNewsLetter'), 'opacity').start(1,0);
  var myFx = new Fx.Style($('overlayNewsLetterBack'), 'opacity').start(0.8,0);
  var myFx = new Fx.Style($('overlayNewsLetterContent'), 'opacity').start(1,0);
}

function performOverlayNewsLetter(obj, action){
  obj.disabled = true;
  var url      = '/ajax.php?request=newsLetter';
  var form     = $('newsLetterForm');
  var proceed  = true;

  for (i=0; form.elements[i]; i++) {
    if (form.elements[i].name && form.elements[i].value){
      url += '&' + form.elements[i].name + '=' + escape(form.elements[i].value);
    }

    if (form.elements[i].className.indexOf("fValidate['required']") > -1) {
      if (form.elements[i].value.length > 0)  {
        form.elements[i].style["border"] = "#0c0";
      } else {
        form.elements[i].style["border"] = "#e70000 1px solid";
        proceed  = false;
      }
    }
  }

  if (proceed) {
		url = url + '&action=' + action;
    new Ajax(url, {
      method:       'get',
      update:       $('newsLetterFormContainer')
    }).request();
  } else {
    obj.disabled = false;
  }
}

// ---------------------------------------------------------------------- Overlay Client logo
function openOverlayClientLogo(){
	var myFx = new Fx.Style($('overlayClientLogo'), 'opacity').start(0,1);
	var myFx = new Fx.Style($('overlayClientLogoBack'), 'opacity').start(0,0.8);
	var myFx = new Fx.Style($('overlayClientLogoContent'), 'opacity').start(0,1);

}

function closeOverlayClientLogo(){
	var myFx = new Fx.Style($('overlayClientLogo'), 'opacity').start(1,0);
	var myFx = new Fx.Style($('overlayClientLogoBack'), 'opacity').start(0.8,0);
	var myFx = new Fx.Style($('overlayClientLogoContent'), 'opacity').start(1,0);

	$('clientLogo').src = '/clientLogo.php'+ '#' + Math.random();
}



// --------------------------------------------------------------------- External configurators

function openOverlayExternalConfigurator(url){

	var myFx = new Fx.Style($('overlayExternalConfigurator'), 'opacity').start(0,1);
	var myFx = new Fx.Style($('overlayExternalConfiguratorBack'), 'opacity').start(0,0.8);
	var myFx = new Fx.Style($('overlayExternalConfiguratorContent'), 'opacity').start(0,1);

	$('overlayExternalConfiguratorFrame').src = url;
}

function closeOverlayExternalConfigurator(){

  var myFx = new Fx.Style($('overlayExternalConfigurator'), 'opacity').start(1,0);
  var myFx = new Fx.Style($('overlayExternalConfiguratorBack'), 'opacity').start(0.8,0);
  var myFx = new Fx.Style($('overlayExternalConfiguratorContent'), 'opacity').start(1,0);

}

// ---------------------------------------------------------------------- Overlay check stock

function openOverlayStockCheck(vendor, prodid){
	var myFx = new Fx.Style($('overlayStockCheck'), 'opacity').start(0,1);
	var myFx = new Fx.Style($('overlayStockCheckBack'), 'opacity').start(0,0.8);
	var myFx = new Fx.Style($('overlayStockCheckContent'), 'opacity').start(0,1);
	
	$('overlayStockCheckBack').style.marginTop = getScrollXY() + 'px';
	$('overlayStockCheckContent').style.top = getScrollXY() + 'px';

	window.onresize = function(){
	  $('overlayStockCheckBack').style.marginTop = getScrollXY() + 'px';
	  $('overlayStockCheckContent').style.top = getScrollXY() + 'px';
	}
	window.onscroll = function(){
	  $('overlayStockCheckBack').style.marginTop = getScrollXY() + 'px';
	  $('overlayStockCheckContent').style.top = getScrollXY() + 'px';
	}
	
	var url  = '/ajax.php?request=price&htmlResponse=true&vendor=' + vendor + '&prodid=' + prodid;
 	new Ajax(url, {
		method: 'get',
		update: $('stockCheckFormContainer')
	}).request();

}
function closeOverlayStockCheck(){
	var myFx = new Fx.Style($('overlayStockCheck'), 'opacity').start(1,0);
	var myFx = new Fx.Style($('overlayStockCheckBack'), 'opacity').start(0.8,0);
	var myFx = new Fx.Style($('overlayStockCheckContent'), 'opacity').start(1,0);
}

// ---------------------------------------------------------------------- Overlay add to wishlist

function openOverlayAddToWishlist(vendor, prodid){

	var myFx = new Fx.Style($('overlayAddToWishlist'), 'opacity').start(0,1);
  var myFx = new Fx.Style($('overlayAddToWishlistBack'), 'opacity').start(0,0.8);
  var myFx = new Fx.Style($('overlayAddToWishlistContent'), 'opacity').start(0,1);
  var url  = '/ajax.php?request=wishlist&vendor=' + escape(vendor) + '&prodid=' + escape(prodid) + '&nocache=' + Math.random();

  new Ajax(url, {
  	method: 'get',
		update: $('addToWishlistContainer')
	}).request();
}

function closeOverlayAddToWishlist(){

	var myFx = new Fx.Style($('overlayAddToWishlist'), 'opacity').start(1,0);
	var myFx = new Fx.Style($('overlayAddToWishlistBack'), 'opacity').start(0.8,0);
	var myFx = new Fx.Style($('overlayAddToWishlistContent'), 'opacity').start(1,0);

}

// --------------------------------------------------------------------- Overlay Submit YouTube
function submitYouTube(vendor,prod_id){
	var myFx = new Fx.Style($('overlaySubmitYouTube'), 'opacity').start(0,1);
	var myFx = new Fx.Style($('overlaySubmitYouTubeBack'), 'opacity').start(0,0.8);
	var myFx = new Fx.Style($('overlaySubmitYouTubeContent'), 'opacity').start(0,1);

	$('overlaySubmitYouTubeBack').style.marginTop = getScrollXY() + 'px';
	$('overlaySubmitYouTubeContent').style.top = getScrollXY() + 'px';

	window.onresize = function(){
					$('overlaySubmitYouTubeBack').style.marginTop = getScrollXY() + 'px';
					$('overlaySubmitYouTubeContent').style.top = getScrollXY() + 'px';
	}
	window.onscroll = function(){
					$('overlaySubmitYouTubeBack').style.marginTop = getScrollXY() + 'px';
					$('overlaySubmitYouTubeContent').style.top = getScrollXY() + 'px';
	}

//	var url = 'ajax_response_submit_youtube.html';
	var url = '/ajax.php?request=getYoutube&mode=user&vendor='+escape(vendor)+'&prod_id='+escape(prod_id);

	new Ajax(url, {
		method: 'get',
		update: $('SubmitYouTubeContainer')
	}).request();

}
function closeOverlaySubmitYouTube(){
				var myFx = new Fx.Style($('overlaySubmitYouTube'), 'opacity').start(1,0);
				var myFx = new Fx.Style($('overlaySubmitYouTubeBack'), 'opacity').start(0.8,0);
				var myFx = new Fx.Style($('overlaySubmitYouTubeContent'), 'opacity').start(1,0);
}

// ---------------------------------------------------------------------- Overlay Describe request

function openOverlayRequest(vendor, prodid){
	var myFx = new Fx.Style($('overlayRequest'), 'opacity').start(0,1);
	var myFx = new Fx.Style($('overlayRequestBack'), 'opacity').start(0,0.8);
	var myFx = new Fx.Style($('overlayRequestContent'), 'opacity').start(0,1);
	var url = '/ajax.php?request=reportDescribe&vendor=' + vendor + '&prodid=' + prodid;

	new Ajax(url, {
		method: 'get',
		update: $('requestFormContainer')
	}).request();
}

function closeOverlayRequest(){
  var myFx = new Fx.Style($('overlayRequest'), 'opacity').start(1,0);
  var myFx = new Fx.Style($('overlayRequestBack'), 'opacity').start(0.8,0);
  var myFx = new Fx.Style($('overlayRequestContent'), 'opacity').start(1,0);
}

function performOverlayRequest(obj){
  obj.disabled = true;
  var url      = '/ajax.php?request=reportDescribe';
  var form     = $('requestForm');
  var proceed  = true;

  for (i=0; form.elements[i]; i++) {
		if (form.elements[i].name && form.elements[i].value){
			url += '&' + form.elements[i].name + '=' + escape(form.elements[i].value);
		}

		if (form.elements[i].className.indexOf("fValidate['required']") > -1) {
			if (form.elements[i].value.length > 0)  {
				form.elements[i].style["border"] = "#0c0";
			} else {
			  form.elements[i].style["border"] = "#e70000 1px solid";
			  proceed  = false;
			}
		}
 	}

	if (proceed) {
		new Ajax(url, {
			method:       'get',
			update:       $('requestFormContainer')
		}).request();
	} else {
	  obj.disabled = false;
	}
}
																																																					
// ---------------------------------------------------------------------- Overlay editorial
function openOverlayEditorial(productID){
	var myFx = new Fx.Style($('overlayEditorial'), 'opacity').start(0,1);
	var myFx = new Fx.Style($('overlayEditorialBack'), 'opacity').start(0,0.8);
	var myFx = new Fx.Style($('overlayEditorialContent'), 'opacity').start(0,1);
	
	$('overlayEditorialBack').style.marginTop = getScrollXY() + 'px';
	$('overlayEditorialContent').style.top = getScrollXY() + 'px';

	window.onresize = function(){
	  $('overlayEditorialBack').style.marginTop = getScrollXY() + 'px';
	  $('overlayEditorialContent').style.top = getScrollXY() + 'px';
	}
	window.onscroll = function(){
	  $('overlayEditorialBack').style.marginTop = getScrollXY() + 'px';
	  $('overlayEditorialContent').style.top = getScrollXY() + 'px';
	}
		
	var url = '/ajax.php?request=reportError&productID=' + productID;
 
 	new Ajax(url, {
		method: 'get',
		update: $('editorialFormContainer')
	}).request();

}

function closeOverlayEditorial(){
	var myFx = new Fx.Style($('overlayEditorial'), 'opacity').start(1,0);
	var myFx = new Fx.Style($('overlayEditorialBack'), 'opacity').start(0.8,0);
	var myFx = new Fx.Style($('overlayEditorialContent'), 'opacity').start(1,0);
}


function performOverlayEditorial(obj){
  obj.disabled = true;
  var url      = '/ajax.php?request=reportError';
  var form     = $('editorialForm');
	var proceed  = true;
	
  for (i=0; form.elements[i]; i++) {
	  if (form.elements[i].name && form.elements[i].value){
		  url += '&' + form.elements[i].name + '=' + escape(form.elements[i].value);
		}

		if (form.elements[i].className.indexOf("fValidate['required']") > -1) {
			if (form.elements[i].value.length > 0)	{
				form.elements[i].style["border"] = "#0c0";
			} else {
				form.elements[i].style["border"] = "#e70000 1px solid";
				proceed  = false;
			}
		} 
	}

	if (proceed) {
		new Ajax(url, {
			method: 			'get',
			update: 			$('editorialFormContainer')
		}).request();
	} else {
		obj.disabled = false;
	} 
}

// ---------------------------------------------------------------------- Overlay send-a-friend

function openOverlaySendFriend(vendor, prod_id){
  var myFx = new Fx.Style($('overlaySendFriend'), 'opacity').start(0,1);
	var myFx = new Fx.Style($('overlaySendFriendBack'), 'opacity').start(0,0.8);
	var myFx = new Fx.Style($('overlaySendFriendContent'), 'opacity').start(0,1);
	
	$('overlaySendFriendBack').style.marginTop = getScrollXY() + 'px';
	$('overlaySendFriendContent').style.top = getScrollXY() + 'px';

	window.onresize = function(){
	  $('overlaySendFriendBack').style.marginTop = getScrollXY() + 'px';
	  $('overlaySendFriendContent').style.top = getScrollXY() + 'px';
	}
	window.onscroll = function(){
	  $('overlaySendFriendBack').style.marginTop = getScrollXY() + 'px';
	  $('overlaySendFriendContent').style.top = getScrollXY() + 'px';
	}

	var url = '/ajax.php?request=sendToFriend&vendor=' + escape(vendor) + '&prod_id=' + escape(prod_id);
	url += '&random='+Math.random();

	new Ajax(url, {
	  method: 'get',
	  update: $('sendFriendFormContainer')
	}).request();
}

function performOverlaySendFriend(obj) {
  obj.disabled = true;
  var url      = '/ajax.php?request=sendToFriend';
  var form     = $('sendFriendForm');
	var proceed  = true;

  for (i=0; form.elements[i]; i++) {
	  if (form.elements[i].name && form.elements[i].value){
		  url += '&' + form.elements[i].name + '=' + escape(form.elements[i].value);
		}
		if (form.elements[i].className.indexOf("fValidate['required']") > -1) {
			if (form.elements[i].value.length > 0)	{
				form.elements[i].style["border"] = "#0c0";
			} else {
				form.elements[i].style["border"] = "#e70000 1px solid";
				proceed  = false;
			}
		} 
		if(form.elements[i].className.indexOf("fValidate['agree']") > -1){
			if(form.elements[i].checked == true){
				document.getElementById(form.elements[i].id+'Label').style["border"] = "#0c0";
			} else {
				document.getElementById(form.elements[i].id+'Label').style["border"] = "#e70000 1px solid";
				proceed  = false;

			}
		}

	}
	if (proceed) {
		new Ajax(url, {
			method: 			'get',
			update: 			$('sendFriendFormContainer')
		}).request();
	} else {
		obj.disabled = false;
	} 
}

function closeOverlaySendFriend(){
	var myFx = new Fx.Style($('overlaySendFriend'), 'opacity').start(1,0);
	var myFx = new Fx.Style($('overlaySendFriendBack'), 'opacity').start(0.8,0);
	var myFx = new Fx.Style($('overlaySendFriendContent'), 'opacity').start(1,0);
}
// ---------------------------------------------------------------------- Overlay mini product
function openMiniProduct(productID,prodlevid,supplier){
	var myFx = new Fx.Style($('overlayMiniProduct'), 'opacity').start(0,1);
 	var myFx = new Fx.Style($('overlayMiniProductBack'), 'opacity').start(0,0.8);
 	var myFx = new Fx.Style($('overlayMiniProductContent'), 'opacity').start(0,1);

 	$('overlayMiniProductBack').style.marginTop = getScrollXY() + 'px';
 	$('overlayMiniProductContent').style.top = getScrollXY() + 'px';

 	window.onresize = function(){
   	$('overlayMiniProductBack').style.marginTop = getScrollXY() + 'px';
   	$('overlayMiniProductContent').style.top = getScrollXY() + 'px';
 	}
 	window.onscroll = function(){
  	$('overlayMiniProductBack').style.marginTop = getScrollXY() + 'px';
   	$('overlayMiniProductContent').style.top = getScrollXY() + 'px';
 	}

	var url = '/ajax.php?request=miniProduct&productID=' + productID+'&prodlevid='+prodlevid+'&supplier='+supplier;

// 	url = 'iframe_response_miniproduct.html?productID='+productID;

	$('miniProductFrame').src=url;

/*  new Ajax(url, {
   	method: 'get',
//		update: $('miniProductFormContainer')
   	update: $('miniProductFrame')
 	}).request();*/
}
function closeMiniProduct(){
 	var myFx = new Fx.Style($('overlayMiniProduct'), 'opacity').start(1,0);
 	var myFx = new Fx.Style($('overlayMiniProductBack'), 'opacity').start(0.8,0);
 	var myFx = new Fx.Style($('overlayMiniProductContent'), 'opacity').start(1,0);
}
function selectRadio(productID){
 	$(productID).checked = true;
}
// ---------------------------------------------------------------------- Overlay YouTube
function openYouTube(YouTubeID){
 	var myFx = new Fx.Style($('overlayYouTube'), 'opacity').start(0,1);
 	var myFx = new Fx.Style($('overlayYouTubeBack'), 'opacity').start(0,0.8);
 	var myFx = new Fx.Style($('overlayYouTubeContent'), 'opacity').start(0,1);

 	$('overlayYouTubeBack').style.marginTop = getScrollXY() + 'px';
 	$('overlayYouTubeContent').style.top = getScrollXY() + 'px';

 	window.onresize = function(){
   	$('overlayYouTubeBack').style.marginTop = getScrollXY() + 'px';
   	$('overlayYouTubeContent').style.top = getScrollXY() + 'px';
 	}
 	window.onscroll = function(){
   	$('overlayYouTubeBack').style.marginTop = getScrollXY() + 'px';
   	$('overlayYouTubeContent').style.top = getScrollXY() + 'px';
 	}

	var url = '/ajax.php?request=getYoutube&YouTubeID='+YouTubeID; 	

  new Ajax(url, {
   	method: 'get',
   	update: $('YouTubeContainer'),
		onComplete: function(){
			showSwfYoutube(YouTubeID);
		}
 	}).request();

}
function closeOverlayYouTube(){
 	var myFx = new Fx.Style($('overlayYouTube'), 'opacity').start(1,0);
 	var myFx = new Fx.Style($('overlayYouTubeBack'), 'opacity').start(0.8,0);
 	var myFx = new Fx.Style($('overlayYouTubeContent'), 'opacity').start(1,0);

	var url = '/ajax.php?request=getYoutube'; 	

  new Ajax(url, {
   	method: 'get',
   	update: $('YouTubeContainer')
 	}).request();

}
// ----------------------------------------------------------------------
function submitFrontPageForm (form, id) {
	form.quant1.value	=	document.getElementById(id).value;
	form.submit();
}
// ---------------------------------------------------------------------- Show wishlist note
function showNote(id) {
	$('noteLink'+id).style.display = 'none';
 	$('noteField'+id).style.display = 'block';
 	$('wishNote'+id).focus();
}
function showNote2(id) {
  $('noteLink'+id).style.display = 'block';
  $('noteField'+id).style.display = 'none';
}
// ---------------------------------------------------------------------- Set checkboxes refine brands
function setRefineAllBrands(state, auto){
//	field = $$('#pulldownBrands input')
	if (document.getElementById('vendors_count')){
  	lengthvar = document.getElementById('vendors_count').value;
	  if (state && auto) {
  	  flag = false;
    	for (i = 1; i <= lengthvar; i++){
      	ref_id = 'refineBrandII' + i;
	      obj = document.getElementById(ref_id);
  	    if (obj){
    	    if (obj.checked) {
      	    flag = true;
        	  break;
	        }
  	    }
    	}

			if (flag) {
				$('refineBrandShowAllTrue').setStyle('display','block')
				$('refineBrandShowAllFalse').setStyle('display','none')
				$('refineBrandTrue').checked = false;
				$ES('label', 'pulldownBrands').setStyle('color', '#202b60')
				$ES('label', 'pulldownBrands').setStyle('cursor', 'pointer')
				$('refineBrandFalse').disabled = false
				//$('showRefine').disabled = false
				return;
			}
		}

		for (i = 1; i <=lengthvar; i++){
    	ref_id = 'refineBrandII' + i;
	    obj    = document.getElementById(ref_id);
	    if (obj){
      	obj.checked = state;
    	  obj.disabled = state;
  	  }
	  }

  	if (state==true){
	  	$('refineBrandFalse').checked = true;
  	//  $ES('label', 'pulldownBrands').setStyle('color', '#b6bacf')
	  //  $ES('label', 'pulldownBrands').setStyle('cursor', 'auto')
  	  $('refineBrandShowAllTrue').setStyle('display','none')
	    $('refineBrandShowAllFalse').setStyle('display','block')
    	$('refineBrandShowAllFalse').setStyle('color', '#202b60')
  	  $('refineBrandShowAllFalse').setStyle('cursor', 'pointer')
		}
  	else if (state==false){
	  	$('refineBrandShowAllTrue').setStyle('display','block')
    	$('refineBrandShowAllFalse').setStyle('display','none')
  	  $('refineBrandTrue').checked = false;
	  //  $ES('label', 'pulldownBrands').setStyle('color', '#202b60')
  	//  $ES('label', 'pulldownBrands').setStyle('cursor', 'pointer')
	  }
  	$('refineBrandFalse').disabled = false
		$('showRefine').disabled = false
	}
}
// ---------------------------------------------------------------------- Show image overlay
 
// ---------------------------------------------------------------------- Overlay Turnpage
function openTurnpage(){
  var myFx = new Fx.Style($('overlayTurnpage'), 'opacity').start(0,1);
  var myFx = new Fx.Style($('overlayTurnpageBack'), 'opacity').start(0,0.8);
  var myFx = new Fx.Style($('overlayTurnpageContent'), 'opacity').start(0,1);

  $('overlayTurnpageBack').style.marginTop = getScrollXY() + 'px';
  $('overlayTurnpageContent').style.top = getScrollXY() + 'px';

  window.onresize = function(){
    $('overlayTurnpageBack').style.marginTop = getScrollXY() + 'px';
    $('overlayTurnpageContent').style.top = getScrollXY() + 'px';
  }
  window.onscroll = function(){
    $('overlayTurnpageBack').style.marginTop = getScrollXY() + 'px';
    $('overlayTurnpageContent').style.top = getScrollXY() + 'px';
  }

  $('TurnpageFrame').src = 'https://www.centralpoint.nl/images/tp_licentiegids/alex.html'
}
function closeOverlayTurnpage(){
  var myFx = new Fx.Style($('overlayTurnpage'), 'opacity').start(1,0);
  var myFx = new Fx.Style($('overlayTurnpageBack'), 'opacity').start(0.8,0);
  var myFx = new Fx.Style($('overlayTurnpageContent'), 'opacity').start(1,0);
}

// ----------------------------------------------------------------------
function showMemoryTabs(openTab) {
  var tabs = new mootabs("memoryTabsContainer", {
              width: "510px",
              changeTransition: "none",
              mouseOverClass: "over",
              activateOnLoad: openTab
  });
};
// ---------------------------------------------------------------------- Show image overlay^M
function showSwfYoutube(youtube_key){
	if (youtube_key == '') return;
	var params = { allowScriptAccess: "always" , allowFullScreen: "true"};
	var atts = { id: "myytplayer" };
	swfobject.embedSWF("http://www.youtube.com/v/"+youtube_key+"&enablejsapi=1&playerapiid=ytplayer&autoplay=1&hd=1&fs=1&fmt=18","ytapiplayer", "650", "360", "8", null, null, params, atts);
}
//---------------------------------------------------------------------- Overlay Printer Supplies
function openOverlayPrinterSupplies(vendor,prodid,cnt,type_id){
	var myFx = new Fx.Style($('overlayPrinterSupplies'), 'opacity').start(0,1);
	var myFx = new Fx.Style($('overlayPrinterSuppliesBack'), 'opacity').start(0,0.8);
	var myFx = new Fx.Style($('overlayPrinterSuppliesContent'), 'opacity').start(0,1);

	$('overlayPrinterSuppliesBack').style.marginTop = getScrollXY() + 'px';
	$('overlayPrinterSuppliesContent').style.top = getScrollXY() + 'px';

	window.onresize = function(){
					$('overlayPrinterSuppliesBack').style.marginTop = getScrollXY() + 'px';
					$('overlayPrinterSuppliesContent').style.top = getScrollXY() + 'px';
	}
/*	window.onscroll = function(){
					$('overlayPrinterSuppliesBack').style.marginTop = getScrollXY() + 'px';
					$('overlayPrinterSuppliesContent').style.top = getScrollXY() + 'px';
	}*/
	
	$('overlayPrinterSuppliesContent').style.height	=	((cnt+1)*30+160)+'px';	
	if(type_id==2){
		var url = '/ajax.php?request=printerSupplies&vendor=' + escape(vendor) + '&prodid=' + escape(prodid);
	}else if(type_id==3){
		var url = '/ajax.php?request=compWarranty&vendor=' + escape(vendor) + '&prodid=' + escape(prodid);
	}
	new Ajax(url, {
	    method: 'get',
	    evalScripts: true,
	    update: $('printerSuppliesContainer')
	  }).request();
}

function closeOverlayPrinterSupplies(){
	var myFx = new Fx.Style($('overlayPrinterSupplies'), 'opacity').start(1,0);
	var myFx = new Fx.Style($('overlayPrinterSuppliesBack'), 'opacity').start(0.8,0);
	var myFx = new Fx.Style($('overlayPrinterSuppliesContent'), 'opacity').start(1,0);
}
// ---------------------------------------------------------------------- Stepper for printer supplies
function numericStepperPrinterSupplies(textFieldName, type, textFieldNameBottom){// adds or subtracts 1 to textfield value
  if(textFieldNameBottom == undefined){
    var textFieldIdBottom = "";
  } else {
    var textFieldIdBottom = $(textFieldNameBottom);
	}
	var textFieldId = $(textFieldName);
	var textFieldValue = $(textFieldName).value;
	if(textFieldId.value.match(/^[0-9]+$/)){// input is a number
		if (type == "plus"){// add 1
			textFieldId.value = parseInt(textFieldValue) + 1
			textFieldIdBottom.value = parseInt(textFieldValue) + 1
		}
		else if (type == "minus"){
			if (textFieldId.value <= 0 || textFieldIdBottom.value <= 0){// don't go lower then 1
				textFieldId.value = 0
				textFieldIdBottom.value = 0
			}	else{// subtract 1
				textFieldId.value = parseInt(textFieldValue) - 1
				textFieldIdBottom.value = parseInt(textFieldValue) - 1
			}
		}
	}
	else{// input is not a number, set to 0
		textFieldId.value = 0
		textFieldIdBottom.value = 0
	}
}
// ---------------------------------------------------------------------- Account notes (Slide)
function closeAccountNote(noteID) {
	var mySlide = new Fx.Slide('note'+noteID, {duration: 500});
	mySlide.slideOut();

	var url = '/ajax.php?request=notes&note_id='+escape(noteID);

	new Ajax(url, {
		method: 'get'
	}).request();
}
// ---------------------------------------------------------------------- tagCloudBox better word alignment script
function AlignTagCloud(words)
{
	if(document.getElementById('tagCloudInnerField') == null ) return false;

	if (/Mozilla[\/\s](\d+\.\d+)/.test(navigator.userAgent))
	{
		var rowwidthmax = document.getElementById('tagCloudInnerField').offsetWidth-15;
	} else 
	{
		var rowwidthmax = document.getElementById('tagCloudInnerField').offsetWidth-20;
	}


	var template = new Array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');

	var htmlstr = "<div class=\"clearfloat\"></div>";

	for ( i in words)
	{
		if(!words[i]) continue;

		if(document.getElementById(words[i]['word']))
		{
			if (/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent))
			{
				words[i]['width'] = document.getElementById(words[i]['word']).clientWidth;
			} else 
			{
				words[i]['width'] = document.getElementById(words[i]['word']).offsetWidth;
			}

			words[i]['index'] = words[i]['word'].substr(0,1);
		}

	}

	var link = new Array();
	var width = new Array();
	var indexwords = new Array();

	for( var i=0; i < template.length; i++)	
	{

	indexwords[i] = new Array();
	var rowlen = 0;

		for(j in words)
		{
			if(!words[j]) continue;

			if( words[j]['index'] == template[i] || words[j]['index'] == template[i].toLowerCase() )
			{

				var present = false;

				for(var x=0; x<indexwords[i].length; x++)
				{
					if(indexwords[i][x] == words[j]['word']) 
					{
						present = true;
						break;
					}
				}

				if(!present) 	
				{
					if((rowlen + words[j]['width']) < rowwidthmax)
					{
						indexwords[i].push(words[j]['word'].toLowerCase());
						rowlen += words[j]['width'];
						width[i] = rowlen;
					}else
					{
						continue;
					}
				}
			}
		}
	indexwords[i].sort();
	}



	var list = new Array();

	for(var k=0; k<5; k++)
	{
		var max = 0;
		var maxindex = 0;

		for(var y=0; y<indexwords.length; y++)
		{
			if(!indexwords[y]) continue;

			if(width[y] > max)
			{
				max = width[y];
				maxindex = y;
			}
		}

		list[k] = new Array();
		list[k].push(indexwords[maxindex]);
		indexwords[maxindex] = 0;

	}

	for( var i=0; i<template.length; i++ )
	{
		if(!template[i]) continue;

		for(var y=0; y<list.length; y++ )
		{
			if( template[i] == list[y][0][0].substr(0,1) || template[i].toLowerCase() == list[y][0][0].substr(0,1) ) 
			{
				htmlstr += '<table style=\"width: 235px;\"><tbody><tr>';

				for(var z=0; z<list[y][0].length; z++)
				{
					for(var j=0; j<words.length; j++)
					{
						if(list[y][0][z] == words[j]['word'].toLowerCase()) 
						{
							if(z == 0) 
							{
								htmlstr += '<td style=\"text-align: left;\">';
							}else
							{
								if(z == list[y][0].length-1)
								{
									htmlstr += '<td style=\"text-align: right;\">';
								}else
									htmlstr += '<td style=\"text-align: center;\">';
							}
	
							htmlstr += words[j]['link'];

							if(z == 0) 
							{
								htmlstr += '</td">';
							}else
								if(z == list[y][0].length-1)
								{
									htmlstr += '</td>';
								}											
						}
					}
				}

				htmlstr += '</tr></tbody></table>';
			}
		}
	}

	document.getElementById('tagCloudInnerField').innerHTML = htmlstr;
	document.getElementById('tagCloudInnerField').style.visibility = 'visible';
}

function processGoogleMap () {
	if (xmlOrders[xmlIndex] == undefined) {
		loadOrders();
		xmlIndex = 0;
	} else {
		
		var currNo = xmlOrders[xmlIndex];

		if (window.ActiveXObject)
		{
			var doc=new ActiveXObject("Microsoft.XMLDOM");
			doc.async="false";
			doc.loadXML(xmlAddresses);
		} else {
			var parser=new DOMParser();
			var doc=parser.parseFromString(xmlAddresses,"text/xml");
		}

		var root = doc.getElementsByTagName('content')[0];


		var items = root.getElementsByTagName("order");

		var item = items[xmlIndex];

		var city = item.getElementsByTagName("city")[0].firstChild.nodeValue;
		var country = item.getElementsByTagName("country")[0].firstChild.nodeValue;
		var name = item.getElementsByTagName("name")[0].firstChild.nodeValue;
		var fullname = item.getElementsByTagName("fullname")[0].firstChild.nodeValue;
		var image = item.getElementsByTagName("image")[0].firstChild.nodeValue;
		var hours = item.getElementsByTagName("hours")[0].firstChild.nodeValue;
		var minutes = item.getElementsByTagName("minutes")[0].firstChild.nodeValue;
		var fullName = item.getElementsByTagName("fullname")[0].firstChild.nodeValue;
		var longitude = item.getElementsByTagName("longitude")[0].firstChild.nodeValue;
		var latitude = item.getElementsByTagName("latitude")[0].firstChild.nodeValue;
		var url = item.getElementsByTagName("url")[0].firstChild.nodeValue;
		showAddress(city + ' ' + country, city, name, fullName, image, hours, minutes, url, 9, longitude, latitude);
		xmlIndex ++;

		setTimeout("processGoogleMap()", 10000);
	}
}

function addPointToCache(city, longitude, latitude) {
	var url = '/ajax.php?request=google&city=' + encodeURIComponent(city) + '&longitude='+encodeURIComponent(longitude)+'&latitude='+encodeURIComponent(latitude);
	new Ajax(url, {method: 'get'}).request();
}

// --------------------------------------------------------------------- 
function loadOrders() {
	var url = '/ajax.php?request=google';
	new Ajax(url, {
			method: 'get',
			onComplete: function(){
				xmlAddresses	=	this.response.text;

//				alert (xmlAddresses);
				
				if (window.ActiveXObject)
				{
					var doc=new ActiveXObject("Microsoft.XMLDOM");
					doc.async="false";
					doc.loadXML(xmlAddresses);
				}	else {
					var parser=new DOMParser();
					var doc=parser.parseFromString(xmlAddresses,"text/xml");
				}

				var root = doc.getElementsByTagName('content')[0];

				var items = root.getElementsByTagName("order");


				xmlOrders = new Array();

				
				for (var i = 0 ; i < items.length ; i++) {
					var item = items[i];
					var No = item.getAttribute("No");

					xmlOrders[i] = No;

				}
				setTimeout("processGoogleMap()",1000);
			}
		}).request();
}
// --------------------------------------------------------------------- Load facets
function loadFacetsThread(query_string,cnt, currentKeyword,currentIndexes,currentFieldsFilename,facetFilterArray,facetFilterDate,requestVendor,reset,requestCategory,isBook,sphinxIP,sphinxStatus) {
	main_template = '';
	cat_part			=	'';
	price_part		=	'';
	refinement_part	=	'';

	facet_ready_status_value = 3;

  prices    = new Array(); // Storing prices ranges here
	ready_status	=	0;
	if (query_string.indexOf('vendor=')<0 && requestVendor){
		if (query_string.length>0)
			query_string += '&vendor='+encodeURIComponent(requestVendor);
		else
			query_string = 'vendor='+encodeURIComponent(requestVendor);
	}
	if (query_string.indexOf('category=')<0 && requestCategory){
		if (query_string.length>0)
			query_string += '&category='+encodeURIComponent(requestCategory);
		else
			query_string = 'category='+encodeURIComponent(requestCategory);
	}
	if (query_string.indexOf('reset=')<0 && reset && query_string.indexOf('delete=')<0){
		if (query_string.length>0)
			query_string += '&reset='+reset;
		else
			query_string = 'reset='+reset;
	}
	query_string += '&sphinxIP='+sphinxIP;
	query_string += '&sphinxStatus='+sphinxStatus;
	// price
 	var params = getURIParams(query_string);
	if (params['priceRange']){
		price_part = "<input type=\"hidden\" name=\"priceRange\" value=\""+params['priceRange']+"\"/>";
		ready_status++;
	}else
		loadFacetPrices(query_string,cnt, currentKeyword,currentIndexes,currentFieldsFilename,facetFilterArray,facetFilterDate);
	// vendors
	if (params['searchAllByVendor']){
		vendor_part	=	'';
		ready_status++;
	}else
	 	loadfacetVendors(query_string,cnt, currentKeyword,currentIndexes,currentFieldsFilename,facetFilterArray,facetFilterDate,isBook);
	//main template with refinements
	var url = '/ajax.php?request=search_facets&'+query_string+'&main_template=1&numberOfResults='+cnt+'&currentKeyword='+escape(currentKeyword)+'&currentIndexes='+escape(currentIndexes)+'&currentFieldsFilename='+escape(currentFieldsFilename)+'&useSavedFacets=1&facetFilterArray='+facetFilterArray+'&facetFilterDate='+facetFilterDate;
	new Ajax(url, {
			method: 'get',
			onComplete: function(){
//				alert('main1');
				main_template	=	this.response.text;
				if (ready_status	>=	facet_ready_status_value){
//					alert('main');
					main_template	=	main_template.replace(/<!--categories-->/ig,cat_part).replace(/<!--prices-->/ig,price_part).replace(/<!--vendors-->/ig,vendor_part);
					document.getElementById('searched_refineBlock').innerHTML = main_template;
					setTimeout("setRefineAllBrands(true,true);",100);
					new Ajax('/ajax.php?request=search_facets&drop_tmp_file=1&currentFieldsFilename='+escape(currentFieldsFilename), { method: 'get' }).request();
					return;
				}else{
					ready_status++;
				}
			}
		}).request();
	// categories
	var url = '/ajax.php?request=search_facets&'+query_string+'&what=cat&numberOfResults='+cnt+'&currentKeyword='+escape(currentKeyword)+'&currentIndexes='+escape(currentIndexes)+'&currentFieldsFilename='+escape(currentFieldsFilename)+'&useSavedFacets=1&facetFilterArray='+facetFilterArray+'&facetFilterDate='+facetFilterDate;
	new Ajax(url, {
			method: 'get',
			onComplete: function(){
//				alert('cat1');
				cat_part	=	this.response.text;
				if (ready_status	>=	facet_ready_status_value){
//					alert('cat');
					main_template	=	main_template.replace(/<!--categories-->/ig,cat_part).replace(/<!--prices-->/ig,price_part).replace(/<!--vendors-->/ig,vendor_part);
					document.getElementById('searched_refineBlock').innerHTML = main_template;
					setTimeout("setRefineAllBrands(true,true);",100);
					new Ajax('/ajax.php?request=search_facets&drop_tmp_file=1&currentFieldsFilename='+escape(currentFieldsFilename), { method: 'get' }).request();
					return;
				}else{
					ready_status++;
				}
			}
		}).request();
}

function loadFacetPrices(query_string,cnt, currentKeyword,currentIndexes,currentFieldsFilename,facetFilterArray,facetFilterDate){
	var search_limit = cnt > 5000 ? 5000 : cnt;
	var price_step	 = 500;

	var ready_price_status  = 0;	
	var finish_status	=	Math.ceil(search_limit/price_step)-1;

	var totalFound	=	cnt;
	var stopFlag	=	0;

	var price_ranges	=	new Array();

				for(var i=0; i*price_step < search_limit; i++){
					if (stopFlag)
						continue;
					var url = '/ajax.php?request=search_facets&'+query_string+'&what=price&priceFacetsFrom='+i*price_step+'&priceFacetsLimit='+price_step+'&numberOfResults='+cnt+'&currentKeyword='+escape(currentKeyword)+'&currentIndexes='+escape(currentIndexes)+'&currentFieldsFilename='+escape(currentFieldsFilename)+'&useSavedFacets=1&facetFilterArray='+facetFilterArray+'&facetFilterDate='+facetFilterDate;
//alert(url);
					new Ajax(url, {
						method: 'get',
						onComplete: function(){

						 	var response	=	this.response.text;
				 			//server error?
						  if (response.indexOf("ERRNO") >= 0 || response.indexOf("error:") >= 0 || response.length == 0){
								throw(response.length == 0 ? "Void server response." : response);
//								stopFlag	=	1;
							}else{
//								throw(response.length == 0 ? "Void server response." : response);
    		     	// retrieve the document element
		         	response = this.response.xml.documentElement;
//							price_ranges.push(response);							
							if (response.getElementsByTagName("index").item(0)){
                var index = response.getElementsByTagName("index").item(0).firstChild.data;
                price_ranges[index]  = response;
              }							
							if (ready_price_status	>=	finish_status || stopFlag){
			   				var priceRangeArray = new Array();
    			 			var cntArray  = new Array();
								for(var i1=0; i1<=price_ranges.length; i1++){
									if (!price_ranges[i1]) continue;
									var price_response	=	price_ranges[i1].getElementsByTagName("price_range");
									var cnt_response		=	price_ranges[i1].getElementsByTagName("cnt");
    			        if(price_response.length){
										for(var j=0;j<price_response.length;j++){									
										  priceRangeArray.push(price_response.item(j).firstChild.data);
											cntArray.push(cnt_response.item(j).firstChild.data);
										}
    		      	  }
								}

					      var max_ranges = 6;
    		  			var cnt_per_range  = Math.round(totalFound / max_ranges);
      					var min  = 0;
		      			var cnt_product  = 0;
								var range_counter	=	0;
								for(var i2=0;i2<priceRangeArray.length;i2++){
									cnt_product += parseInt(cntArray[i2]);
									if (cnt_product >=cnt_per_range){
										var range	=	new Array();
										var next_val	=	parseInt((parseInt(priceRangeArray[i2])+5));
										range['range']	= min + '-' + next_val;
										range['cnt']		=	cnt_product;
										prices.push(range);
										cnt_product	=	0;
										min	=	parseInt(priceRangeArray[i2])+5;
									}
								}
								if (cnt_product>0){
									var range	=	new Array();	
									range['range']	= min + '->';
									range['cnt']		=	cnt_product;
									prices.push(range);
								}
								var html =	'';
								var params = getURIParams(query_string);
		 						if (prices.length>0 && !params['priceRange']){
									html = "<select name=\"priceRange\" onchange=\"this.form.submit();\">" +
											   " <option value=\"\">Prijsklasse</option>"; 
									for(var i3=0;i3<prices.length;i3++)
										html += "<option value=\""+prices[i3]['range']+"\">&euro; "+prices[i3]['range']+" (" + prices[i3]['cnt'] + ")</option>";
									html +=  "</select>";
  							} else {
									if (params['priceRange']){
		    						html = "<input type=\"hidden\" name=\"priceRange\" value=\""+params['priceRange']+"\"/>";
									}
								}
								price_part	=	html;

								if (ready_status>=facet_ready_status_value){
//									alert('price');	
									main_template = main_template.replace(/<!--categories-->/ig,cat_part).replace(/<!--prices-->/ig,price_part).replace(/<!--vendors-->/ig,vendor_part);
				          document.getElementById('searched_refineBlock').innerHTML = main_template;
									setTimeout("setRefineAllBrands(true,true);",100);
									new Ajax('/ajax.php?request=search_facets&drop_tmp_file=1&currentFieldsFilename='+escape(currentFieldsFilename), { method: 'get' }).request();
								}else{
									ready_status++;
								}
							}else{
								ready_price_status++;
							}
						}//else
						
					  }
					}).request();
				}	
}

function loadfacetVendors(query_string,cnt, currentKeyword,currentIndexes,currentFieldsFilename,facetFilterArray,facetFilterDate,isBook){
	var search_limit = cnt > 2000 ? 2000 : cnt;
	var vendor_step	 = 600;

	var ready_vendor_status  = 0;	
	var finish_status	=	Math.ceil(search_limit/vendor_step)-1;

	var totalFound	=	cnt;
	var stopFlag	=	0;
	var params = getURIParams(query_string);

	var vendors	=	new Array();

				for(var i=0; i*vendor_step < search_limit; i++){
					if (stopFlag)
						continue;
					var url = '/ajax.php?request=search_facets&'+query_string+'&what=vendor&vendorFacetsFrom='+i*vendor_step+'&vendorFacetsLimit='+vendor_step+'&numberOfResults='+cnt+'&currentKeyword='+escape(currentKeyword)+'&currentIndexes='+escape(currentIndexes)+'&currentFieldsFilename='+escape(currentFieldsFilename)+'&useSavedFacets=1&facetFilterArray='+facetFilterArray+'&facetFilterDate='+facetFilterDate;
//alert(url);
					new Ajax(url, {
						method: 'get',
						onComplete: function(){

						 	var response	=	this.response.text;
				 			//server error?
						  if (response.indexOf("ERRNO") >= 0 || response.indexOf("error:") >= 0 || response.length == 0){
								throw(response.length == 0 ? "Void server response." : response);
								stopFlag	=	1;
							}else{
    		     	// retrieve the document element
		         	response = this.response.xml.documentElement;
							//vendors.push(response);
							if (response.getElementsByTagName("index").item(0)){
								var index = response.getElementsByTagName("index").item(0).firstChild.data;							
								vendors[index]	=	response;
							}
							if (ready_vendor_status	>=	finish_status || stopFlag){
			   				var vendorArray = new Array();
    			 			var cntArray  = new Array();
								var checkedArray  = new Array();
								for(var i1=0; i1<=vendors.length; i1++){
									if (!vendors[i1]) continue;
									var vendor_response	=	vendors[i1].getElementsByTagName("vendor");
									var cnt_response		=	vendors[i1].getElementsByTagName("cnt");
									var checked_response		=	vendors[i1].getElementsByTagName("checked");
    			        if(vendor_response.length){
										for(var j=0;j<vendor_response.length;j++){
										  vendorArray.push(vendor_response.item(j).firstChild.data);
											cntArray.push(cnt_response.item(j).firstChild.data);
											if (checked_response.item(j).firstChild)
												checkedArray.push(checked_response.item(j).firstChild.data);
											else
												checkedArray.push(0);
										}
    		      	  }
								}

								var html = '';
								if (vendorArray.length > 0){
									html	=	'<input type="hidden" name="vendors_count" value="'+vendorArray.length+'" id="vendors_count" />' +
															'  <ul class="pulldownContainer">' +
													    '  <li><a href="javascript:togglePulldown(\'pulldownBrands\')" class="pulldownButton">'+																			
															(isBook ? 'Uitgever' : 'Merk') +' </a>'+
													    '  <ul id="pulldownBrands">'+
															'  <li><label for="refineBrandFalse" onclick="setRefineAllBrands(false);" id="refineBrandShowAllFalse"><input name="refineBrandFalse" id="refineBrandFalse" type="checkbox" value=""/>Toon alle merken</label>'+
															'<label for="refineBrandTrue" onclick="setRefineAllBrands(true);" id="refineBrandShowAllTrue">'+
															'<input name="refineBrandTrue" id="refineBrandTrue" type="checkbox" value=""/>Toon alle merken</label></li>';
									var vv=0;	
									for(var v=0;v<vendorArray.length;v++){
										vv++;
              			html += '<li class="toolTip" title="Indien u dit merk selecteert zullen er '+cntArray[v]+' producten van '+encodeURIComponent(vendorArray[v])+
														' aan de zoekresultaten toegevoegd worden."><label for="refineBrandII'+encodeURIComponent(vendorArray[v])+
														'"><input name="refineBrandII'+encodeURIComponent(vendorArray[v])+'" id="refineBrandII'+vv+'" type="checkbox" value="'+encodeURIComponent(vendorArray[v])+
														'"  '+(checkedArray[v] ? 'checked="checked"' : '')+'/>'+truncate(vendorArray[v],16,'...')+'('+cntArray[v]+')</label></li>';
         					}							
				          html += ' <li class="end"><input name="showRefine" id="showRefine" type="submit" class="buttonBlueMedium" value="Toon" /></li>'+
												  ' </ul>'+
											    ' </li>'+
												  ' </ul>';
								}
								vendor_part	=	html;

								if (ready_status>=facet_ready_status_value){
//									alert('vendor');	
//alert(cat_part);alert(price_part);alert(vendor_part); alert(main_template);
									main_template = main_template.replace(/<!--categories-->/ig,cat_part).replace(/<!--prices-->/ig,price_part).replace(/<!--vendors-->/ig,vendor_part);
				          document.getElementById('searched_refineBlock').innerHTML = main_template;
        				  setTimeout("setRefineAllBrands(true,true);",100);
									new Ajax('/ajax.php?request=search_facets&drop_tmp_file=1&currentFieldsFilename='+escape(currentFieldsFilename), { method: 'get' }).request();
								}else{
									ready_status++;
								}
							}else{
								ready_vendor_status++;
							}
						}//else
						
					  }
					}).request();
				}	
}


function getURIParams(query_string){
	var params	=	new Array();
	var full_params	=	query_string.split('&');

	for(var i=0;i<full_params.length;i++){
		param_value	=	full_params[i].split('=');
		params[param_value[0]]	=	param_value[1];
	}
	return params;
}

function truncate(str,limit,tail){
	if (escape(str).length <= limit)
		return str;
	var tail_len = tail.length;
	var words	=	str.split(' ');
	if (words.length == 1)
		return str.substr(0,str.length-tail_len-1)+tail;
	var res = '';
	for(var i=0;i<words.length;i++){
		if (res.length+words[i].length > limit)
			return res.substr(0,res.length-1)+tail;
		else
			res += words[i]+' ';
	}
	return res.substr(0,res.length-1);
}

// ---------------------------------------------------------------------- Overlay Screenshot image
function openOverlayScreenshot(imageURL){
  var myFx = new Fx.Style($('overlayScreenshot'), 'opacity').start(0,1);
  var myFx = new Fx.Style($('overlayScreenshotBack'), 'opacity').start(0,0.8);
  var myFx = new Fx.Style($('overlayScreenshotContent'), 'opacity').start(0,1);

  $('overlayScreenshotBack').style.marginTop = getScrollXY() + 'px';
  $('overlayScreenshotContent').style.top = getScrollXY() + 'px';

  window.onresize = function(){
    $('overlayScreenshotBack').style.marginTop = getScrollXY() + 'px';
    $('overlayScreenshotContent').style.top = getScrollXY() + 'px';
  }
  window.onscroll = function(){
    $('overlayScreenshotBack').style.marginTop = getScrollXY() + 'px';
    $('overlayScreenshotContent').style.top = getScrollXY() + 'px';
  }
  $('screenshotImage').src = imageURL;
}
function closeOverlayScreenshot(){
  var myFx = new Fx.Style($('overlayScreenshot'), 'opacity').start(1,0);
  var myFx = new Fx.Style($('overlayScreenshotBack'), 'opacity').start(0.8,0);
  var myFx = new Fx.Style($('overlayScreenshotContent'), 'opacity').start(1,0);
}

// ---------------------------------------------------------------------- Checks Search KeyWord
function startSearch(){
	if (document.getElementById('search').value == '' || document.getElementById('search').value ==  'Typ uw zoekterm'){
		alert('Gelieve een zoekterm in te vullen');
	}else{
	  document.getElementById('searchForm').submit();
	}
}
/*! SWFObject v2.1 <http://code.google.com/p/swfobject/>
	Copyright (c) 2007-2008 Geoff Stearns, Michael Williams, and Bobby van der Sluis
	This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/

var swfobject = function() {
	
	var UNDEF = "undefined",
		OBJECT = "object",
		SHOCKWAVE_FLASH = "Shockwave Flash",
		SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash",
		FLASH_MIME_TYPE = "application/x-shockwave-flash",
		EXPRESS_INSTALL_ID = "SWFObjectExprInst",
		
		win = window,
		doc = document,
		nav = navigator,
		
		domLoadFnArr = [],
		regObjArr = [],
		objIdArr = [],
		listenersArr = [],
		script,
		timer = null,
		storedAltContent = null,
		storedAltContentId = null,
		isDomLoaded = false,
		isExpressInstallActive = false;
	
	/* Centralized function for browser feature detection
		- Proprietary feature detection (conditional compiling) is used to detect Internet Explorer's features
		- User agent string detection is only used when no alternative is possible
		- Is executed directly for optimal performance
	*/	
	var ua = function() {
		var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF,
			playerVersion = [0,0,0],
			d = null;
		if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) {
			d = nav.plugins[SHOCKWAVE_FLASH].description;
			if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+
				d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
				playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10);
				playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10);
				playerVersion[2] = /r/.test(d) ? parseInt(d.replace(/^.*r(.*)$/, "$1"), 10) : 0;
			}
		}
		else if (typeof win.ActiveXObject != UNDEF) {
			var a = null, fp6Crash = false;
			try {
				a = new ActiveXObject(SHOCKWAVE_FLASH_AX + ".7");
			}
			catch(e) {
				try { 
					a = new ActiveXObject(SHOCKWAVE_FLASH_AX + ".6");
					playerVersion = [6,0,21];
					a.AllowScriptAccess = "always";	 // Introduced in fp6.0.47
				}
				catch(e) {
					if (playerVersion[0] == 6) {
						fp6Crash = true;
					}
				}
				if (!fp6Crash) {
					try {
						a = new ActiveXObject(SHOCKWAVE_FLASH_AX);
					}
					catch(e) {}
				}
			}
			if (!fp6Crash && a) { // a will return null when ActiveX is disabled
				try {
					d = a.GetVariable("$version");	// Will crash fp6.0.21/23/29
					if (d) {
						d = d.split(" ")[1].split(",");
						playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
					}
				}
				catch(e) {}
			}
		}
		var u = nav.userAgent.toLowerCase(),
			p = nav.platform.toLowerCase(),
			webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit
			ie = false,
			windows = p ? /win/.test(p) : /win/.test(u),
			mac = p ? /mac/.test(p) : /mac/.test(u);
		/*@cc_on
			ie = true;
			@if (@_win32)
				windows = true;
			@elif (@_mac)
				mac = true;
			@end
		@*/
		return { w3cdom:w3cdom, pv:playerVersion, webkit:webkit, ie:ie, win:windows, mac:mac };
	}();

	/* Cross-browser onDomLoad
		- Based on Dean Edwards' solution: http://dean.edwards.name/weblog/2006/06/again/
		- Will fire an event as soon as the DOM of a page is loaded (supported by Gecko based browsers - like Firefox -, IE, Opera9+, Safari)
	*/ 
	var onDomLoad = function() {
		if (!ua.w3cdom) {
			return;
		}
		addDomLoadEvent(main);
		if (ua.ie && ua.win) {
			try {	 // Avoid a possible Operation Aborted error
				doc.write("<scr" + "ipt id=__ie_ondomload defer=true src=//:></scr" + "ipt>"); // String is split into pieces to avoid Norton AV to add code that can cause errors 
				script = getElementById("__ie_ondomload");
				if (script) {
					addListener(script, "onreadystatechange", checkReadyState);
				}
			}
			catch(e) {}
		}
		if (ua.webkit && typeof doc.readyState != UNDEF) {
			timer = setInterval(function() { if (/loaded|complete/.test(doc.readyState)) { callDomLoadFunctions(); }}, 10);
		}
		if (typeof doc.addEventListener != UNDEF) {
			doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, null);
		}
		addLoadEvent(callDomLoadFunctions);
	}();
	
	function checkReadyState() {
		if (script.readyState == "complete") {
			script.parentNode.removeChild(script);
			callDomLoadFunctions();
		}
	}
	
	function callDomLoadFunctions() {
		if (isDomLoaded) {
			return;
		}
		if (ua.ie && ua.win) { // Test if we can really add elements to the DOM; we don't want to fire it too early
			var s = createElement("span");
			try { // Avoid a possible Operation Aborted error
				var t = doc.getElementsByTagName("body")[0].appendChild(s);
				t.parentNode.removeChild(t);
			}
			catch (e) {
				return;
			}
		}
		isDomLoaded = true;
		if (timer) {
			clearInterval(timer);
			timer = null;
		}
		var dl = domLoadFnArr.length;
		for (var i = 0; i < dl; i++) {
			domLoadFnArr[i]();
		}
	}
	
	function addDomLoadEvent(fn) {
		if (isDomLoaded) {
			fn();
		}
		else { 
			domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+
		}
	}
	
	/* Cross-browser onload
		- Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/
		- Will fire an event as soon as a web page including all of its assets are loaded 
	 */
	function addLoadEvent(fn) {
		if (typeof win.addEventListener != UNDEF) {
			win.addEventListener("load", fn, false);
		}
		else if (typeof doc.addEventListener != UNDEF) {
			doc.addEventListener("load", fn, false);
		}
		else if (typeof win.attachEvent != UNDEF) {
			addListener(win, "onload", fn);
		}
		else if (typeof win.onload == "function") {
			var fnOld = win.onload;
			win.onload = function() {
				fnOld();
				fn();
			};
		}
		else {
			win.onload = fn;
		}
	}
	
	/* Main function
		- Will preferably execute onDomLoad, otherwise onload (as a fallback)
	*/
	function main() { // Static publishing only
		var rl = regObjArr.length;
		for (var i = 0; i < rl; i++) { // For each registered object element
			var id = regObjArr[i].id;
			if (ua.pv[0] > 0) {
				var obj = getElementById(id);
				if (obj) {
					regObjArr[i].width = obj.getAttribute("width") ? obj.getAttribute("width") : "0";
					regObjArr[i].height = obj.getAttribute("height") ? obj.getAttribute("height") : "0";
					if (hasPlayerVersion(regObjArr[i].swfVersion)) { // Flash plug-in version >= Flash content version: Houston, we have a match!
						if (ua.webkit && ua.webkit < 312) { // Older webkit engines ignore the object element's nested param elements
							fixParams(obj);
						}
						setVisibility(id, true);
					}
					else if (regObjArr[i].expressInstall && !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac)) { // Show the Adobe Express Install dialog if set by the web page author and if supported (fp6.0.65+ on Win/Mac OS only)
						showExpressInstall(regObjArr[i]);
					}
					else { // Flash plug-in and Flash content version mismatch: display alternative content instead of Flash content
						displayAltContent(obj);
					}
				}
			}
			else {	// If no fp is installed, we let the object element do its job (show alternative content)
				setVisibility(id, true);
			}
		}
	}
	
	/* Fix nested param elements, which are ignored by older webkit engines
		- This includes Safari up to and including version 1.2.2 on Mac OS 10.3
		- Fall back to the proprietary embed element
	*/
	function fixParams(obj) {
		var nestedObj = obj.getElementsByTagName(OBJECT)[0];
		if (nestedObj) {
			var e = createElement("embed"), a = nestedObj.attributes;
			if (a) {
				var al = a.length;
				for (var i = 0; i < al; i++) {
					if (a[i].nodeName == "DATA") {
						e.setAttribute("src", a[i].nodeValue);
					}
					else {
						e.setAttribute(a[i].nodeName, a[i].nodeValue);
					}
				}
			}
			var c = nestedObj.childNodes;
			if (c) {
				var cl = c.length;
				for (var j = 0; j < cl; j++) {
					if (c[j].nodeType == 1 && c[j].nodeName == "PARAM") {
						e.setAttribute(c[j].getAttribute("name"), c[j].getAttribute("value"));
					}
				}
			}
			obj.parentNode.replaceChild(e, obj);
		}
	}
	
	/* Show the Adobe Express Install dialog
		- Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75
	*/
	function showExpressInstall(regObj) {
		isExpressInstallActive = true;
		var obj = getElementById(regObj.id);
		if (obj) {
			if (regObj.altContentId) {
				var ac = getElementById(regObj.altContentId);
				if (ac) {
					storedAltContent = ac;
					storedAltContentId = regObj.altContentId;
				}
			}
			else {
				storedAltContent = abstractAltContent(obj);
			}
			if (!(/%$/.test(regObj.width)) && parseInt(regObj.width, 10) < 310) {
				regObj.width = "310";
			}
			if (!(/%$/.test(regObj.height)) && parseInt(regObj.height, 10) < 137) {
				regObj.height = "137";
			}
			doc.title = doc.title.slice(0, 47) + " - Flash Player Installation";
			var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn",
				dt = doc.title,
				fv = "MMredirectURL=" + win.location + "&MMplayerType=" + pt + "&MMdoctitle=" + dt,
				replaceId = regObj.id;
			// For IE when a SWF is loading (AND: not available in cache) wait for the onload event to fire to remove the original object element
			// In IE you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
			if (ua.ie && ua.win && obj.readyState != 4) {
				var newObj = createElement("div");
				replaceId += "SWFObjectNew";
				newObj.setAttribute("id", replaceId);
				obj.parentNode.insertBefore(newObj, obj); // Insert placeholder div that will be replaced by the object element that loads expressinstall.swf
				obj.style.display = "none";
				var fn = function() {
					obj.parentNode.removeChild(obj);
				};
				addListener(win, "onload", fn);
			}
			createSWF({ data:regObj.expressInstall, id:EXPRESS_INSTALL_ID, width:regObj.width, height:regObj.height }, { flashvars:fv }, replaceId);
		}
	}
	
	/* Functions to abstract and display alternative content
	*/
	function displayAltContent(obj) {
		if (ua.ie && ua.win && obj.readyState != 4) {
			// For IE when a SWF is loading (AND: not available in cache) wait for the onload event to fire to remove the original object element
			// In IE you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
			var el = createElement("div");
			obj.parentNode.insertBefore(el, obj); // Insert placeholder div that will be replaced by the alternative content
			el.parentNode.replaceChild(abstractAltContent(obj), el);
			obj.style.display = "none";
			var fn = function() {
				obj.parentNode.removeChild(obj);
			};
			addListener(win, "onload", fn);
		}
		else {
			obj.parentNode.replaceChild(abstractAltContent(obj), obj);
		}
	} 

	function abstractAltContent(obj) {
		var ac = createElement("div");
		if (ua.win && ua.ie) {
			ac.innerHTML = obj.innerHTML;
		}
		else {
			var nestedObj = obj.getElementsByTagName(OBJECT)[0];
			if (nestedObj) {
				var c = nestedObj.childNodes;
				if (c) {
					var cl = c.length;
					for (var i = 0; i < cl; i++) {
						if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) {
							ac.appendChild(c[i].cloneNode(true));
						}
					}
				}
			}
		}
		return ac;
	}
	
	/* Cross-browser dynamic SWF creation
	*/
	function createSWF(attObj, parObj, id) {
		var r, el = getElementById(id);
		if (el) {
			if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content
				attObj.id = id;
			}
			if (ua.ie && ua.win) { // IE, the object element and W3C DOM methods do not combine: fall back to outerHTML
				var att = "";
				for (var i in attObj) {
					if (attObj[i] != Object.prototype[i]) { // Filter out prototype additions from other potential libraries, like Object.prototype.toJSONString = function() {}
						if (i.toLowerCase() == "data") {
							parObj.movie = attObj[i];
						}
						else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
							att += ' class="' + attObj[i] + '"';
						}
						else if (i.toLowerCase() != "classid") {
							att += ' ' + i + '="' + attObj[i] + '"';
						}
					}
				}
				var par = "";
				for (var j in parObj) {
					if (parObj[j] != Object.prototype[j]) { // Filter out prototype additions from other potential libraries
						par += '<param name="' + j + '" value="' + parObj[j] + '" />';
					}
				}
				el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>';
				objIdArr[objIdArr.length] = attObj.id; // Stored to fix object 'leaks' on unload (dynamic publishing only)
				r = getElementById(attObj.id);	
			}
			else if (ua.webkit && ua.webkit < 312) { // Older webkit engines ignore the object element's nested param elements: fall back to the proprietary embed element
				var e = createElement("embed");
				e.setAttribute("type", FLASH_MIME_TYPE);
				for (var k in attObj) {
					if (attObj[k] != Object.prototype[k]) { // Filter out prototype additions from other potential libraries
						if (k.toLowerCase() == "data") {
							e.setAttribute("src", attObj[k]);
						}
						else if (k.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
							e.setAttribute("class", attObj[k]);
						}
						else if (k.toLowerCase() != "classid") { // Filter out IE specific attribute
							e.setAttribute(k, attObj[k]);
						}
					}
				}
				for (var l in parObj) {
					if (parObj[l] != Object.prototype[l]) { // Filter out prototype additions from other potential libraries
						if (l.toLowerCase() != "movie") { // Filter out IE specific param element
							e.setAttribute(l, parObj[l]);
						}
					}
				}
				el.parentNode.replaceChild(e, el);
				r = e;
			}
			else { // Well-behaving browsers
				var o = createElement(OBJECT);
				o.setAttribute("type", FLASH_MIME_TYPE);
				for (var m in attObj) {
					if (attObj[m] != Object.prototype[m]) { // Filter out prototype additions from other potential libraries
						if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
							o.setAttribute("class", attObj[m]);
						}
						else if (m.toLowerCase() != "classid") { // Filter out IE specific attribute
							o.setAttribute(m, attObj[m]);
						}
					}
				}
				for (var n in parObj) {
					if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // Filter out prototype additions from other potential libraries and IE specific param element
						createObjParam(o, n, parObj[n]);
					}
				}
				el.parentNode.replaceChild(o, el);
				r = o;
			}
		}
		return r;
	}
	
	function createObjParam(el, pName, pValue) {
		var p = createElement("param");
		p.setAttribute("name", pName);	
		p.setAttribute("value", pValue);
		el.appendChild(p);
	}
	
	/* Cross-browser SWF removal
		- Especially needed to safely and completely remove a SWF in Internet Explorer
	*/
	function removeSWF(id) {
		var obj = getElementById(id);
		if (obj && (obj.nodeName == "OBJECT" || obj.nodeName == "EMBED")) {
			if (ua.ie && ua.win) {
				if (obj.readyState == 4) {
					removeObjectInIE(id);
				}
				else {
					win.attachEvent("onload", function() {
						removeObjectInIE(id);
					});
				}
			}
			else {
				obj.parentNode.removeChild(obj);
			}
		}
	}
	
	function removeObjectInIE(id) {
		var obj = getElementById(id);
		if (obj) {
			for (var i in obj) {
				if (typeof obj[i] == "function") {
					obj[i] = null;
				}
			}
			obj.parentNode.removeChild(obj);
		}
	}
	
	/* Functions to optimize JavaScript compression
	*/
	function getElementById(id) {
		var el = null;
		try {
			el = doc.getElementById(id);
		}
		catch (e) {}
		return el;
	}
	
	function createElement(el) {
		return doc.createElement(el);
	}
	
	/* Updated attachEvent function for Internet Explorer
		- Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks
	*/	
	function addListener(target, eventType, fn) {
		target.attachEvent(eventType, fn);
		listenersArr[listenersArr.length] = [target, eventType, fn];
	}
	
	/* Flash Player and SWF content version matching
	*/
	function hasPlayerVersion(rv) {
		var pv = ua.pv, v = rv.split(".");
		v[0] = parseInt(v[0], 10);
		v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0"
		v[2] = parseInt(v[2], 10) || 0;
		return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
	}
	
	/* Cross-browser dynamic CSS creation
		- Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php
	*/	
	function createCSS(sel, decl) {
		if (ua.ie && ua.mac) {
			return;
		}
		var h = doc.getElementsByTagName("head")[0], s = createElement("style");
		s.setAttribute("type", "text/css");
		s.setAttribute("media", "screen");
		if (!(ua.ie && ua.win) && typeof doc.createTextNode != UNDEF) {
			s.appendChild(doc.createTextNode(sel + " {" + decl + "}"));
		}
		h.appendChild(s);
		if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) {
			var ls = doc.styleSheets[doc.styleSheets.length - 1];
			if (typeof ls.addRule == OBJECT) {
				ls.addRule(sel, decl);
			}
		}
	}
	
	function setVisibility(id, isVisible) {
		var v = isVisible ? "visible" : "hidden";
		if (isDomLoaded && getElementById(id)) {
			getElementById(id).style.visibility = v;
		}
		else {
			createCSS("#" + id, "visibility:" + v);
		}
	}

	/* Filter to avoid XSS attacks 
	*/
	function urlEncodeIfNecessary(s) {
		var regex = /[\\\"<>\.;]/;
		var hasBadChars = regex.exec(s) != null;
		return hasBadChars ? encodeURIComponent(s) : s;
	}
	
	/* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only)
	*/
	var cleanup = function() {
		if (ua.ie && ua.win) {
			window.attachEvent("onunload", function() {
				// remove listeners to avoid memory leaks
				var ll = listenersArr.length;
				for (var i = 0; i < ll; i++) {
					listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]);
				}
				// cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect
				var il = objIdArr.length;
				for (var j = 0; j < il; j++) {
					removeSWF(objIdArr[j]);
				}
				// cleanup library's main closures to avoid memory leaks
				for (var k in ua) {
					ua[k] = null;
				}
				ua = null;
				for (var l in swfobject) {
					swfobject[l] = null;
				}
				swfobject = null;
			});
		}
	}();
	
	
	return {
		/* Public API
			- Reference: http://code.google.com/p/swfobject/wiki/SWFObject_2_0_documentation
		*/ 
		registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr) {
			if (!ua.w3cdom || !objectIdStr || !swfVersionStr) {
				return;
			}
			var regObj = {};
			regObj.id = objectIdStr;
			regObj.swfVersion = swfVersionStr;
			regObj.expressInstall = xiSwfUrlStr ? xiSwfUrlStr : false;
			regObjArr[regObjArr.length] = regObj;
			setVisibility(objectIdStr, false);
		},
		
		getObjectById: function(objectIdStr) {
			var r = null;
			if (ua.w3cdom) {
				var o = getElementById(objectIdStr);
				if (o) {
					var n = o.getElementsByTagName(OBJECT)[0];
					if (!n || (n && typeof o.SetVariable != UNDEF)) {
							r = o;
					}
					else if (typeof n.SetVariable != UNDEF) {
						r = n;
					}
				}
			}
			return r;
		},
		
		embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj) {
			if (!ua.w3cdom || !swfUrlStr || !replaceElemIdStr || !widthStr || !heightStr || !swfVersionStr) {
				return;
			}
			widthStr += ""; // Auto-convert to string
			heightStr += "";
			if (hasPlayerVersion(swfVersionStr)) {
				setVisibility(replaceElemIdStr, false);
				var att = {};
				if (attObj && typeof attObj === OBJECT) {
					for (var i in attObj) {
						if (attObj[i] != Object.prototype[i]) { // Filter out prototype additions from other potential libraries
							att[i] = attObj[i];
						}
					}
				}
				att.data = swfUrlStr;
				att.width = widthStr;
				att.height = heightStr;
				var par = {}; 
				if (parObj && typeof parObj === OBJECT) {
					for (var j in parObj) {
						if (parObj[j] != Object.prototype[j]) { // Filter out prototype additions from other potential libraries
							par[j] = parObj[j];
						}
					}
				}
				if (flashvarsObj && typeof flashvarsObj === OBJECT) {
					for (var k in flashvarsObj) {
						if (flashvarsObj[k] != Object.prototype[k]) { // Filter out prototype additions from other potential libraries
							if (typeof par.flashvars != UNDEF) {
								par.flashvars += "&" + k + "=" + flashvarsObj[k];
							}
							else {
								par.flashvars = k + "=" + flashvarsObj[k];
							}
						}
					}
				}
				addDomLoadEvent(function() {
					createSWF(att, par, replaceElemIdStr);
					if (att.id == replaceElemIdStr) {
						setVisibility(replaceElemIdStr, true);
					}
				});
			}
			else if (xiSwfUrlStr && !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac)) {
				isExpressInstallActive = true; // deferred execution
				setVisibility(replaceElemIdStr, false);
				addDomLoadEvent(function() {
					var regObj = {};
					regObj.id = regObj.altContentId = replaceElemIdStr;
					regObj.width = widthStr;
					regObj.height = heightStr;
					regObj.expressInstall = xiSwfUrlStr;
					showExpressInstall(regObj);
				});
			}
		},
		
		getFlashPlayerVersion: function() {
			return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] };
		},
		
		hasFlashPlayerVersion: hasPlayerVersion,
		
		createSWF: function(attObj, parObj, replaceElemIdStr) {
			if (ua.w3cdom) {
				return createSWF(attObj, parObj, replaceElemIdStr);
			}
			else {
				return undefined;
			}
		},
		
		removeSWF: function(objElemIdStr) {
			if (ua.w3cdom) {
				removeSWF(objElemIdStr);
			}
		},
		
		createCSS: function(sel, decl) {
			if (ua.w3cdom) {
				createCSS(sel, decl);
			}
		},
		
		addDomLoadEvent: addDomLoadEvent,
		
		addLoadEvent: addLoadEvent,
		
		getQueryParamValue: function(param) {
			var q = doc.location.search || doc.location.hash;
			if (param == null) {
				return urlEncodeIfNecessary(q);
			}
			if (q) {
				var pairs = q.substring(1).split("&");
				for (var i = 0; i < pairs.length; i++) {
					if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
						return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1)));
					}
				}
			}
			return "";
		},
		
		// For internal usage only
		expressInstallCallback: function() {
			if (isExpressInstallActive && storedAltContent) {
				var obj = getElementById(EXPRESS_INSTALL_ID);
				if (obj) {
					obj.parentNode.replaceChild(storedAltContent, obj);
					if (storedAltContentId) {
						setVisibility(storedAltContentId, true);
						if (ua.ie && ua.win) {
							storedAltContent.style.display = "block";
						}
					}
					storedAltContent = null;
					storedAltContentId = null;
					isExpressInstallActive = false;
				}
			} 
		}
	};
}();
/*
    This file is part of JonDesign's SmoothGallery v1.0.1.

    JonDesign's SmoothGallery is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    JonDesign's SmoothGallery is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with JonDesign's SmoothGallery; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

    Main Developer: Jonathan Schemoul (JonDesign: http://www.jondesign.net/)
    Contributed code by:
    - Christian Ehret (bugfix)
	- Nitrix (bugfix)
	- Valerio from Mad4Milk for his great help with the carousel scrolling and many other things.
	- Archie Cowan for helping me find a bugfix on carousel inner width problem.
	Many thanks to:
	- The mootools team for the great mootools lib, and it's help and support throughout the project.
*/
var $removeEvents = function (object, type)
{
	if (!object.events) return object;
	if (type){
		if (!object.events[type]) return object;
		for (var fn in object.events[type]) object.removeEvent(type, fn);
		object.events[type] = null;
	} else {
		for (var evType in object.events) object.removeEvents(evType);
		object.events = null;
	}
	return object;
};
		
		
// declaring the class
var gallery = new Class({
	initialize: function(element, options) {
		this.setOptions({
			showArrows: true,
			showCarousel: true,
			showInfopane: true,
			thumbHeight: 50,
			thumbWidth: 50,
			thumbSpacing: 0,
			embedLinks: true,
			fadeDuration: 500,
			timed: false,
			delay: 5000,
			preloader: true,
			manualData: [],
			populateData: true,
			elementSelector: "dl.imageElement",
			titleSelector: "h3",
			subtitleSelector: "p",
			linkSelector: "a.open",
			imageSelector: "img.full",
			thumbnailSelector: "img.thumbnail",
			slideInfoZoneOpacity: 0.7,
			carouselMinimizedOpacity: 0.8,
			carouselMinimizedHeight: 50,
			carouselMaximizedOpacity: 1, 
			destroyAfterPopulate: true,
			baseClass: 'imageGallery',
			withArrowsClass: 'withArrows',
			textShowCarousel: '',
			useThumbGenerator: false,
			thumbGenerator: 'resizer.php'
		}, options);
		this.fireEvent('onInit');
		this.currentIter = 0;
		this.lastIter = 0;
		this.maxIter = 0;
		this.galleryElement = element;
		this.galleryData = this.options.manualData;
		this.galleryInit = 1;
		this.galleryElements = Array();
		this.thumbnailElements = Array();
		this.galleryElement.addClass(this.options.baseClass);
		if (this.options.populateData)
			this.populateData();
		element.style.display="block";
		
		if (this.options.embedLinks)
		{
			this.currentLink = new Element('a').addClass('open').setProperties({
				href: '#',
				title: ''
			}).injectInside(element);
			if ((!this.options.showArrows) && (!this.options.showCarousel))
				this.galleryElement = element = this.currentLink;
			else
				this.currentLink.setStyle('display', 'none');
		}
		
		this.constructElements();
		if ((data.length>1)&&(this.options.showArrows))
		{
			var leftArrow = new Element('a').addClass('left').addEvent(
				'click',
				this.prevItem.bind(this)
			).injectInside(element);
			var rightArrow = new Element('a').addClass('right').addEvent(
				'click',
				this.nextItem.bind(this)
			).injectInside(element);
			this.galleryElement.addClass(this.options.withArrowsClass);
		}
		this.loadingElement = new Element('div').addClass('loadingElement').injectInside(element);
		if (this.options.showInfopane) this.initInfoSlideshow();
		if (this.options.showCarousel) this.initCarousel();
		this.doSlideShow(1);
		this.showCarousel()
	},
	populateData: function() {
		currentArrayPlace = this.galleryData.length;
		options = this.options;
		data = this.galleryData;
		this.galleryElement.getElements(options.elementSelector).each(function(el) {
			elementDict = {
				image: el.getElement(options.imageSelector).getProperty('src'),
				number: currentArrayPlace
			};
			if ((options.showInfopane) | (options.showCarousel))
				Object.extend(elementDict, {
					//title: el.getElement(options.titleSelector).innerHTML,
					//description: el.getElement(options.subtitleSelector).innerHTML
				});
			if (options.embedLinks)
				Object.extend(elementDict, {
					link: el.getElement(options.linkSelector).href||false,
					linkTitle: el.getElement(options.linkSelector).title||false
				});
			if ((!options.useThumbGenerator) && (options.showCarousel))
				Object.extend(elementDict, {
					thumbnail: el.getElement(options.thumbnailSelector).src
				});
			else if (options.useThumbGenerator)
				Object.extend(elementDict, {
					thumbnail: 'resizer.php?imgfile=' + elementDict.image + '&max_width=' + options.thumbWidth + '&max_height=' + options.thumbHeight
				});
			
			data[currentArrayPlace] = elementDict;
			currentArrayPlace++;
			if (this.options.destroyAfterPopulate)
				el.remove();
		});
		this.galleryData = data;
		this.fireEvent('onPopulated');
	},
	constructElements: function() {
		el = this.galleryElement;
		this.maxIter = this.galleryData.length;
		var currentImg;
		for(i=0;i<this.galleryData.length;i++)
		{
			var currentImg = new Fx.Style(
				new Element('div').addClass('slideElement').setStyles({
					'position':'absolute',
					'left':'0px',
					'right':'0px',
					'margin':'0px',
					'padding':'0px',
					'backgroundImage':"url('" + this.galleryData[i].image + "')",
					'backgroundPosition':"top center",
					'opacity':'0'
				}).injectInside(el),
				'opacity',
				{duration: this.options.fadeDuration}
			);
			this.galleryElements[parseInt(i)] = currentImg;
		}
	},
	destroySlideShow: function(element) {
		var myClassName = element.className;
		var newElement = new Element('div').addClass('myClassName');
		element.parentNode.replaceChild(newElement, element);
	},
	startSlideShow: function() {
		this.fireEvent('onStart');
		this.loadingElement.style.display = "none";
		this.lastIter = this.maxIter - 1;
		this.currentIter = 0;
		this.galleryInit = 0;
		this.galleryElements[parseInt(this.currentIter)].set(1);
		if (this.options.showInfopane)
			this.showInfoSlideShow.delay(0, this);
		this.prepareTimer();
		if (this.options.embedLinks)
			this.makeLink(this.currentIter);
	},
	nextItem: function() {
		this.fireEvent('onNextCalled');
		this.nextIter = this.currentIter+1;
		if (this.nextIter >= this.maxIter)
			this.nextIter = 0;
		this.galleryInit = 0;
		this.goTo(this.nextIter);
	},
	prevItem: function() {
		this.fireEvent('onPreviousCalled');
		this.nextIter = this.currentIter-1;
		if (this.nextIter <= -1)
			this.nextIter = this.maxIter - 1;
		this.galleryInit = 0;
		this.goTo(this.nextIter);
	},
	goTo: function(num) {
		this.clearTimer();
		if (this.options.embedLinks)
			this.clearLink();
		if (this.options.showInfopane)
		{
			this.slideInfoZone.clearChain();
			this.hideInfoSlideShow().chain(this.changeItem.pass(num, this));
		} else
			this.changeItem.delay(0, this, num);
		if (this.options.embedLinks)
			this.makeLink(num);
		this.prepareTimer();
		/*if (this.options.showCarousel)
			this.clearThumbnailsHighlights();*/
	},
	changeItem: function(num) {
		this.fireEvent('onStartChanging');
		this.galleryInit = 0;
		if (this.currentIter != num)
		{
			for(i=0;i<this.maxIter;i++)
			{
				if ((i != this.currentIter)) this.galleryElements[i].set(0);
			}
			if (num > this.currentIter) this.galleryElements[num].custom(1);
			else
			{
				this.galleryElements[num].set(1);
				this.galleryElements[this.currentIter].custom(0);
			}
			this.currentIter = num;
		}
		this.doSlideShow.bind(this)();
		this.fireEvent('onChanged');
	},
	clearTimer: function() {
		if (this.options.timed)
			$clear(this.timer);
	},
	prepareTimer: function() {
		if (this.options.timed)
			this.timer = this.nextItem.delay(this.options.delay, this);
	},
	doSlideShow: function(position) {
		if (this.galleryInit == 1)
		{
			imgPreloader = new Image();
			imgPreloader.onload=function(){
				this.startSlideShow.delay(0, this);
			}.bind(this);
			imgPreloader.src = this.galleryData[0].image;
		} else {
			if (this.options.showInfopane)
			{
				if (this.options.showInfopane)
				{
					this.showInfoSlideShow.delay((0), this);
				} else
					if (this.options.showCarousel)
						this.centerCarouselOn(position);
			}
		}
	},
	initCarousel: function () {
		var carouselContainerElement = new Element('div').addClass('carouselContainer').injectInside(this.galleryElement);
		this.carouselContainer = new Fx.Styles(carouselContainerElement, {transition: Fx.Transitions.expoOut});
		this.carouselContainer.normalHeight = carouselContainerElement.offsetHeight;
		this.carouselContainer.set({'opacity': this.options.carouselMinimizedOpacity, 'top': 200});
		
		this.carouselBtn = new Element('a').addClass('carouselBtn').setProperties({
			title: this.options.textShowCarousel
		}).setHTML(this.options.textShowCarousel).injectInside(carouselContainerElement);
		
		this.carouselBtn.addEvent(
			'click',
			function () {
				this.carouselContainer.clearTimer();
				this.toggleCarousel();
			}.bind(this)
		);
		this.carouselActive = false;

		var carouselElement = new Element('div').addClass('carousel').injectInside(carouselContainerElement);
		this.carousel = new Fx.Styles(carouselElement);
		
		/*this.carouselLabel = new Element('p').addClass('label').injectInside(this.carousel.element);*/
		this.carouselWrapper = new Element('div').addClass('carouselWrapper').injectInside(this.carousel.element);
		this.carouselInner = new Element('div').addClass('carouselInner').injectInside(this.carouselWrapper);
		
		this.carouselWrapper.scroller = new Scroller(this.carouselWrapper, {
			area: 100,
			velocity: 0.2
		})
		
		this.carouselWrapper.elementScroller = new Fx.Scroll(this.carouselWrapper, {
			duration: 400,
			onStart: this.carouselWrapper.scroller.stop.bind(this.carouselWrapper.scroller),
			onComplete: this.carouselWrapper.scroller.start.bind(this.carouselWrapper.scroller)
		});

		this.constructThumbnails();

		this.carouselInner.style.width = ((this.maxIter * (this.options.thumbWidth + 1))) + "px";
	},
	toggleCarousel: function() {
		if (this.carouselActive)
			this.hideCarousel();
		else
			this.showCarousel();
	},
	showCarousel: function () {
		this.fireEvent('onShowCarousel');
		this.carouselContainer.custom({
			'opacity': this.options.carouselMaximizedOpacity,
			'top': 200
		}).addEvent('onComplete', function() { this.carouselActive = true; this.carouselWrapper.scroller.start(); }.bind(this));
		
	},
	hideCarousel: function () {
		this.fireEvent('onHideCarousel');
		this.carouselContainer.custom({
			'opacity': this.options.carouselMinimizedOpacity,
			'top': (this.options.carouselMinimizedHeight - this.carouselContainer.normalHeight)
		}).addEvent('onComplete', function() { this.carouselActive = false; this.carouselWrapper.scroller.stop(); }.bind(this));
	},
	constructThumbnails: function () {
		element = this.carouselInner;
		for(i=0;i<this.galleryData.length;i++)
		{
			var currentImg = new Fx.Style(new Element ('div').addClass("thumbnail").setStyles({
					backgroundImage: "url('" + this.galleryData[i].thumbnail + "')",
					backgroundPosition: "center center",
					backgroundRepeat: 'no-repeat',
					marginLeft: this.options.thumbSpacing + "px",
					width: this.options.thumbWidth + "px",
					height: this.options.thumbHeight + "px"
				}).injectInside(element), "opacity", {duration: 200}).set(0.6);
			currentImg.element.addEvents({
				'mouseover': function (myself) {
					myself.clearTimer();
					myself.custom(0.99);
					//$(this.carouselLabel).setHTML('<span class="number">' + (myself.relatedImage.number + 1) + "/" + this.maxIter + ":</span> " + myself.relatedImage.title);
				}.pass(currentImg, this),
				'mouseout': function (myself) {
					myself.clearTimer();
					myself.custom(0.6);
				}.pass(currentImg, this),
				'click': function (myself) {
					this.goTo(myself.relatedImage.number);
					this.clearTimer()
				}.pass(currentImg, this)
			});
			
			currentImg.relatedImage = this.galleryData[i];
			this.thumbnailElements[parseInt(i)] = currentImg;
		}
	},
	clearThumbnailsHighlights: function()
	{
		for(i=0;i<this.galleryData.length;i++)
		{
			this.thumbnailElements[i].clearTimer();
			this.thumbnailElements[i].custom(0.6);
		}
	},
	centerCarouselOn: function(num) {
		var carouselElement = this.thumbnailElements[num];
		var position = carouselElement.element.offsetLeft + (carouselElement.element.offsetWidth / 2);
		var carouselWidth = this.carouselWrapper.offsetWidth;
		var carouselInnerWidth = this.carouselInner.offsetWidth;
		var diffWidth = carouselWidth / 2;
		var scrollPos = position-diffWidth;
		//this.carouselWrapper.elementScroller.scrollTo(scrollPos,0);
	},
	initInfoSlideshow: function() {
		/*if (this.slideInfoZone.element)
			this.slideInfoZone.element.remove();*/
		this.slideInfoZone = new Fx.Styles(new Element('div').addClass('slideInfoZone').injectInside($(this.galleryElement))).set({'opacity':0});
		var slideInfoZoneTitle = new Element('h2').injectInside(this.slideInfoZone.element);
		var slideInfoZoneDescription = new Element('p').injectInside(this.slideInfoZone.element);
		this.slideInfoZone.normalHeight = this.slideInfoZone.element.offsetHeight;
		this.slideInfoZone.element.setStyle('opacity',0);
	},
	changeInfoSlideShow: function()
	{
		this.hideInfoSlideShow.delay(500, this);
		this.showInfoSlideShow.delay(500, this);
	},
	showInfoSlideShow: function() {
		this.fireEvent('onShowInfopane');
		this.slideInfoZone.clearTimer();
		element = this.slideInfoZone.element;
		element.getElement('h2').setHTML(this.galleryData[this.currentIter].title);
		element.getElement('p').setHTML(this.galleryData[this.currentIter].description);
		this.slideInfoZone.custom({'opacity': [0, this.options.slideInfoZoneOpacity], 'height': [0, this.slideInfoZone.normalHeight]});
		if (this.options.showCarousel)
			this.slideInfoZone.chain(this.centerCarouselOn.pass(this.currentIter, this));
		return this.slideInfoZone;
	},
	hideInfoSlideShow: function() {
		this.fireEvent('onHideInfopane');
		this.slideInfoZone.clearTimer();
		this.slideInfoZone.custom({'opacity': 0, 'height': 0});
		return this.slideInfoZone;
	},
	makeLink: function(num) {
		this.currentLink.setProperties({
			href: this.galleryData[num].link,
			title: this.galleryData[num].linkTitle
		})
		if (!((this.options.embedLinks) && (!this.options.showArrows) && (!this.options.showCarousel)))
			this.currentLink.setStyle('display', 'block');
	},
	clearLink: function() {
		this.currentLink.setProperties({href: '', title: ''});
		if (!((this.options.embedLinks) && (!this.options.showArrows) && (!this.options.showCarousel)))
			this.currentLink.setStyle('display', 'none');
	}
});
gallery.implement(new Events);
gallery.implement(new Options);
/* All code copyright 2006 Jonathan Schemoul */function hideTabs(){
	$$('.tabPanel').setStyle('display', 'none')
	$$('.active').setStyle('display', 'block')
	}

var mootabs = new Class({
	initialize: function(element, options) {
		
		this.options = Object.extend({
			width:				'300px',
			//height:			'200px',
			changeTransition:	Fx.Transitions.Bounce.easeOut,
			duration:			1000,
			mouseOverClass:		'active',
			activateOnLoad:		'first',
			useAjax: 			false,
			ajaxUrl: 			'',
			ajaxOptions: 		{method:'get'},
			ajaxLoadingText: 	'Loading...'
		}, options || {});
		
		this.el = $(element);
		this.elid = element;
		
		this.el.setStyles({
			//height: this.options.height,
			width: this.options.width
		});
		
		this.titles = $$('#' + this.elid + ' ul li');
		//this.panelHeight = this.el.getSize().size.y - (this.titles[0].getSize().size.y + 4);
		this.panels = $$('#' + this.elid + ' .tabPanel');
		
		this.titles.each(function(item) {
			item.addEvent('click', function(){
					item.removeClass(this.options.mouseOverClass);
					this.activate(item);
				}.bind(this)
			);
			
			item.addEvent('mouseover', function() {
				if(item != this.activeTitle)
				{
					item.addClass(this.options.mouseOverClass);
				}
			}.bind(this));
			
			item.addEvent('mouseout', function() {
				if(item != this.activeTitle)
				{
					item.removeClass(this.options.mouseOverClass);
				}
			}.bind(this));
		}.bind(this));
		
		
		if(this.options.activateOnLoad != 'none')
		{
			if(this.options.activateOnLoad == 'first')
			{
				this.activate(this.titles[0], true);
			}
			else
			{
				this.activate(this.options.activateOnLoad, true);	
			}
		}
	},
	
	activate: function(tab, skipAnim){
		if(! $defined(skipAnim))
		{
			skipAnim = false;
		}
		if($type(tab) == 'string') 
		{
			myTab = $$('#' + this.elid + ' ul li').filterByAttribute('title', '=', tab)[0];
			tab = myTab;
		}
		
		if($type(tab) == 'element')
		{
			var newTab = tab.getProperty('title');
			this.panels.removeClass('active');
			this.panels.setStyle('display', 'none')
			
			this.activePanel = this.panels.filterById(newTab)[0];
			
			this.activePanel.addClass('active');
			this.activePanel.setStyle('display', 'block')
			
			if(this.options.changeTransition != 'none' && skipAnim==false)
			{
				this.panels.filterById(newTab).setStyle('height', 0);
				var changeEffect = new Fx.Elements(this.panels.filterById(newTab), {duration: this.options.duration, transition: this.options.changeTransition});
				changeEffect.start({
					'0': {
						'height': [0, this.panelHeight]
					}
				});
			}
			
			this.titles.removeClass('active');
			
			tab.addClass('active');
			
			this.activeTitle = tab;
			
			if(this.options.useAjax)
			{
				this._getContent();
			}
		}
	},
	
	_getContent: function(){
		this.activePanel.setHTML(this.options.ajaxLoadingText);
		var newOptions = {update: this.activePanel.getProperty('id')};
		this.options.ajaxOptions = Object.extend(this.options.ajaxOptions, newOptions || {});
		var tabRequest = new Ajax(this.options.ajaxUrl + '?tab=' + this.activeTitle.getProperty('title'), this.options.ajaxOptions);
		tabRequest.request();
	},
	
	addTab: function(title, label, content){
		//the new title
		var newTitle = new Element('li', {
			'title': title
		});
		newTitle.appendText(label);
		this.titles.include(newTitle);
		$$('#' + this.elid + ' ul').adopt(newTitle);
		newTitle.addEvent('click', function() {
			this.activate(newTitle);
		}.bind(this));
		
		newTitle.addEvent('mouseover', function() {
			if(newTitle != this.activeTitle)
			{
				newTitle.addClass(this.options.mouseOverClass);
			}
		}.bind(this));
		newTitle.addEvent('mouseout', function() {
			if(newTitle != this.activeTitle)
			{
				newTitle.removeClass(this.options.mouseOverClass);
			}
		}.bind(this));
		//the new panel
		var newPanel = new Element('div', {
			//'style': {'height': this.options.panelHeight},
			'id': title,
			'class': 'tabPanel'
		});
		if(!this.options.useAjax)
		{
			newPanel.setHTML(content);
		}
		this.panels.include(newPanel);
		this.el.adopt(newPanel);
	},
	
	removeTab: function(title){
		if(this.activeTitle.title == title)
		{
			this.activate(this.titles[0]);
		}
		$$('#' + this.elid + ' ul li').filterByAttribute('title', '=', title)[0].remove();
		
		$$('#' + this.elid + ' .tabPanel').filterById(title)[0].remove();
	},
	
	next: function(){
		var nextTab = this.activeTitle.getNext();
		if(!nextTab) {
			nextTab = this.titles[0];
		}
		this.activate(nextTab);
	},
	
	previous: function(){
		var previousTab = this.activeTitle.getPrevious();
		if(!previousTab) {
			previousTab = this.titles[this.titles.length - 1];
		}
		this.activate(previousTab);
	}
});/*
	Slimbox v1.41 - The ultimate lightweight Lightbox clone
	by Christophe Beyls (http://www.digitalia.be) - MIT-style license.
	Inspired by the original Lightbox v2 by Lokesh Dhakar.
*/
var Lightbox = {
	init: function(options){
		this.options = $extend({
			resizeDuration: 400,
			resizeTransition: false,	// default transition
			initialWidth: 400,
			initialHeight: 400,
			animateCaption: false,
			showCounter: true
		}, options || {});

		this.anchors = [];
		$each(document.links, function(el){
			if (el.rel && el.rel.test(/^lightbox/i)){
				el.onclick = this.click.pass(el, this);
				this.anchors.push(el);
			}
		}, this);
		this.eventKeyDown = this.keyboardListener.bindAsEventListener(this);
		this.eventPosition = this.position.bind(this);

		this.overlay = new Element('div', {'id': 'lbOverlay'}).injectInside(document.body);

		this.center = new Element('div', {'id': 'lbCenter', 'styles': {'width': this.options.initialWidth, 'height': this.options.initialHeight, 'marginLeft': -(this.options.initialWidth/2), 'marginTop': 140, 'display': 'none'}}).injectInside(document.body);
		this.image = new Element('div', {'id': 'lbImage'}).injectInside(this.center);
		//
		this.imageClose = new Element('a', {'id': 'imageClose', 'href': '#', 'styles': {'display': 'block'}}).injectInside(this.image);
		this.imageClose.onclick = this.close.bind(this);
		//
		this.prevLink = new Element('a', {'id': 'lbPrevLink', 'href': '#', 'styles': {'display': 'none'}}).injectInside(this.image);
		this.nextLink = this.prevLink.clone().setProperty('id', 'lbNextLink').injectInside(this.image);
		this.prevLink.onclick = this.previous.bind(this);
		this.nextLink.onclick = this.next.bind(this);

		this.bottomContainer = new Element('div', {'id': 'lbBottomContainer', 'styles': {'display': 'none'}}).injectInside(document.body);
		this.bottom = new Element('div', {'id': 'lbBottom'}).injectInside(this.bottomContainer);
		new Element('a', {'id': 'lbCloseLink', 'href': '#'}).injectInside(this.bottom).onclick = this.overlay.onclick = this.close.bind(this);
		this.caption = new Element('div', {'id': 'lbCaption'}).injectInside(this.bottom);
		this.number = new Element('div', {'id': 'lbNumber'}).injectInside(this.bottom);
		new Element('div', {'styles': {'clear': 'both'}}).injectInside(this.bottom);

		var nextEffect = this.nextEffect.bind(this);
		this.fx = {
			overlay: this.overlay.effect('opacity', {duration: 500}).hide(),
			resize: this.center.effects($extend({duration: this.options.resizeDuration, onComplete: nextEffect}, this.options.resizeTransition ? {transition: this.options.resizeTransition} : {})),
			image: this.image.effect('opacity', {duration: 500, onComplete: nextEffect}),
			bottom: this.bottom.effect('margin-top', {duration: 400, onComplete: nextEffect})
		};

		this.preloadPrev = new Image();
		this.preloadNext = new Image();
	},

	click: function(link){
		//if (link.rel.length == 8) return this.show(link.href, link.title);

		var j, imageNum, images = [];
		this.anchors.each(function(el){
			if (el.rel == link.rel){
				for (j = 0; j < images.length; j++) if(images[j][0] == el.href) break;
				if (j == images.length){
					images.push([el.href, el.title]);
					if (el.href == link.href) imageNum = j;
				}
			}
		}, this);
		return this.open(images, imageNum);
	},

	show: function(url, title){
		return this.open([[url, title]], 0);
	},

	open: function(images, imageNum){
		this.images = images;
		this.position();
		this.setup(true);
		this.top = window.getScrollTop() + (window.getHeight() / 15);
		this.center.setStyles({top: this.top, display: ''});
		this.fx.overlay.start(0.8);
		return this.changeImage(imageNum);
	},

	position: function(){
		this.overlay.setStyles({'top': window.getScrollTop(), 'height': window.getHeight()});
	},

	setup: function(open){
		var elements = $A(document.getElementsByTagName('object'));
		elements.extend(document.getElementsByTagName(window.ie ? 'select' : 'embed'));
		elements.each(function(el){
			if (open) el.lbBackupStyle = el.style.visibility;
			el.style.visibility = open ? 'hidden' : el.lbBackupStyle;
		});
		var fn = open ? 'addEvent' : 'removeEvent';
		window[fn]('scroll', this.eventPosition)[fn]('resize', this.eventPosition);
		document[fn]('keydown', this.eventKeyDown);
		this.step = 0;
	},

	keyboardListener: function(event){
		switch (event.keyCode){
			case 27: case 88: case 67: this.close(); break;
			case 37: case 80: this.previous(); break;	
			case 39: case 78: this.next();
		}
	},

	previous: function(){
		return this.changeImage(this.activeImage-1);
	},

	next: function(){
		return this.changeImage(this.activeImage+1);
	},

	changeImage: function(imageNum){
		if (this.step || (imageNum < 0) || (imageNum >= this.images.length)) return false;
		this.step = 1;
		this.activeImage = imageNum;

		this.bottomContainer.style.display = this.prevLink.style.display = this.nextLink.style.display = 'none';
		this.fx.image.hide();
		this.center.className = 'lbLoading';

		this.preload = new Image();
		this.preload.onload = this.nextEffect.bind(this);
		this.preload.src = this.images[imageNum][0];
		return false;
	},

	nextEffect: function(){
		switch (this.step++){
		case 1:
			this.center.className = '';
			this.image.style.backgroundImage = 'url('+this.images[this.activeImage][0]+')';
			this.image.style.width = this.bottom.style.width = this.preload.width+'px';
			this.image.style.height = this.prevLink.style.height = this.nextLink.style.height = this.preload.height+'px';

			this.caption.setHTML(this.images[this.activeImage][1] || '');
			this.number.setHTML((!this.options.showCounter || (this.images.length == 1)) ? '' : 'Image '+(this.activeImage+1)+' of '+this.images.length);

			if (this.activeImage) this.preloadPrev.src = this.images[this.activeImage-1][0];
			if (this.activeImage != (this.images.length - 1)) this.preloadNext.src = this.images[this.activeImage+1][0];
			if (this.center.clientHeight != this.image.offsetHeight){
				this.fx.resize.start({height: this.image.offsetHeight});
				break;
			}
			this.step++;
		case 2:
			if (this.center.clientWidth != this.image.offsetWidth){
				this.fx.resize.start({width: this.image.offsetWidth, marginLeft: -this.image.offsetWidth/2});
				break;
			}
			this.step++;
		case 3:
			this.bottomContainer.setStyles({top: this.top + this.center.clientHeight, height: 0, marginLeft: this.center.style.marginLeft, display: ''});
			this.fx.image.start(1);
			break;
		case 4:
			if (this.options.animateCaption){
				this.fx.bottom.set(-this.bottom.offsetHeight);
				this.bottomContainer.style.height = '';
				this.fx.bottom.start(0);
				break;
			}
			this.bottomContainer.style.height = '';
		case 5:
			if (this.activeImage) this.prevLink.style.display = '';
			if (this.activeImage != (this.images.length - 1)) this.nextLink.style.display = '';
			this.step = 0;
		}
	},

	close: function(){
		if (this.step < 0) return;
		this.step = -1;
		if (this.preload){
			this.preload.onload = Class.empty;
			this.preload = null;
		}
		for (var f in this.fx) this.fx[f].stop();
		this.center.style.display = this.bottomContainer.style.display = 'none';
		this.fx.overlay.chain(this.setup.pass(false, this)).start(0);
		return false;
	}
};
window.addEvent('domready', Lightbox.init.bind(Lightbox));///////////////////////////////////////////////////////////////////////////////////////////////////

function collectSingleProductToCart(prodlevid, supplier, qty, redirect) {
	var products = Array();
	products.push(new Array(prodlevid, supplier, qty));
	if (redirect == 1) {
		redirectToCart(products);
	} else {
		ajaxAddToCart (products);
	}
}

function collectFeaturedProductToCart(prodlevid, supplier, qty, main_prodlevid, main_supplier) {
	var products						= Array();
	var additionalProducts	= Array();
	products.push(new Array(prodlevid, supplier, qty));
	additionalProducts.push(new Array(main_prodlevid, main_supplier, qty));
	ajaxAddToCart (products,additionalProducts);
}
///////////////////////////////////////////////////////////////////////////////////////////////////

function collectBundleToCart(bundle, qty) {
	var bundle_array = new Array();
	var bundle_split = bundle.split(", ");

	for (i=0; bundle_split[i]; i+=2) {
		bundle_array.push(new Array(bundle_split[i], bundle_split[i+1], qty));	
	}

	collectProductsToCart(false, false, false, bundle_array);
}	

///////////////////////////////////////////////////////////////////////////////////////////////////

function collectProductsToCart(prodlevid, supplier, qty, bundle_array) {

	var products = Array();

	// Checking the main product
	if (prodlevid && supplier && qty) {
		products.push(new Array(prodlevid, supplier, qty));
	}

 	// Checking whether we need to add bundles
	if (bundle_array) {
		for (i=0; bundle_array[i]; i++) {
			products.push(bundle_array[i]);
		}
	}

	// Collecting featured products if they are present
  for (i=0;document.forms['featured_products'].elements[i];i++) {
		if (document.forms['featured_products'].elements[i].checked) {
			var product  = document.forms['featured_products'].elements[i].value;
			var splitted = product.split(", ");
			products.push(new Array(splitted[0], splitted[1], qty));
		}
	}

  // Collecting optional products if they are present
	for (i=0;document.forms['options'].elements[i];i++) {
		if (document.forms['options'].elements[i].checked) {
			var product  = document.forms['options'].elements[i].value;
			var splitted = product.split(", ");
			products.push(new Array(splitted[0], splitted[1], qty));
		}
	}

	// Collecting preferred options if they are present
	for (i=0;document.forms['preferred_options'].elements[i];i++) {
		if (document.forms['preferred_options'].elements[i].checked) {
			var product  = document.forms['preferred_options'].elements[i].value;
			var splitted = product.split(", ");
			products.push(new Array(splitted[0], splitted[1], qty));
		}
	}

	ajaxAddToCart (products);
	//redirectToCart(products);

}

function ajaxAddToCart (products,additionalProducts) {

		// Generating purchase request
		var report = "Going to purchase following products:\n";
		var url    = '/ajax.php?request=addToCart';

		cartText	=	'<table width="100%"><tr align="center"><td>Uw product(en) worden toegevoegd ...</td></tr></table>';

		for (i=0; products[i]; i++) {
			url += '&prodlevid' + (i+1) + '=' + products[i][0] + '&supplier' + (i+1) + '=' + products[i][1]  + '&quant' + (i+1) + '=' + products[i][2]; 
		}
		if (additionalProducts) {
			for (i=0; additionalProducts[i]; i++) {
				url += '&addProdlevid' + (i+1) + '=' + additionalProducts[i][0] + '&addSupplier' + (i+1) + '=' + additionalProducts[i][1]  + '&addQuant' + (i+1) + '=' + additionalProducts[i][2]; 
			}
		}

		time	=	new Date();
		url += '&hash='+ time.getTime();
		url += Math.random();


		var myFx = new Fx.Style($('overlayMiniCart'), 'opacity').start(0,1);
		var myFx = new Fx.Style($('overlayMiniCartBack'), 'opacity').start(0,0.8);
		var myFx = new Fx.Style($('overlayMiniCartContent'), 'opacity').start(0,1);

		setTimeout ('closeOverlayMiniCart()', 2000);

		var shoppingCart	=	document.getElementById('shoppingCart');

		if (shoppingCart) {
			document.getElementById('shoppingCart').innerHTML = "<table><tr><td><img src='/images/icons/loading_price.gif'></td></tr></table>";
		}

		document.getElementById("miniCartFormContainer").innerHTML = cartText;

		if (shoppingCart) {
			new Ajax(url, {
				method: 'get',
				update: $('shoppingCart')
			}).request();
		} else {
			new Ajax(url, {
				method: 'get'
			}).request();
		}

		// window.location.href = url;
}

function closeOverlayMiniCart () {
		var myFx = new Fx.Style($('overlayMiniCart'), 'opacity').start(1,0);
		var myFx = new Fx.Style($('overlayMiniCartBack'), 'opacity').start(0.8,0);
		var myFx = new Fx.Style($('overlayMiniCartContent'), 'opacity').start(1,0);
}


///////////////////////////////////////////////////////////////////////////////////////////////////

function redirectToCart(products) {

	if (products.length) {

		// Generating purchase request
		var report = "Going to purchase following products:\n";
		var url    = '/?page=cart'
		for (i=0; products[i]; i++) {
			url += '&prodlevid' + (i+1) + '=' + products[i][0] + '&supplier' + (i+1) + '=' + products[i][1]  + '&quant' + (i+1) + '=' + products[i][2]; 
			report += " - Prodlevid: " + products[i][0] + ", Supplier: " + products[i][1] + ", Quantity: " + products[i][2] + "\n";
		}
		// alert(report);

		if (window.location.href.indexOf('iceshop') == -1) {
			url = 'http://www.centralpoint.nl' + url;
		}

		// window.location.href = url;
		toPost(url);
	}

}

///////////////////////////////////////////////////////////////////////////////////////////////////

function toPost(getString) {
	var parms 	= getString.split('?'); 
	var newF  	= document.createElement("form"); 
	newF.action = parms[0]; 
	newF.method = 'POST'; 
	var parms   = parms[1].split('&'); 
	for (var i=0; i<parms.length; i++) {var pos = parms[i].indexOf('='); if (pos > 0) {var key = parms[i].substring(0,pos); var val = parms[i].substring(pos+1);  
	/*@cc_on @if (@_jscript)  var newH = document.createElement("<input name='"+key+"'>");  @else */  
	var newH = document.createElement("input"); newH.name = key; /* @end @*/ newH.type = 'hidden'; newH.value = val; newF.appendChild(newH);}} document.getElementsByTagName('body')[0].appendChild(newF); newF.submit();
}

///////////////////////////////////////////////////////////////////////////////////////////////////

function checkEmailExists(e) {
	var e_mail      = document.getElementById('email').value;
	var emailExists = document.getElementById('customerExists').innerHTML;

	if (e_mail.length > 0) {
		if (emailExists == "1") {
			sendReminder = confirm("Uw e-mailadres " + e_mail + " is al gekoppeld aan een account.\n\r \n\r Klik op \"ok\" om uw wachtwoord op te vragen of klik op \"annuleren\" om een nieuwe account aan te maken.");
			if (sendReminder) {
				window.location.href = '/?page=cart&step=2&sendReminder=' + e_mail; 
				e.returnValue = false;
				return false;
			}
		}
	}

	e.returnValue = true;
	return true;
}

///////////////////////////////////////////////////////////////////////////////////////////////////

function checkCustomerExists(e_mail) {
	new Ajax('/ajax.php?request=checkCustomerExists&email=' + e_mail, {
	    		   method: 'get',
			       update: $('customerExists')
			    }).request();
	return true;				
}

///////////////////////////////////////////////////////////////////////////////////////////////////
function collectPrinterSuppliesToCart() {
	var products						= new Array();

	var elements	=	document.getElementsByName('amountPrinterSupply');
	var supplies	=	document.getElementsByName('printerSupply');
	// Collecting printer supplies if they are present
  for (i=0;i<elements.length;i++) {
			if (validateAmount(elements[i].id) && elements[i].value>0){ // collect to cart
				var supply = supplies[i].value;				
				var splitted = supply.split("|");
				products.push(new Array(splitted[0], splitted[1], elements[i].value));
			}
	}
	if (products.length == 0)	return;

	ajaxAddToCart (products,null);
}
///////////////////////////////////////////////////////////////////////////////////////////////////

function compareSelectedProducts(formName, elemPrefix){

	count    = 0;
	products = new Array();

	try{
		for(i=0;document.forms[formName].elements[i];i++){

			name     = document.forms[formName].elements[i].name;
			checkbox = name.indexOf(elemPrefix);

			if (checkbox > -1 && document.forms[formName].elements[i].checked) {

				products.push(name.substring(elemPrefix.length, name.length));
				count++;

			}
		}
		
		if(count < 2){
			alert('Selecteer minimaal twee producten om te vergelijken');
		}else{
			url = '/?page=compare';
			for(i=0;products[i];i++) {
				url += '&product_' + (i+1) + '=' + products[i];
			}
			window.location.href = url;

		}

	}catch(e){
	}

}

///////////////////////////////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////////////////////////////

var xmlHttp = createXmlHttpRequestObject(); 

function createXmlHttpRequestObject() {
  var xmlHttp;
  try {
    xmlHttp = new XMLHttpRequest();
  } catch(e) {
    // assume IE6 or older
    var XmlHttpVersions = new Array('MSXML2.XMLHTTP.6.0',
                                    'MSXML2.XMLHTTP.5.0',
                                    'MSXML2.XMLHTTP.4.0',
                                    'MSXML2.XMLHTTP.3.0',
                                    'MSXML2.XMLHTTP',
                                    'Microsoft.XMLHTTP');
    // try every prog id until one works
    for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++)  {
      try  { 
        xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
      } catch (e) {}
    }
  }

  // return the created object or display an error message
  if (!xmlHttp)
    alert("Uw browser ondersteunt geen AJAX scripts. De prijs en voorraad kan helaas niet opgehaald worden. Update u a.u.b. uw browser.");
  else 
    return xmlHttp;
}

///////////////////////////////////////////////////////////////////////////////////////////////////

// make asynchronous HTTP request using the XMLHttpRequest object 
function processPrice(vendor,product,secret,stock,euprice,eupriceWithVat){
  
  if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
		var url	=	"/ajax.php?request=price&brand=" + vendor + "&product=" + product + "&stock=" + stock + "&euprice=" + euprice + "&eupriceWithVat=" + eupriceWithVat + "&secret=" + encodeURIComponent(secret) + '&nocache=' + Math.random();
    xmlHttp.open("GET", url, true);
    xmlHttp.onreadystatechange = handleServerResponse;
    xmlHttp.send(null);

  } else {

    setTimeout('processPrice('+vendor+','+product+','+secret+','+stock+','+euprice+','+eupriceWithVat+')', 1000);

	}
}

///////////////////////////////////////////////////////////////////////////////////////////////////

function handleServerResponse() {
  if (xmlHttp.readyState == 4) {
    if (xmlHttp.status == 200) {

			try {
      	xmlResponse		= xmlHttp.responseXML;
      	xmlRoot				= xmlResponse.documentElement;
				error					= xmlRoot.getElementsByTagName("error")[0].childNodes[0].nodeValue;
				downloadbare	=	xmlRoot.getElementsByTagName("downloadbare")[0].childNodes[0].nodeValue;

				if (error == 0) {
			
					var extax						= xmlRoot.getElementsByTagName("price")[0].childNodes[0].nodeValue;
					var intax						= xmlRoot.getElementsByTagName("priceWithVat")[0].childNodes[0].nodeValue;
					var stock						= xmlRoot.getElementsByTagName("stockValue")[0].childNodes[0].nodeValue;
					var vendor					= xmlRoot.getElementsByTagName("vendor")[0].childNodes[0].nodeValue;
					var prodid					= xmlRoot.getElementsByTagName("partNo")[0].childNodes[0].nodeValue;
					var name						= xmlRoot.getElementsByTagName("name")[0].childNodes[0].nodeValue;
					var deliveryDate		=	xmlRoot.getElementsByTagName("date")[0].childNodes[0].nodeValue;
					var stockEigenInfo	=	xmlRoot.getElementsByTagName("stockEigenInfo")[0].childNodes[0].nodeValue;

					if (downloadbare == 1) {
						var downloadbare_extax  				= xmlRoot.getElementsByTagName("downloadbare_price")[0].childNodes[0].nodeValue;
						var downloadbare_intax  				= xmlRoot.getElementsByTagName("downloadbare_priceWithVat")[0].childNodes[0].nodeValue;
						var downloadbare_stock  				= xmlRoot.getElementsByTagName("downloadbare_stockValue")[0].childNodes[0].nodeValue;
						var downloadbare_vendor 				= xmlRoot.getElementsByTagName("downloadbare_vendor")[0].childNodes[0].nodeValue;
						var downloadbare_prodid 				= xmlRoot.getElementsByTagName("downloadbare_partNo")[0].childNodes[0].nodeValue;
						var downloadbare_name   				= xmlRoot.getElementsByTagName("downloadbare_name")[0].childNodes[0].nodeValue;
						var downloadbare_deliveryDate		=	xmlRoot.getElementsByTagName("downloadbare_date")[0].childNodes[0].nodeValue;
						displayDownloadbarePriceOk(extax, intax, stock, vendor, prodid, name, deliveryDat, downloadbare_extax, downloadbare_intax, downloadbare_stock, downloadbare_vendor, downloadbare_prodid, downloadbare_name, downloadbare_deliveryDate, stockEigenInfo);
					} else {
						displayPriceOk(extax, intax, stock, vendor, prodid, name, deliveryDate, stockEigenInfo);
					}

				} else {

					displayPriceNotOk();

				}
    	} catch (err) {
				displayPriceNotOk();
			}
		}

    // a HTTP status different than 200 signals an error

    else 
    {
       displayPriceNotOk();
    }
  }
}
function displayDownloadBarePriceOk(extax, intax, stock, vendor, prodid, name, deliveryDate, downloadbare_extax, downloadbare_intax, downloadbare_stock, downloadbare_vendor, downloadbare_prodid, downloadbare_name, downloadbare_deliveryDate, stockEigenInfo){

 	document.getElementById("loadingPrice").style.display = 'none';
	document.getElementById("priceEx").style.display 			= '';
	document.getElementById("stock").style.display 				= '';
	document.getElementById("priceInc").style.display 		= '';

	document.getElementById("txtExtax").innerHTML      = "<strong>&#8364;" + extax + "</strong> excl.BTW";
	document.getElementById("txtIntax").innerHTML      = "<strong>&#8364;" + intax + "</strong> incl.BTW";

	if (stock > 0) {
		document.getElementById("txtStock").innerHTML    	= "voorraad:<span class=\"stockTrue\" style=\"cursor: hand; cursor: pointer;\" onclick=\"window.location.href=window.location.href + '#';javascript:checkMainStock()\">" + stock  + "</span>";
		if (stockEigenInfo != '0') {
			document.getElementById("deliveryText").innerHTML    = stockEigenInfo;
		}
	} else {
		document.getElementById("txtStock").innerHTML    	= "voorraad:<span class=\"stockFalse\" style=\"cursor: hand; cursor: pointer;\" onclick=\"window.location.href=window.location.href + '#'; javascript:checkMainStock()\">" + stock + "</span>";
		document.getElementById("stockText").innerHTML    = 'Product is momenteel niet op voorraad.';
		document.getElementById("deliveryText").innerHTML = 'Verwachte voorraad datum: ' + deliveryDate;
		document.getElementById("stockText").className		= 'stockFalse';
	}


	document.getElementById("stockText").style.display 		= '';
	document.getElementById("deliveryText").style.display = '';
	document.getElementById("orderForm").style.display 		= '';

}

///////////////////////////////////////////////////////////////////////////////////////////////////

function displayPriceOk(extax, intax, stock, vendor, prodid, name, deliveryDate, stockEigenInfo){

 	document.getElementById("loadingPrice").style.display = 'none';
	document.getElementById("priceEx").style.display 			= '';
	document.getElementById("stock").style.display 				= '';
	document.getElementById("priceInc").style.display 		= '';

	document.getElementById("txtExtax").innerHTML      = "<strong>&#8364;" + extax + "</strong> excl.BTW";
	document.getElementById("txtIntax").innerHTML      = "<strong>&#8364;" + intax + "</strong> incl.BTW";

	if (stock > 0) {
		document.getElementById("txtStock").innerHTML    	= "voorraad:<span class=\"stockTrue\" style=\"cursor: hand; cursor: pointer;\" onclick=\"window.location.href=window.location.href + '#';javascript:checkMainStock()\">" + stock  + "</span>";
		if (stockEigenInfo != '0') {
			document.getElementById("deliveryText").innerHTML		=	stockEigenInfo;
		}
	} else {
		document.getElementById("txtStock").innerHTML    	= "voorraad:<span class=\"stockFalse\" style=\"cursor: hand; cursor: pointer;\" onclick=\"window.location.href=window.location.href + '#'; javascript:checkMainStock()\">" + stock + "</span>";
		document.getElementById("stockText").innerHTML    = 'Product is momenteel niet op voorraad.';
		document.getElementById("deliveryText").innerHTML = 'Verwachte voorraad datum: ' + deliveryDate;
		document.getElementById("stockText").className		= 'stockFalse';
	}


	document.getElementById("stockText").style.display 		= '';
	document.getElementById("deliveryText").style.display = '';
	document.getElementById("orderForm").style.display 		= '';

}

///////////////////////////////////////////////////////////////////////////////////////////////////

function displayPriceNotOk(){

	document.getElementById("txtExtax").innerHTML      = '';
	document.getElementById("txtIntax").innerHTML      = '';
	document.getElementById("txtStock").innerHTML      = '';
	document.getElementById("orderForm").style.display = 'none';

}


///////////////////////////////////////////////////////////////////////////////////////////////////


/* ************************************************************************************* *\
 * The MIT License
 * Copyright (c) 2007 Fabio Zendhi Nagao - http://zend.lojcomm.com.br
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this
 * software and associated documentation files (the "Software"), to deal in the Software
 * without restriction, including without limitation the rights to use, copy, modify,
 * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the following
 * conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies
 * or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 * 
\* ************************************************************************************* */
//class="fValidate['required']
//fValidate['required','alpha','alphanum','integer','real','date','email','phone','url'} 

var fValidator = new Class({
	options: {
		msgContainerTag: "div",
		msgClass: "formError",

		styleNeutral: {"border-color": "#dbdfe6"},
		styleInvalid: {"border-color": "#e70000"},
		styleValid: {"border-color": "#0c0"},
		
		required: {type: "required", re: /[^.*]/, msg: "Dit is een verplicht veld"},
		agree: {type: "agree", msg: "U dient akkoord te gaan met de leveringsvoorwaarden en E-commerceovereenkomst"},
		alpha: {type: "alpha", re: /^[agree]+$/i, msg: "This field accepts alphabetic characters only."},
		alphanum: {type: "alphanum", re: /^[a-z0-9 ._-]+$/i, msg: "This field accepts alphanumeric characters only."},
		integer: {type: "integer", re: /^[-+]?\d+$/, msg: "Please enter a valid integer."},
		real: {type: "real", re: /^[-+]?\d*\.?\d+$/, msg: "Please enter a valid number."},
		date: {type: "date", re: /^((((0[13578])|([13578])|(1[02]))[\/](([1-9])|([0-2][0-9])|(3[01])))|(((0[469])|([469])|(11))[\/](([1-9])|([0-2][0-9])|(30)))|((2|02)[\/](([1-9])|([0-2][0-9]))))[\/]\d{4}$|^\d{4}$/, msg: "Please enter a valid date (mm/dd/yyyy)."},
		email: {type: "email", re: /^[a-z0-9._%-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i, msg: "U heeft geen (correct) email-adres ingevoerd"},
		email_reminder: {type: "email", re: /^[a-z0-9._%-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i, msg: ""},
	  phone: {type: "real", re: /^[0-9- ]+\d{4}$/, msg: "Vul hier uw telefoonnummer in. Minimaal 5 getallen. Voorbeeld: 020-3472323"},

		zip: {type: "zip", re: /^....../, msg: "U heeft geen (correct) postcode ingevoerd."},
		gender: {type: "gender", re: /^(heer|mevrouw|afdeling)/, msg: "Dit is een verplicht veld"}, 
		//url: {type: "url", re: /^(http|https|ftp)\:\/\/[a-z0-9\-\.]+\.[a-z]{2,3}(:[a-z0-9]*)?\/?([a-z0-9\-\._\?\,\'\/\\\+&amp;%\$#\=~])*$/i, msg: "Please enter a valid url."},
		confirm: {type: "confirm", msg: "Wachtwoorden zijn niet gelijk"},

		onValid: Class.empty,
		onInvalid: Class.empty
	},

	initialize: function(form, options) {
		this.form = $(form);
		this.setOptions(options);

		this.fields = this.form.getElements("*[class^=fValidate]");
		this.validations = [];

		this.fields.each(function(element) {
			if(!this._isChildType(element)) element.setStyles(this.options.styleNeutral);
			element.cbErr = 0;
			var classes = element.getProperty("class").split(' ');
			classes.each(function(klass) {
				if(klass.match(/^fValidate(\[.+\])$/)) {
					var aFilters = eval(klass.match(/^fValidate(\[.+\])$/)[1]);
					for(var i = 0; i < aFilters.length; i++) {
						if(this.options[aFilters[i]]) this.register(element, this.options[aFilters[i]]);
						if(aFilters[i].charAt(0) == '=') this.register(element, $extend(this.options.confirm, {idField: aFilters[i].substr(1)}));
					}
				}
			}.bind(this));
		}.bind(this));

		this.form.addEvents({
			"submit": this._onSubmit.bind(this),
			"reset": this._onReset.bind(this)
		});
	},

	register: function(field, options) {
		field = $(field);
		this.validations.push([field, options]);
		field.addEvent("blur", function() {
			this._validate(field, options);
		}.bind(this));
	},

	_isChildType: function(el) {
		//var elType = el.type.toLowerCase();
		//if((elType == "radio") || (elType == "checkbox")) return true;
		//return false;
	},

	_validate: function(field, options) {
		switch(options.type) {
			case "confirm":
				if($(options.idField).getValue() == field.getValue()) this._msgRemove(field, options);
				else this._msgInject(field, options);
				break;
			case "agree":
				if($('agree').checked == true){
					$('agreeLabel').setStyle('border', '#ffffff 1px solid')
					this._msgRemove(field, options);
					}
				else {
					this._msgInject(field, options);
					$('agreeLabel').setStyle('border', '#e70000 1px solid')
				}
				break;
			default:
				if(options.re.test(field.getValue())) this._msgRemove(field, options);
				else this._msgInject(field, options);
		}
	},

	_validateChild: function(child, options) {
		var nlButtonGroup = this.form[child.getProperty("name")];
		var cbCheckeds = 0;
		var isValid = true;
 		for(var i = 0; i < nlButtonGroup.length; i++) {
			if(nlButtonGroup[i].checked) {
				cbCheckeds++;
				if(!options.re.test(nlButtonGroup[i].getValue())) {
					isValid = false;
					break;
				}
			}
		}
		if(cbCheckeds == 0 && options.type == "required") isValid = false;
		if(isValid) this._msgRemove(child, options);
		else this._msgInject(child, options);
	},

	_msgInject: function(owner, options) {
		if(!$(owner.getProperty("id") + options.type +"_msg")) {
			var msgContainer = new Element(this.options.msgContainerTag, {"id": owner.getProperty("id") + options.type +"_msg", "class": this.options.msgClass})
				.setHTML(options.msg)
				.setStyle("opacity", 0)
				.injectAfter(owner)
				.effect("opacity", {
					duration: 500,
					transition: Fx.Transitions.linear
				}).start(0, 1);
			owner.cbErr++;
			this._chkStatus(owner, options);
			$('formErrorHidden').setStyle('display', 'block')
			window.location.href = '#Top';
		}
	},

	_msgRemove: function(owner, options, isReset) {
		isReset = isReset || false;
		if($(owner.getProperty("id") + options.type +"_msg")) {
			var el = $(owner.getProperty("id") + options.type +"_msg");
			el.effect("opacity", {
				duration: 500,
				transition: Fx.Transitions.linear,
				onComplete: function() {el.remove()}
			}).start(1, 0);
			if(!isReset) {
				owner.cbErr--;
				this._chkStatus(owner, options);
			}
		}
	},

	_chkStatus: function(field, options) {
		if(field.cbErr == 0) {
			field.effects({duration: 500, transition: Fx.Transitions.linear}).start(this.options.styleValid);
			this.fireEvent("onValid", [field, options], 50);
		} else {
			field.effects({duration: 500, transition: Fx.Transitions.linear}).start(this.options.styleInvalid);
			this.fireEvent("onInvalid", [field, options], 50);
		}
	},

	_onSubmit: function(event) {
		event = new Event(event);
		var isValid = true;

		this.validations.each(function(array) {
			if(this._isChildType(array[0])) this._validateChild(array[0], array[1]);
			else this._validate(array[0], array[1]);
			if(array[0].cbErr > 0) isValid = false;
		}.bind(this));

		if(!isValid) event.stop();
		return isValid;
	},

	_onReset: function() {
		this.validations.each(function(array) {
			if(!this._isChildType(array[0])) array[0].setStyles(this.options.styleNeutral);
			array[0].cbErr = 0;
			this._msgRemove(array[0], array[1], true);
		}.bind(this));
	}
});
fValidator.implement(new Events); // Implements addEvent(type, fn), fireEvent(type, [args], delay) and removeEvent(type, fn)
fValidator.implement(new Options);// Implements setOptions(defaults, options)
// Password strength meter v2.0
// Matthew R. Miller - 2007
// www.codeandcoffee.com
// Based off of code from:
//  http://www.intelligent-web.co.uk
//  http://www.geekwisdom.com/dyn/passwdmeter

/*
	Password Strength Algorithm:
	
	Password Length:
		5 Points: Less than 4 characters
		10 Points: 5 to 7 characters
		25 Points: 8 or more
		
	Letters:
		0 Points: No letters
		10 Points: Letters are all lower case
		20 Points: Letters are upper case and lower case

	Numbers:
		0 Points: No numbers
		10 Points: 1 number
		20 Points: 3 or more numbers
		
	Characters:
		0 Points: No characters
		10 Points: 1 character
		25 Points: More than 1 character

	Bonus:
		2 Points: Letters and numbers
		3 Points: Letters, numbers, and characters
		5 Points: Mixed case letters, numbers, and characters
		
	Password Text Range:
	
		>= 90: Very Secure
		>= 80: Secure
		>= 70: Very Strong
		>= 60: Strong
		>= 50: Average
		>= 25: Weak
		>= 0: Very Weak
		
*/


// Settings
// -- Toggle to true or false, if you want to change what is checked in the password
var m_strUpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var m_strLowerCase = "abcdefghijklmnopqrstuvwxyz";
var m_strNumber = "0123456789";
var m_strCharacters = "!@#$%^&*?_~"

// Check password
function checkPassword(strPassword)
{
	// Reset combination count
	var nScore = 0;
	
	// Password length
	// -- Less than 4 characters
	if (strPassword.length < 5)
	{
		nScore += 5;
	}
	// -- 5 to 7 characters
	else if (strPassword.length > 4 && strPassword.length < 8)
	{
		nScore += 10;
	}
	// -- 8 or more
	else if (strPassword.length > 7)
	{
		nScore += 25;
	}

	// Letters
	var nUpperCount = countContain(strPassword, m_strUpperCase);
	var nLowerCount = countContain(strPassword, m_strLowerCase);
	var nLowerUpperCount = nUpperCount + nLowerCount;
	// -- Letters are all lower case
	if (nUpperCount == 0 && nLowerCount != 0) 
	{ 
		nScore += 10; 
	}
	// -- Letters are upper case and lower case
	else if (nUpperCount != 0 && nLowerCount != 0) 
	{ 
		nScore += 20; 
	}
	
	// Numbers
	var nNumberCount = countContain(strPassword, m_strNumber);
	// -- 1 number
	if (nNumberCount == 1)
	{
		nScore += 10;
	}
	// -- 3 or more numbers
	if (nNumberCount >= 3)
	{
		nScore += 20;
	}
	
	// Characters
	var nCharacterCount = countContain(strPassword, m_strCharacters);
	// -- 1 character
	if (nCharacterCount == 1)
	{
		nScore += 10;
	}	
	// -- More than 1 character
	if (nCharacterCount > 1)
	{
		nScore += 25;
	}
	
	// Bonus
	// -- Letters and numbers
	if (nNumberCount != 0 && nLowerUpperCount != 0)
	{
		nScore += 2;
	}
	// -- Letters, numbers, and characters
	if (nNumberCount != 0 && nLowerUpperCount != 0 && nCharacterCount != 0)
	{
		nScore += 3;
	}
	// -- Mixed case letters, numbers, and characters
	if (nNumberCount != 0 && nUpperCount != 0 && nLowerCount != 0 && nCharacterCount != 0)
	{
		nScore += 5;
	}
	
	
	return nScore;
}
 
// Runs password through check and then updates GUI 
function runPassword(strPassword, strFieldID) 
{
	// Check password
	var nScore = checkPassword(strPassword);
	
	 // Get controls
    	var ctlBar = document.getElementById(strFieldID + "Bar"); 
    	var ctlText = document.getElementById(strFieldID + "Text");
    	if (!ctlBar || !ctlText)
    		return;
    	
    	// Set new width
    	ctlBar.style.width = nScore + "%";

 	// Color and text
	// -- Very Secure
 	if (nScore >= 90)
 	{
 		var strText = "Zeer veilig";
 		var strColor = "#00d500";
 	}
 	// -- Secure
 	else if (nScore >= 80)
 	{
 		var strText = "Veilig";
 		var strColor = "#009900";
	}
	// -- Very Strong
 	else if (nScore >= 70)
 	{
 		var strText = "Goed";
 		var strColor = "#ffcc00";
	}
	// -- Strong
 	else if (nScore >= 60)
 	{
 		var strText = "Gemiddeld";
 		var strColor = "#039ed8";
	}
	// -- Average
 	else if (nScore >= 50)
 	{
 		var strText = "Redelijk";
 		var strColor = "#202b60";
	}
	// -- Weak
 	else if (nScore >= 25)
 	{
 		var strText = "Onveilig";
 		var strColor = "#ff6600";
	}
	// -- Very Weak
 	else
 	{
 		var strText = "Zeer onveilig";
 		var strColor = "#e70000";
	}
	ctlBar.style.backgroundColor = strColor;
	ctlText.innerHTML = "<span style='color: " + strColor + ";'>" + strText + "</span>";
}
 
// Checks a string for a list of characters
function countContain(strPassword, strCheck)
{ 
	// Declare variables
	var nCount = 0;
	
	for (i = 0; i < strPassword.length; i++) 
	{
		if (strCheck.indexOf(strPassword.charAt(i)) > -1) 
		{ 
	        	nCount++;
		} 
	} 
 
	return nCount; 
} 
 
 
 
 
 


var agt = navigator.userAgent.toLowerCase(); 
var is_mobile = ( (agt.indexOf("blacknerry") != -1) 
                || (agt.indexOf("nokia") != -1) 
                || (agt.indexOf("webtv") != -1) 
                || (agt.indexOf("windows ce") != -1) 
                || (agt.indexOf("microsoft pocket internet explorer") != -1) 
                || (agt.indexOf("up") != -1));
if (is_mobile) {
  document.write('<a href="http://www.centralpoint.mobi" title="klik hier om naar centralpoint.mobi te gaan">klik hier om naar centralpoint.mobi te gaan</a>');
}/* URL to the PHP page called for receiving suggestions for a keyword*/
var getFunctionsUrl = "/suggest.php?keyword=";
/* URL for seeing the results for the selected suggestion */
var phpHelpUrl="/?page=search&reset=1&search=";
/* the keyword for which an HTTP request has been  */
var httpRequestKeyword = "";
/* the last keyword for which suggests have been requested */
var userKeyword = "";
/* number of suggestions received as results for the keyword */
var suggestions = 0;
/* the maximum number of characters to be displayed for a suggestion */
var suggestionMaxLength = 30;
/* flag that indicates if the up or down arrow keys were pressed
   the last time a keyup event occurred  */
var isKeyUpDownPressed = false;
/* the last suggestion that has been used for autocompleting the keyword */
var autocompletedKeyword = "";
/* flag that indicates if there are results for the current requested keyword*/
var hasResults = false;
/* the identifier used to cancel the evaluation with the clearTimeout method. */
var timeoutId = -1;
/* the currently selected suggestion (by arrow keys or mouse)*/
var position = -1;
/* cache object containing the retrieved suggestions for different keywords */
var oCache = new Object();
/* the minimum and maximum position of the visible suggestions */
var minVisiblePosition = 0;
var maxVisiblePosition = 9;
// when set to true, display detailed error messages
var debugMode = true;
/* the XMLHttp object for communicating with the server */
var xmlHttpGetSuggestions = createXmlHttpRequestObject();
/* the onload event is handled by our init function */
window.onload = init_suggestions;

var rubbish	=	'                                                                     ';
var init	=	0;
var nonFoundWord	=	'Typ uw zoekterm';
var sugestHeightLimit	=	180;
var	suggestionsLimit	=	12;
var defaultWidth			=	"180px";
// creates an XMLHttpRequest instance
function createXmlHttpRequestObject() 
{
  // will store the reference to the XMLHttpRequest object
  var xmlHttp;
  // this should work for all browsers except IE6 and older
  try
  {
    // try to create XMLHttpRequest object
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    // assume IE6 or older
    var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
                                    "MSXML2.XMLHTTP.5.0",
                                    "MSXML2.XMLHTTP.4.0",
                                    "MSXML2.XMLHTTP.3.0",
                                    "MSXML2.XMLHTTP",
                                    "Microsoft.XMLHTTP");
    // try every prog id until one works
    for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) 
    {
      try 
 
      { 
        // try to create XMLHttpRequest object
        xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
      } 
      catch (e) {}
    }
  }
  // return the created object or display an error message
  if (!xmlHttp)
    alert("Error creating the XMLHttpRequest object.");
  else 
    return xmlHttp;
}

/* function that initializes the page */
function init_suggestions() 
{  
  // retrieve the input control for the keyword
  var oKeyword = document.getElementById("search");    
  // prevent browser from starting the autofill function
  oKeyword.setAttribute("autocomplete", "off");  
  // reset the content of the keyword and set the focus on it
//  oKeyword.value = "";
	hideSuggestions();
//  oKeyword.focus();
  // set the timeout for checking updates in the keyword's value
  init = 1;
  setTimeout("checkForChanges()", 500);
} 

/* function that adds to a keyword an array of values */
function addToCache(keyword, values)
{
  // create a new array entry in the cache
  oCache[keyword] = new Array();
  // add all the values to the keywo;rd's entry in the cache
  for(i=0; i<values.length; i++)
    oCache[keyword][i] = values[i];
}

/* 
   function that checks to see if the keyword specified as parameter is in 
   the cache or tries to find the longest matching prefixes in the cache 
   and adds them in the cache for the current keyword parameter
*/
function checkCache(keyword)
{
  // check to see if the keyword is already in the cache
  if(oCache[keyword])
    return true;
  // try to find the biggest prefixes
  for(i=keyword.length-2; i>=0; i--)
  {
    // compute the current prefix keyword 
    var currentKeyword = keyword.substring(0, i+1);
    // check to see if we have the current prefix keyword in the cache
    if(oCache[currentKeyword])
    {            
      // the current keyword's results already in the cache
      var cacheResults = oCache[currentKeyword];
      // the results matching the keyword in the current cache results
      var keywordResults = new Array();
      var keywordResultsSize = 0;            
      // try to find all matching results starting with the current prefix
      for(j=0;j<cacheResults.length;j++)
      {
 
        if(cacheResults[j].indexOf(keyword) == 0)               
          keywordResults[keywordResultsSize++] = cacheResults[j];
      }      
      // add all the keyword's prefix results to the cache
      addToCache(keyword, keywordResults);      
      return true;  
    }
  }
  // no match found
  return false;
}

/* initiate HTTP request to retrieve suggestions for the current keyword */
function getSuggestions(keyword) 
{  
  /* continue if keyword isn't null and the last pressed key wasn't up or 
     down */
  if(keyword != "" && !isKeyUpDownPressed)
  {
    // check to see if the keyword is in the cache
    isInCache = false;	//checkCache(keyword);
    // if keyword is in cache...
    if(isInCache == true)          
    {   
      // retrieve the results from the cache          
      httpRequestKeyword=keyword;
      userKeyword=keyword;     
      // display the results in the cache
      displayResults(keyword, oCache[keyword],new Array());                          
    }
    // if the keyword isn't in cache, make an HTTP request
    else    
    {    
      if(xmlHttpGetSuggestions)
      { 
        try
        {
          /* if the XMLHttpRequest object isn't busy with a previous
             request... */
          if (xmlHttpGetSuggestions.readyState == 4 || 
              xmlHttpGetSuggestions.readyState == 0) 
          {    
            httpRequestKeyword = keyword;
            userKeyword = keyword;
            xmlHttpGetSuggestions.open("GET",	getFunctionsUrl + encodeURIComponent(escape(keyword)), true);
//						alert(getFunctionsUrl + encodeURIComponent(escape(keyword)));
            xmlHttpGetSuggestions.onreadystatechange = 
                                                handleGettingSuggestions; 
            xmlHttpGetSuggestions.send(null);
          }
          // if the XMLHttpRequest object is busy...
          else
          {
            // retain the keyword the user wanted             
            userKeyword = keyword;
            // clear any previous timeouts already set
            if(timeoutId != -1)
              clearTimeout(timeoutId);          
            // try again in 0.5 seconds     
            timeoutId = setTimeout("getSuggestions(userKeyword);", 5);
          }
        }
        catch(e)
 
        {
          displayError("Can't connect to server:\n" + e.toString());
        }
      }
    }    
  }
}

/* transforms all the children of an xml node into an array */
function xmlToArray(resultsXml)
{
  // initiate the resultsArray
  var resultsArray= new Array();  
  // loop through all the xml nodes retrieving the content  
  for(i=0;i<resultsXml.length;i++)
    resultsArray[i]=resultsXml.item(i).firstChild.data;
  // return the node's content as an array
  return resultsArray;
}

/* handles the server's response containing the suggestions 
   for the requested keyword  */
function handleGettingSuggestions() 
{
  //if the process is completed, decide what to do with the returned data
  if (xmlHttpGetSuggestions.readyState == 4) 
  {
    // only if HTTP status is "OK"
    if (xmlHttpGetSuggestions.status == 200) 
    { 
      try
      {
        // process the server's response
        updateSuggestions();
      }
      catch(e)
      {
        // display the error message
        displayError(e.toString()); 
      }  
    } 
    else
    {
      displayError("There was a problem retrieving the data:\n" + 
                   xmlHttpGetSuggestions.statusText);
    }       
  }
}

/* function that processes the server's response */
function updateSuggestions()
{
  // retrieve the server's response 
  var response = xmlHttpGetSuggestions.responseText;
  // server error?
  if (response.indexOf("ERRNO") >= 0 
      || response.indexOf("error:") >= 0
      || response.length == 0)
    throw(response.length == 0 ? "Void server response." : response);
  // retrieve the document element
  response = xmlHttpGetSuggestions.responseXML.documentElement;
  // initialize the new array of functions' names
  nameArray = new Array();
	cntArray	=	new Array();
	originArray = new Array();
	typeArray = new Array();
	urlArray	=	new Array();
  // check to see if we have any results for the searched keyword
 
  if(response.childNodes.length)
  {
    /* we retrieve the new functions' names from the document element as 
       an array */

		var nameElements = response.getElementsByTagName("name");

		for (i=0; i<nameElements.length; i++) {
			typeArray.push(nameElements[i].attributes.getNamedItem('type').value);
			urlArray.push(nameElements[i].attributes.getNamedItem('url').value);
		}

    nameArray = xmlToArray(nameElements);
		cntArray	=	xmlToArray(response.getElementsByTagName("cnt"));
		originArray = xmlToArray(response.getElementsByTagName("origin"));

  }
  // check to see if other keywords are already being searched for
  if(httpRequestKeyword == userKeyword)    
  {
    // display the results array
    displayResults(httpRequestKeyword, nameArray, cntArray, typeArray, urlArray, originArray);
  }
  else
  {
    // add the results to the cache
    // we don't need to display the results since they are no longer useful
    addToCache(httpRequestKeyword, nameArray);              
  }
}

/* populates the list with the current suggestions */
function displayResults(keyword, results_array, cnt_array, type_array, url_array, origin_array) 
{  
  // start building the HTML table containing the results  
	var div = ""; 
	var current_i = -1;
  // if the searched for keyword is not in the cache then add it to the cache
  if(!oCache[keyword] && keyword)
    addToCache(keyword, results_array);
  // if the array of results is empty display a message
  if(results_array.length == 0)
  {
		div += "<table style=\"color:red;overflow: auto\"><tr><td><b><i>Andere klanten zochten:</i></b></td></tr>";
    div += "<tr><td>No results found for <strong>" + keyword + 
           "</strong></td></tr>";
    // set the flag indicating that no results have been found 
    // and reset the counter for results
    hasResults = false;
    suggestions = 0;
  }
  // display the results
  else
  {
    // resets the index of the currently selected suggestion
    position = -1;
    // resets the flag indicating whether the up or down key has been pressed
    isKeyUpDownPressed = false;
    /* sets the flag indicating that there are results for the searched 
       for keyword */
    hasResults = true;
    // get the number of results from the cache
    suggestions = oCache[keyword].length;
    // loop through all the results and generate the HTML list of results
    for (var i=0; i<oCache[keyword].length; i++) 
    {  
			if (type_array[i] != current_i) {
				if (type_array[i] == 1) {
					if (div != "") {div += "</table>";}
					div += "<table style=\"color:red;\"><tr><td><b><i>Laatste nieuws:</i></b></td></tr>";
				} else if (type_array[i] == 2) {
					if (div != "") {div += "</table>";}
					div += "<table style=\"color:red;\"><tr><td><b><i>Acties en aanbiedingen:</i></b></td></tr>";
				} else if (type_array[i] == 0) {
					if (div != "") {div += "</table>";}
					div += "<table style=\"color:red;\"><tr><td><b><i>Andere klanten zochten:</i></b></td></tr>";
				}
				current_i = type_array[i];
			}
      // retrieve the current function
      crtFunction = oCache[keyword][i];
      // set the string link for the for the current function 
      // to the name of the function
      crtFunctionLink = crtFunction;
      // replace the _ with - in the string link
//      while(crtFunctionLink.indexOf("_") !=-1)
//        crtFunctionLink = crtFunctionLink.replace("_","-");
      // start building the HTML row that contains the link to the 
      // PHP help page of the current function
			if (i+1 >= oCache[keyword].length) {
				div += "<tr style=\"line-height: 1.3\" id='tr" + i + 
             "' onclick='location.href=document.getElementById(\"a" + i + 
             "\").href;' onmouseover='handleOnMouseOver(this);' " + 
             "onmouseout='handleOnMouseOut(this);'>" + 
             "<td align='left'><a name= '"+crtFunctionLink+"' onClick=\"document.getElementById('search').value = document.getElementById('a' + position).name + rubbish;\" id='a" + i + 
             "' href='" + (url_array[i] == ''?phpHelpUrl + encodeURIComponent(crtFunctionLink):url_array[i]) + "";
			} else {
				div += "<tr id='tr" + i + 
             "' onclick='location.href=document.getElementById(\"a" + i + 
             "\").href;' onmouseover='handleOnMouseOver(this);' " + 
             "onmouseout='handleOnMouseOut(this);'>" + 
             "<td align='left'><a name= '"+crtFunctionLink+"' onClick=\"document.getElementById('search').value = document.getElementById('a' + position).name + rubbish;\" id='a" + i + 
             "' href='" + (url_array[i] == ''?phpHelpUrl + encodeURIComponent(crtFunctionLink):url_array[i]) + "";
			}
      // check to see if the current function name length exceeds the maximum 
      // number of characters that can be displayed for a function name
			if (type_array[i] != 0) {
				crtFunction = origin_array[i];
				tmpKeyword = "";
			} else {
				tmpKeyword = httpRequestKeyword;
			}
      if(crtFunction.length <= suggestionMaxLength)
      {
        // bold the matching prefix of the function name and of the keyword
        div += "'><b>" + 
               crtFunction.substring(0, tmpKeyword.length) + 
               "</b>"
        div += crtFunction.substring(tmpKeyword.length, 
                                     crtFunction.length) + 
               "</a></td></tr>";
      }
      else
      {
        // check to see if the length of the current keyword exceeds 
        // the maximum number of characters that can be displayed
        if(tmpKeyword.length < suggestionMaxLength)
        {
          /* bold the matching prefix of the function name and that of the 
             keyword */
          div += "'><b>" + 
                 crtFunction.substring(0, tmpKeyword.length) + 
                 "</b>"
					if (type_array[i] != 0) {
						div += crtFunction.substring(tmpKeyword.length,
								suggestionMaxLength - 5) + " ..." +
							"</a></td></tr>";   
					}	else {
	          div += crtFunction.substring(tmpKeyword.length,
                                       suggestionMaxLength) + 
                 "</a></td></tr>";   
					}
        }
        else
        {
          // bold the entire function name
					if (type_array[i] != 0) {
						div += "'><b>" + 
                 crtFunction.substring(0,suggestionMaxLength - 5) + " ..." +
                 "</b></td></tr>"          
					} else {
						div += "'><b>" + 
                 crtFunction.substring(0,suggestionMaxLength) + 
                 "</b></td></tr>"          
					}
        }
      }
    }
  }
  // end building the HTML table
	
	//div += "<tr id='tr3' style=\"line-height: 0.5\"><td align='left'><a name= 'apple introduceert mediabox apple tv' id='a3' href='/?page=news&nid=2624'>&nbsp;</a></td><td></td></tr>";
	
  div += "</table>";
  if (suggestions !=0){
  // retrieve the suggest and scroll object
  var oSuggest = document.getElementById("suggest");  
  var oScroll = document.getElementById("scroll");
	if (suggestions > suggestionsLimit)	{	
		oScroll.style.height	=	sugestHeightLimit.toString() + "px";
		oScroll.style.width		=	defaultWidth;	
	} else {
		oScroll.style.height	=	'auto';
		oScroll.style.width	=	"auto";
	}
  // scroll to the top of the list
  oScroll.scrollTop = 0;
  // update the suggestions list and make it visible
  oSuggest.innerHTML = div;
  oScroll.style.visibility = "visible";
	oScroll.style.display	=	"";
	oScroll.style.left	=	offsetPosition(document.getElementById("search"))[0];


  // if we had results we apply the type ahead for the current keyword
  if(results_array.length > 0)
    autocompleteKeyword();      
	}else{
		hideSuggestions();		
	}
}

function offsetPosition(element) {
	var offsetLeft = 0, offsetTop = 0;
	do {
		offsetLeft += element.offsetLeft;
		offsetTop  += element.offsetTop;
		} while (element = element.offsetParent);
	return [offsetLeft, offsetTop];
}

/* function that periodically checks to see if the typed keyword has changed */
function checkForChanges()
{
  // retrieve the keyword object
  var keyword = document.getElementById("search").value;
  // check to see if the keyword is empty
  if(keyword == "" || init == 1 || keyword == nonFoundWord)
  {
		keyword	=	'';
    // hide the suggestions
    hideSuggestions();
    // reset the keywords 
    userKeyword="";
    httpRequestKeyword="";
  }
  // set the timer for a new check 
  setTimeout("checkForChanges()", 20);
  // check to see if there are any changes
//alert("userKeyword="+userKeyword+" keyword="+keyword+"autocompletedKeyword="+autocompletedKeyword);
  if((userKeyword != keyword) && (autocompletedKeyword != keyword || 1) && (!isKeyUpDownPressed)){
    // update the suggestions
    getSuggestions(keyword);
	}
}

/* function that handles the keys that are pressed */
function handleKeyUp(e) 
{
  // get the event
  e = (!e) ? window.event : e;
  // get the event's target
  target = (!e.target) ? e.srcElement : e.target;
  if (target.nodeType == 3) 
    target = target.parentNode;
  // get the character code of the pressed button
  code = (e.charCode) ? e.charCode :
       ((e.keyCode) ? e.keyCode :
       ((e.which) ? e.which : 0));
  // check to see if the event was keyup
  if (e.type == "keyup") 
  {    
    isKeyUpDownPressed =false; 
    // check to see we if are interested in the current character
    if ((code < 13 && code != 8) || 
        (code >=14 && code < 32) || 
        (code >= 33 && code <= 46 && code != 38 && code != 40) || 
        (code >= 112 && code <= 123)) 
    {
      // simply ignore non-interesting characters
    }
    else
    /* if Enter is pressed we jump to the PHP help page of the current 
       function */
    init = 0;
    if(code == 13)
    {
      // check to see if any function is currently selected
      if(position>0)
      {
				document.getElementById('search').value	=	document.getElementById("a" + position).name + rubbish;
        location.href = document.getElementById("a" + position).href;
      }        
    }        
    else
    // if the down arrow is pressed we go to the next suggestion
      if(code == 40)
      {                   
        newTR=document.getElementById("tr"+(++position));
        oldTR=document.getElementById("tr"+(--position));
        // deselect the old selected suggestion   
        if(position>=0 && position<suggestions-1)
          oldTR.className = "";
 
        // select the new suggestion and update the keyword
        if(position < suggestions - 1)
        {
          newTR.className = "highlightrow";
          updateKeywordValue(newTR);
          position++;         
        }     
        e.cancelBubble = true;
        e.returnValue = false;
        isKeyUpDownPressed = true;        
        // scroll down if the current window is no longer valid
        if(position > maxVisiblePosition)
        {   
          oScroll = document.getElementById("scroll");
          oScroll.scrollTop += 18;
          maxVisiblePosition += 1;
          minVisiblePosition += 1;
        }
      }
      else
      // if the up arrow is pressed we go to the previous suggestion
      if(code == 38)
      {       
        newTR=document.getElementById("tr"+(--position));
        oldTR=document.getElementById("tr"+(++position));
        // deselect the old selected position
        if(position>=0 && position <= suggestions - 1)
        {       
          oldTR.className = "";
        }
        // select the new suggestion and update the keyword
        if(position > 0)
        {
          newTR.className = "highlightrow";
          updateKeywordValue(newTR);
          position--;
          // scroll up if the current window is no longer valid
          if(position<minVisiblePosition)
          {
            oScroll = document.getElementById("scroll");
            oScroll.scrollTop -= 18;
            maxVisiblePosition -= 1;
            minVisiblePosition -= 1;
          }   
        }     
        else
          if(position == 0)
            position--;
        e.cancelBubble = true;
        e.returnValue = false;
        isKeyUpDownPressed = true;  
      }     
  }
}

/* function that updates the keyword value with the value 
   of the currently selected suggestion */
function updateKeywordValue(oTr)
{
  // retrieve the keyword object
  var oKeyword = document.getElementById("search");
  // retrieve the link for the current function
  var crtLink = document.getElementById("a" + 
                            oTr.id.substring(2,oTr.id.length)).toString();
  // replace - with _ and leave out the .php extension
 
//  crtLink = crtLink.replace("-", "_");
//  crtLink = crtLink.substring(0, crtLink.length - 4);
  // update the keyword's value
//  oKeyword.value = unescape(crtLink.substring(phpHelpUrl.length, crtLink.length));
}

/* function that removes the style from all suggestions*/
function deselectAll()
{ 
  for(i=0; i<suggestions; i++)
  {
    var oCrtTr = document.getElementById("tr" + i);
    oCrtTr.className = "";    
  }
}

/* function that handles the mouse entering over a suggestion's area 
   event */
function handleOnMouseOver(oTr)
{
  deselectAll();  
  oTr.className = "highlightrow";  
  position = oTr.id.substring(2, oTr.id.length);
}

/* function that handles the mouse exiting a suggestion's area event */
function handleOnMouseOut(oTr)
{
  oTr.className = "";   
  position = -1;
}

/* function that escapes a string */
function encode(uri) 
{
  if (encodeURIComponent) 
  {
    return encodeURIComponent(uri);
  }

  if (escape) 
  {
    return escape(uri);
  }
}

/* function that hides the layer containing the suggestions */
function hideSuggestions()
{
//  if (oScroll == null) 	return;
  var oScroll = document.getElementById("scroll");
  oScroll.style.visibility = "hidden";  
	oScroll.style.display	=	"none";
}

/* function that selects a range in the text object passed as parameter */
function selectRange(oText, start, length)
{ 
	if (getNameBrouser() == 'opera')
		return;
  // check to see if in IE or FF
  if (oText.createTextRange) 
  {
    //IE
    var oRange = oText.createTextRange(); 
    oRange.moveStart("character", start); 
    oRange.moveEnd("character", length - oText.value.length); 
    oRange.select();
 
  }
  else 
    // FF
    if (oText.setSelectionRange) 
    {
      oText.setSelectionRange(start, length);
    } 
  //:oText.focus(); 
}

/* function that autocompletes the typed keyword*/
function autocompleteKeyword()
{
  //retrieve the keyword object
  var oKeyword = document.getElementById("search");
  // reset the position of the selected suggestion
  position=0;
  // deselect all suggestions
  deselectAll();
  // highlight the selected suggestion 
  document.getElementById("tr0").className="highlightrow";  
  // update the keyword's value with the suggestion
  updateKeywordValue(document.getElementById("tr0"));  
  // apply the type-ahead style
  selectRange(oKeyword,httpRequestKeyword.length,oKeyword.value.length);  
  // set the autocompleted word to the keyword's value
  autocompletedKeyword=oKeyword.value;
}

/* function that displays an error message */
function displayError(message)
{
return;
  // display error message, with more technical details if debugMode is true
  alert("Error accessing the server! "+
        (debugMode ? "\n" + message : ""));
}

/* get browser type */
function getNameBrouser() {
 var ua = navigator.userAgent.toLowerCase();
 if (ua.indexOf("msie") != -1 && ua.indexOf("opera") == -1 && ua.indexOf("webtv") == -1) {
    return "msie"
	}
	// Opera
 	if (ua.indexOf("opera") != -1) {
  	return "opera"
 	}
	// Gecko = Mozilla + Firefox + Netscape
  if (ua.indexOf("gecko") != -1) {
	  return "gecko";
	}
	// Safari
	if (ua.indexOf("safari") != -1) {
	  return "safari";
	}
	// Konqueror
	if (ua.indexOf("konqueror") != -1) {
		return "konqueror";
	}
	return "unknown";
}

function  getInternetExplorerVersion() {

    var rv = -1; // Return value assumes failure.

    if (navigator.appName == 'Microsoft Internet Explorer') {

        var ua = navigator.userAgent;

        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");

        if (re.exec(ua) != null)

            rv = parseFloat(RegExp.$1);

    }

    return rv;

}
/* ************************************************************************************* *\
 * The MIT License
 * Copyright (c) 2007 Fabio Zendhi Nagao - http://zend.lojcomm.com.br
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this
 * software and associated documentation files (the "Software"), to deal in the Software
 * without restriction, including without limitation the rights to use, copy, modify,
 * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the following
 * conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies
 * or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 * 
\* ************************************************************************************* */
// Set new slide nav to active
function setSlideNav(slideLink){
	$('slide0').removeClass('active');
	$('slide1').removeClass('active');
	$('slide2').removeClass('active');
	$('slide3').removeClass('active');
	
	$('slide0').addClass('nonActive');
	$('slide1').addClass('nonActive');
	$('slide2').addClass('nonActive');
	$('slide3').addClass('nonActive');
	
	if (slideLink == 4){
		slideLink = 0;
		}
	slideLink = 'slide'+slideLink
	$(slideLink).addClass('active');
	}


var iCarousel = new Class({
	options: {
		animation: {
			type: "fadeNscroll",// fadeNscroll, scroll, fade
			direction: "left",// if type = scroll, set: top || left
			amount: 1,// if type = scroll, set the amount to scroll
			transition: Fx.Transitions.Cubic.easeInOut,
			duration: 500,
			rotate: {
				type: "manual",// auto || manual
				interval: 1000,// if type = auto, set the interval (ms)
				onMouseOver: "stop"// if type = auto, set the onmouseover behavior: stop || proceed
			}
		},

		item: {
			klass: "item",
			size: 100
		},

		idPrevious: "previous",
		idNext: "next",
		idToggle: "toggle",

		onClickPrevious: Class.empty, 
		onMouseOverPrevious: Class.empty, 
		onClickNext: Class.empty,
		onPrevious: Class.empty,
		onNext: Class.empty,
		onGoTo: Class.empty
		
		
		
	},

	initialize: function(container, options) {
		this.setOptions(options);
		this.container = $(container);
		this.aItems = $A($$('.'+ this.options.item.klass));
		this.isMouseOver = false;

		if(this.options.idPrevious != "undefined" && $(this.options.idPrevious))
			$(this.options.idPrevious).addEvent("click", function(event) {
				new Event(event).stop();
				this._previous();
				this.fireEvent("onClickPrevious", this, 20, this.timer = $clear(this.timer));
			}.bind(this));// check if value is not "undefined" before start search the dom with $()
		if(this.options.idNext != "undefined" && $(this.options.idNext))
			$(this.options.idNext).addEvent("click", function(event) {
				new Event(event).stop();
				this._next();
				this.fireEvent("onClickNext", this, 20, this.timer = $clear(this.timer));
			}.bind(this));
		if(this.options.idToggle != "undefined" && $(this.options.idToggle))
			$(this.options.idToggle).addEvent("click", function(event) {new Event(event).stop(); this._toggle()}.bind(this));

		var oAn = this.options.animation; // short hand
		switch(this.options.animation.type.toLowerCase()) {
			case "fade":
				this.aItems.each(function(item) {
					item.fx = item.effect("opacity", {duration: oAn.duration, transition: oAn.transition});
					item.setStyle("opacity", 0);
					item.addEvents({
						"mouseenter": function() {
							this.isMouseOver = true;
							if(this.options.animation.rotate.type == "auto") this.timer = $clear(this.timer);
						}.bind(this),
						"mouseleave": function() {
							this.isMouseOver = false;
							if(this.options.animation.rotate.type == "auto") this.timer = this._autoRotate.periodical(this.options.animation.rotate.interval, this);
						}.bind(this)
					});
				}.bind(this));
				this.height = this.container.getStyle("height").toInt();
				this.atScreen = 0;
				this._animate(this.atScreen);
				break;

			default:
				(2).times(function() {
					this.aItems.each(function(item) {
						item.clone().injectInside(this.container);
					}.bind(this));
				}.bind(this));
				this.aItems = $A($$('.'+ this.options.item.klass));
				this.aItems.each(function(item) {
					item.addEvents({
						"mouseenter": function() {
							this.isMouseOver = true;
							if(this.options.animation.rotate.type == "auto") this.timer = $clear(this.timer);
						}.bind(this),
						"mouseleave": function() {
							this.isMouseOver = false;
							if(this.options.animation.rotate.type == "auto") this.timer = this._autoRotate.periodical(this.options.animation.rotate.interval, this);
						}.bind(this)
					});
				}.bind(this));
				this.fx = this.container.effects({duration: oAn.duration, transition: oAn.transition, wait: false});
				this.atScreen = this.aItems.length / 3;
				this.container.setStyle(oAn.direction, - this.atScreen * this.options.item.size);
				break;
		}

		if(this.options.animation.rotate.type == "auto") this.timer = this._autoRotate.periodical(this.options.animation.rotate.interval, this);
	},

	goTo: function(n) {
		switch(this.options.animation.type.toLowerCase()) {
			case "fade":
				var lastIndex = this.atScreen;
				this.atScreen = Math.abs(n % (this.aItems.length / 3));
				this._animate(this.atScreen, lastIndex);
				break;

			default:
				this.atScreen = Math.abs(n % (this.aItems.length / 3));
				this.atScreen += this.aItems.length / 3;
				this._animate(this.atScreen);
				break;
		}

		this.fireEvent("onGoTo", this, 20);
	},

	_previous: function() {
		switch(this.options.animation.type.toLowerCase()) {
			case "fade":
				var lastIndex = this.atScreen;
				this.atScreen -= this.options.animation.amount;
				if(this.atScreen < 0) this.atScreen = (this.aItems.length - 1);
				this._animate(this.atScreen, lastIndex);
				break;

			default:
				this.atScreen -= this.options.animation.amount;
				if(this.atScreen < this.aItems.length / 3) {
					this.container.setStyle(this.options.animation.direction, - this.options.item.size * this.aItems.length * 2 / 3);
					this.atScreen = this.aItems.length * 2 / 3 - this.options.animation.amount;
				}
				this._animate(this.atScreen);
				break;
		}

		this.fireEvent("onPrevious", this, 20);
	},

	_next: function() {
		switch(this.options.animation.type.toLowerCase()) {
			case "fade":
				var lastIndex = this.atScreen;
				this.atScreen += this.options.animation.amount;
				if(this.atScreen >= this.aItems.length) this.atScreen = 0;
				this._animate(this.atScreen, lastIndex);
				break;

			default:
				this.atScreen += this.options.animation.amount;
				if(this.atScreen > this.aItems.length * 2 / 3) {
					this.container.setStyle(this.options.animation.direction, - this.options.item.size * this.aItems.length / 3);
					this.atScreen = this.aItems.length / 3 + this.options.animation.amount;
				}
				this._animate(this.atScreen);
				break;
		}

		this.fireEvent("onNext", this, 20);
	},

	_toggle: function() {
		(this.container.getStyle("height").toInt() == 0) ?
			this.container.effect("height", { duration:1000, transition: Fx.Transitions.Sine.easeInOut }).start(this.height):
			this.container.effect("height", { duration:1000, transition: Fx.Transitions.Sine.easeInOut }).start(0);
	},

	_autoRotate: function() {
		if(this.options.animation.rotate.onMouseOver == "stop" && !this.isMouseOver) this._next();
	},

	_animate: function(a, b) {
	setSlideNav(this.atScreen-4)
	switch(this.options.animation.type) {
			case "fade":
				if($defined(b)) {
					this.aItems[b].fx.start(0).chain(function() {
					this.aItems[a].fx.start(1);}.bind(this));
				} else {
					this.aItems[a].fx.start(1);
				}
				break;

			case "scroll":
				var that = this;
				if(that.options.animation.direction == "top") {
					that.fx.start({"top" : - a * that.options.item.size});
				} else {
					that.fx.start({"left" : - a * that.options.item.size});
				}
				break;

			case "fadeNscroll":
				var that = this;
				if(that.options.animation.direction == "top") {
					that.fx.start({"opacity":0.75}).chain(function() {
						that.fx.start({"top" : - a * that.options.item.size}).chain(function() {
							that.fx.start({"opacity": 1});
						});
					});
				} else {
					that.fx.start({"opacity":0.75}).chain(function() {
						that.fx.start({"left" : - a * that.options.item.size}).chain(function() {
							that.fx.start({"opacity": 1});
						});
					});
				}
				break;
		}
	}
});
iCarousel.implement(new Events); // Implements addEvent(type, fn), fireEvent(type, [args], delay) and removeEvent(type, fn)
iCarousel.implement(new Options);// Implements setOptions(defaults, options)
