/* Utility functions */
var checkpricesCall = null;

function addEvent(obj, evType, fn, useCapture) { // By Scott Andrew
	if (obj.addEventListener) {
		obj.addEventListener(evType, fn, useCapture);
		return true;
	} else if (obj.attachEvent) {
		var r = obj.attachEvent('on' + evType, fn);
		return r;
	} else {
		obj['on' + evType] = fn;
	}
	return void (0);
}

// call it like this
//addEvent(window, 'load', scrollInit, false);
function element(id) {
	var e = false;
	if (document.getElementById) {
		e = document.getElementById(id);
	} else if (document.all) {
		e = document.all(id);
	}
	return e;
}
function displayValue() {
	var returnvalue = 'table';
	var offset = navigator.userAgent.indexOf('MSIE');
	if (offset != -1) {
		returnvalue = 'block';
	}
	return returnvalue;
}
function checkAfleveradres() {
	var radioparent = element('afleveradres');
	var subform = element('afleverform');
	if (radioparent) {
		var radios = radioparent.getElementsByTagName('input');
		if (radios) {
			for ( var i = 0; i < radios.length; i++) {
				var radio = radios[i];
				radio.onclick = function() {
					if (this.checked != false && this.value == 'anders') {
						subform.style.display = 'block';
					} else {
						subform.style.display = 'none';
					}
				}
			}
		}
	}
	return void (0);
}
function checkCondition(formid) {
	var form = element(formid);
	var check = element('akkoord');
	if (check) {
		if (check.checked == false) {
			alert('U bent niet akkoord met de algemene leveringsvoorwaarden');
			//check.className = 'error';
			check.parentNode.style.backgroundColor = '#ff3333';
			return false;
		} else {
			//check.className = '';
			check.parentNode.style.backgroundColor = 'transparent';
			if (form)
				form.submit();
		}
	}
	return false;
}
// login
function toPassword(objOldInput) {
	var objNewElement = document.createElement('input');
	var oldClass = (objOldInput.className) ? objOldInput.className : '';
	if (oldClass != '')
		objNewElement.setAttribute('class', oldClass);
	objNewElement.setAttribute('type', 'password');
	objNewElement.setAttribute('name', objOldInput.name);
	objOldInput.parentNode.replaceChild(objNewElement, objOldInput);
	toPassword.el = objNewElement;
	setTimeout('toPassword.el.focus()', 100);
	return true;
}
// menu.js
function hasULchildren(linode) {
	var uls = linode.getElementsByTagName('ul')[0];
	if (uls)
		return true;
	return false;
}
function efMenu(menuid, menutype) {
	var menudiv = element(menuid);
	var listitems = menudiv.getElementsByTagName('li');
	if (listitems) {
		for ( var i = 0; i < listitems.length; i++) {
			var listitem = listitems[i];
			if (hasULchildren(listitem)) {
				$(listitem).find('a').click(
					function(){
						if($(this).parent().find('ul').length > 0){
							return false;
						}
					}
				);
				listitem.onmouseover = function(e) {
					for ( var i = 0; i < this.childNodes.length; i++) {
						var child = this.childNodes[i];
						if (child.nodeName.toUpperCase() == 'A') {
							if (child.className.indexOf('active') != -1) {
								child.className = 'active mouse';
							} else {
								child.className = 'mouse';
							}
						}
						if (child.nodeName.toUpperCase() == 'UL') {
							child.style.visibility = 'visible';
						}
						if (child.nodeName.toUpperCase() == 'FORM') {
							child.style.display = 'block';
						}
					}
					return false;
				};
				// onmouseout function
				listitem.onmouseout = function(e) {
					for ( var i = 0; i < this.childNodes.length; i++) {
						var child = this.childNodes[i];
						if (child.nodeName.toUpperCase() == 'UL') {
							child.style.visibility = 'hidden';
						}
						if (child.nodeName.toUpperCase() == 'FORM') {
							child.style.display = 'none';
						}
						if (child.nodeName.toUpperCase() == 'A') {
							if (child.className.indexOf('active') != -1) {
								child.className = 'active';
							} else {
								child.className = '';
							}
						}
					}
					return false;
				};
			}
		}
	}
	return void (0);
}

function changePage(id) {
	var val = '';
	var selectbox = element(id);
	if (selectbox) {
		val = selectbox.options[selectbox.selectedIndex].value;
	}
	if (val != '') {
		document.location = val;
	}
}

function foldCatList() {
	var catList = element('categories');
	if (catList) {
		var catBoxen = catList.getElementsByTagName('H2');
		if (catBoxen) {
			for ( var i = 0; i < catBoxen.length; i++) {
				var catBox = catBoxen[i];
				catBox.onclick = function() {
					if (this.firstChild.className == 'active')
						this.firstChild.className = 'inactive';
					else
						this.firstChild.className = 'active';
					if (this.nextSibling) {
						if (this.nextSibling.style.display == 'none')
							this.nextSibling.style.display = 'block';
						else
							this.nextSibling.style.display = 'none';
					}
					return false;
				}
			}
		}
	}
	return false;
}

/* Better(?) Image cross fader (C)2004 Patrick H. Lauke aka redux */

var previousImage, currentImage, galleryImages, gallery, galleryId = 'beeldwissel';
function preInit() {
	if ((document.getElementById) && (gallery = document.getElementById(galleryId))) {
		gallery.style.visibility = "hidden";
		clearTimeout(preInitTimer);
	} else {
		preInitTimer = setTimeout("preInit()", 2);
	}
}
function fader(imageNumber, opacity) {
	var obj = galleryImages[imageNumber];
	if (obj.style.MozOpacity != null) {
		obj.style.MozOpacity = (opacity / 100);
	} else if (obj.style.opacity != null) {
		obj.style.opacity = (opacity / 100);
	} else if (obj.style.filter != null) {
		obj.style.filter = "alpha(opacity=" + opacity + ")";
	}
}

function fadeInit() {
	if (document.getElementById) {
		gallery = document.getElementById(galleryId);
		if (gallery) {
			galleryImages = gallery.childNodes;
			for (i = 0; i < galleryImages.length; i++) {
				galleryImages[i].style.position = 'absolute';
				//galleryImages[i].style.display='block';
				galleryImages[i].style.top = 0;
				galleryImages[i].style.zIndex = 0;
				fader(i, 0);
			}
			gallery.style.visibility = 'visible';
			currentImage = 0;
			previousImage = galleryImages.length - 1;
			opacity = 100;
			fader(currentImage, 100);
			window.setTimeout("crossfade(100)", 2500);
			return void (0);
		} else {
			return false;
		}
	} else {
		return false;
	}
}

function crossfade(opacity) {
	if (opacity < 101) {
		fader(currentImage, opacity);
		fader(previousImage, 100 - opacity * 4);
		opacity += 1;
		window.setTimeout("crossfade(" + opacity + ")", 20);
	} else {
		fader(previousImage, 0);
		previousImage = currentImage;
		currentImage += 1;
		if (currentImage >= galleryImages.length) {
			currentImage = 0;
		}
		galleryImages[previousImage].style.zIndex = 0;
		galleryImages[currentImage].style.zIndex = 3;
		opacity = 0;
		window.setTimeout("crossfade(" + opacity + ")", 5000);
	}
}
function showlistitems() {

	var listitems = document.getElementById('beeldwissel').childNodes;
	for ( var i = 0; i < listitems.length; i++) {
		listitems[i].style.display = 'block';
	}

}

function addStoreSlider() {
	$('#storeSlider').nivoSlider({
		effect: 'sliceDown', //Specify sets like: \'fold,fade,sliceDown\'
		pauseTime: 5000,
		startSlide: 0, //Set starting Slide (0 index)
		directionNav: false, //Next & Prev
		directionNavHide: true, //Only show on hover
		controlNav: true, //1,2,3...
		controlNavThumbs: false, //Use thumbnails for Control Nav
		controlNavThumbsFromRel: false, //Use image rel for thumbs
		controlNavThumbsSearch: '.jpg', //Replace this with...
		controlNavThumbsReplace: '_thumb.jpg', //...this in thumb Image src
		keyboardNav: true, //Use left & right arrows
		pauseOnHover: true
	//Stop animation while hovering
	});
}

function checkPrice(productId, amount, displayAmount){
	if(checkpricesCall != null){
		checkpricesCall.abort();
	}
	if(displayAmount == undefined){
		displayAmount = amount;
	}
	
	var products = new Array();
	var product = new Object();
	
	product.productId = productId;
	product.amount = amount;
	products.push(product);
	
	checkpricesCall = $.ajax({
		  url: '/AJAXcall/compram/getPrices?ajax=true',
		  data: 'products='+JSON.stringify(products),
		  type: 'POST',
		  success: function(xml){
			$(xml).find('product').each(function(index, item){				
				$('.shopContent [name="product_id"][value="'+$(item).find('productId').html()+'"]').closest('.shopContent').find('.price').html('&euro;&nbsp;'+calculateProductPrice(parseFloat($(item).find('price').html()), $(item).find('discount').html(), parseInt(displayAmount)));
			});
		},
		  dataType: 'XML'
		});
}

function updatePrices(products){
	if(checkpricesCall != null){
		checkpricesCall.abort();
	}
		
	checkpricesCall = $.ajax({
		  url: '/AJAXcall/compram/getPrices?ajax=true',
		  data: 'products='+JSON.stringify(products),
		  type: 'POST',
		  success: function(xml){
			$(xml).find('product').each(function(index, item){
				$('.shopContent [name="product_id"][value="'+$(item).find('productId').html()+'"]').parent().find('.basketItemTotal span').html('&euro;&nbsp;'+calculateProductPrice(parseFloat($(item).find('price').html()), $(item).find('discount').html(), parseInt($(item).find('amount').html())));
			});
		},
		  dataType: 'XML'
		});
}

/** Calculate the product price based on the discount percentage and the default price of the product */
function calculateProductPrice(intDefaultPrice, intDiscountPercentage, intAmount){
	var intProductPrice = false;
	/** Check if there is a discountPercentage set */
	if(intDiscountPercentage == undefined && isInt(intDiscounPercentage) != false){ intDiscountPercentage = 0; }
	/** Check if the default price is a valid integer/float value */
	if(isInt(intDefaultPrice) == true && isInt(intAmount) == true){
		intProductPrice = (intDefaultPrice * ( ( 100 - intDiscountPercentage ) / 100 )) * intAmount;
	}
		
	return accounting.formatMoney(accounting.toFixed(intProductPrice, 2), '', 2, ".", ",");
}

function isInt(n) { 
   if(typeof n == 'number' && Math.round(n) % 1 == 0) {
       return true;
   } else {
       return false;
   }
}

$(document).ready(function() {

	if($('.checkPrice').length){
		checkPrice($('.checkPrice').parent().find('[name="product_id"]').val(),1);
		
	}
	
	if($('.leftContentSelector').length){
		if($('.attributeMenu').find('.selected').length){
			$('.categoryMenu').hide();
			$('.attributeMenu').show();
			$('.leftContentSelector li').removeClass('active');
			$('.leftContentSelector li:eq(1)').addClass('active');
		}
		
		$('.leftContentSelector li').click(function(){
			$('.leftContentSelector li').removeClass('active');
			$(this).addClass('active');
			if($(this).index() == 0){
				$('.categoryMenu').show();
				$('.attributeMenu').hide();
			}
			if($(this).index() == 1){
				$('.categoryMenu').hide();
				$('.attributeMenu').show();
			}
		});
	}
	
	if($('.updatePrices').length){
		var products = new Array();
		
		$('.updatePrices').parent().find('[name="product_id"]').each(function(index,item){
			var product = new Object();
//			console.debug($(item));
			product.productId = $(item).val();
			product.amount = 1;
			products.push(product);
		});
//		console.debug(products);
		updatePrices(products);
		
	}
	
	var first = 0;
	var speed = 1000;
	var pause = 10000;
	var speedCarousel = 2000;
	var pauseCarousel = 9000;

	function removeFirst() {
		var first = $('ul#listticker li:first');
		$('ul#listticker li:first').animate({
			opacity: 0.1
		}, speed, function() {
			$(this).remove();
			addLast(first);
		});

		//$('ul#listticker li:first')
		//.animate({opacity: 0}, speed)
		//.fadeOut('slow', function() {$(this).remove();});
	}

	function addLast(first) {
		$(first).animate({
			opacity: 1
		}, 0);
		$('ul#listticker').append(first)

		//$('ul#listticker li:last')
		//.animate({opacity: 1}, speed)
		//.fadeIn('slow')
	}

	function moveLeft() {
		$('ul#myCarousel').animate({
			marginLeft: -234
		}, speedCarousel, function() {
			var First = $('ul#myCarousel li:first');
			$('ul#myCarousel li:first').remove();
			$('ul#myCarousel').animate({
				marginLeft: 0
			}, 0);
			$('ul#myCarousel').append(First);
		});
	}

	function moveDown() {
		var First = $('#beeldwissel').find('li:first');
		var Next = $('#beeldwissel').find('li:first').next();
		$(First).animate({
			opacity: 0
		}, speedCarousel, function() {
			var First = $('#beeldwissel').find('li:first');
			$(First).remove();
			$('#beeldwissel').append(First);
		});
		$(Next).animate({
			opacity: 1
		}, speedCarousel, function() {
		});
	}

	addStoreSlider();

	interval = setInterval(moveDown, pause);
	$('#beeldwissel').find('li:first').animate({
		opacity: 1
	}, speedCarousel);
	//interval = setInterval(removeFirst, pause);
	//interval = setInterval(moveLeft, pauseCarousel);

	//setTimeout('showlistitems()',6500);
	//addEvent (window,'load',fadeInit);
	//foldCatList();
	$('.datepicker').datepicker({ dateFormat: 'dd-mm-yy' ,dayNamesMin: ['Zo', 'Ma', 'Di', 'Wo', 'Do', 'Vr', 'Za'],monthNames: ['Januari','Februari','Maart','April','Mei','Juni','Juli','Augustus','September','Oktober','November','December'] });
});
