
function showLastItemWarning() {
	var lastItemElement = $('lastItemWarning');
	if (lastItemElement && lastItemElement.hasClass('hidden')) {
		lastItemElement.removeClass('hidden');
	}
}

function hideLastItemWarning() {
	var lastItemElement = $('lastItemWarning');
	if (lastItemElement && !lastItemElement.hasClass('hidden')) {
		lastItemElement.addClass('hidden');
	}
}

function gotoAnchor(name) {
	
	var location = document.location.href;
	var lastIndexOf = location.lastIndexOf('#');
	
	if (lastIndexOf != -1) {
		location = location.substr(0,lastIndexOf);
	} 
	
	location += '#' + name;
		
	document.location.href = location;
	return false;
}

function selectFeature(baseProductCode, pkString, selectedFeature, selectedValue, selectedName) {

	var callback = function(result) {
		var object = JSON.decode(result);

		for ( var i = 0; i < object.features.length; i++) {
			var feature = object.features[i];

			for ( var j = 0; j < feature.values.length; j++) {
				var value = feature.values[j];

				var liElement = $(document.getElementById('featurevalue_' + feature.feature + '_' + value.code));
				if (liElement == null) {
					continue;
				}
				var aElement = liElement.getElement('a');

				// clean..
				aElement.removeClass('disabled');
				aElement.removeClass('noStock');
				aElement.removeClass('selectable');
				
				if (value.selected) {
					liElement.addClass('selected');
				}

				if (!value.stock) {
					aElement.addClass('noStock');
				}
			}
		}
		
		// Clear active states.
		$('featureForm').getElements('ul').each(function(ulFeatureElement) {
			ulFeatureElement.removeClass('active');
		});
		
		// Set current active.
		$(selectedFeature).addClass('active');

		// Set variant id
		document.getElementById('selectedVariantPK').value = object.variantPK ? object.variantPK : '';
		
		// Show last item warning msg!
		if (object.variantPK && object.variantPK != ''  && object.variantReservableQuantity == '1') {
			showLastItemWarning();
		} else {
			hideLastItemWarning();
		} 
		
		document.getElementById('baseProductCode').value = baseProductCode ? baseProductCode : '';
		// Swap Images.
		if (object.media != null) {
						
			$('thumbs').empty();
			var mediaArray = JSON.decode(object.media);
			
			for (var i = 0; i < mediaArray.length; i++) {
			    var media = mediaArray[i];
			    
			    var li  = new Element('li');
			    var img = new Element('img');
			    img.set('src',media.small);
			    img.set('rel',media.medium+','+media.large);
			    
			    img.inject(li);
			    li.inject($('thumbs'));
			    
			    if (i == 0) {
				$('image').setProperty('src', media.medium);
				if ($('imagelarge')) $('imagelarge').setProperty('src', media.large);	
			    }
			}
			
			window['VD'].ZoomThumbController.apply();
		}

		// Swap Price.
		switch (object.priceType) {
		case "REGULAR":
			$('productPrice').innerHTML = '<strong>' + object.price + '</strong>';
			break;
		case "FROM":
			$('productPrice').innerHTML = '<strong>VANAF ' + object.price + '</strong>';
			break;
		case "PROMOTION":
			$('productPrice').innerHTML = '<em class="diagonalStrikeThrough">' + object.oldPrice + '</em> <strong>NU ' + object.price + '</strong>';
			window['VD'].StrikeThroughRenderer.addStrikeThroughs();
			break;
		}
	    
	    var productAmountSpan = $('productAmountSpan');
	    if (productAmountSpan) {
		if (object.stockOrderSet) {
		    productAmountSpan.empty();
		    productAmountSpan.removeClass('no_increment_amount_used');
		    productAmountSpan.addClass('increment_amount_used');
		    var aantalProductenSelect = new Element('select', { 'id': 'aantalProducten'} );
		    for(i=0; i<object.stockOrderSet.length; i++) {
			var amount = object.stockOrderSet[i];
			var option = new Element('option', { value : amount} );
			option.set('text', amount);
			option.inject(aantalProductenSelect);
		    }
		    productAmountSpan.adopt(aantalProductenSelect);
		} else {
		    if (productAmountSpan.hasClass('increment_amount_used')) {
			productAmountSpan.empty();
			productAmountSpan.removeClass('increment_amount_used');
			productAmountSpan.addClass('no_increment_amount_used');
			productAmountSpan.adopt(new Element('input', {
			    type: 'text',
			    id: 'aantalProducten',
			    value: 1
			}));
		    }
		}
	    }
	}

	// Remove error
	$('featureContainer').removeClass('error');
	$('errorMessage').innerHTML = '';
	$('message').setStyle('display', 'none');

	// Hide noStockToolTips
	$$('span.tooltip').each(function(el) {
		el.setStyle('display', 'none');
	});
	Seam.Remoting.displayLoadingMessage = function() {
	};
	Seam.Remoting.hideLoadingMessage = function() {
	};
	// Selections
	var selections = new Array();

	// Add clicked feature / featureValue.
	selections.push(selectedFeature + '=' + selectedValue);

	// Remove previous selected value for the feature being selected.
	$(selectedFeature).getChildren().each(function(liElement) {
		liElement.removeClass('selected');
	});

	// Append other selected features.
	$('featureForm').getElements('ul').each(function(ulFeatureElement) {
		ulFeatureElement.getElements('li.selected').each(function(liElement) {
			featureValue = liElement.getElement('a').getAttribute('id');
			feature = liElement.getParent().getAttribute('id');
			selections.push(feature + '=' + featureValue);
			liElement.removeClass('selected');
		});
	});

	Seam.Remoting.loadingMessage = "";
	Seam.Component.getInstance("fhPageController").selecteerFeature(pkString, selections, callback);
}

function rollOverFeature(aElement) {

	var liElement = aElement.getParent();
	var ulElement = liElement.getParent();

	var featureCode = ulElement.getAttribute('id');

	var el = $(featureCode + 'Name');

	if (el) {
		el.innerHTML = aElement.getAttribute('rel');
	}

	if (aElement.hasClass('noStock')) {
		var noStockToolTip = aElement.getElement('span.tooltip');
		noStockToolTip.setStyle('display', 'block');
	}
}

function rollOutFeature(aElement) {

	var liElement = aElement.getParent();
	var ulElement = liElement.getParent();

	var featureCode = ulElement.getAttribute('id');
	var el = $(featureCode + 'Name');

	if (el) {
		var value = '';
		ulElement.getElements('li').each(function(el) {
			if (el.hasClass('selected')) {
				value = el.getElement('a').getAttribute('rel');
			}
		});

		el.innerHTML = value;
	}

	var noStockToolTip = aElement.getElement('span.tooltip');
	noStockToolTip.setStyle('display', 'none');
}

function addToShoppingCartParams(baseProductPK, baseProductCode, variantPK, aantalProducten) {
	if($chk($('favoritesPopup'))){
		$('favoritesPopup').style.display = 'none';
	}
	var callback = function(result) {
		
		var object = JSON.decode(result);
		if (object.success) {
			$(baseProductPK + 'FeatureContainer').removeClass('error');
			$(baseProductPK + 'ErrorMessage').innerHTML = '';
			$(baseProductPK + 'Message').setStyle('display', 'none');

			var basketData = JSON.decode(object.basketdata);
			var basketEntries = JSON.decode(object.basketentries);
			$$('.totaalprijs').each(function(el) {
				el.firstChild.data = basketData.price;
			});
			$$('.totaalitems').each(function(el) {
				el.firstChild.data = basketData.quantity;
			});
			rebuildShoppingCart(basketEntries, basketData.quantity, basketData.price, baseProductCode);
			$('shoppingcartPopup').setStyle('display', 'block');
			setTimeout("hide()", 5000);
			
			var quantityLeft = object.variantReservableQuantity;		
			if (quantityLeft && quantityLeft == 1) {
				showLastItemWarning();
			} else {
				hideLastItemWarning();
			}
			
		} else {
			var errorMessage = object.message;
			if (object.quantity != null && object.quantity.length > 0) {
				errorMessage = errorMessage + " Het maximum aantal is "
						+ object.quantity[object.quantity.length - 1];
			}
			$(baseProductPK + 'FeatureContainer').addClass('error');
			$(baseProductPK + 'ErrorMessage').innerHTML = errorMessage;
			$(baseProductPK + 'Message').setStyle('display', 'block');
		}
	};

	Seam.Remoting.displayLoadingMessage = function() {
	};
	Seam.Remoting.hideLoadingMessage = function() {
	};
	Seam.Remoting.loadingMessage = "";

	Seam.Component.getInstance("checkoutController").addToShoppingCart(variantPK, aantalProducten, callback);
}

function addToShoppingCart() {
		
	if($chk($('favoritesPopup'))){
		$('favoritesPopup').style.display = 'none';
	}
	
	var callback = function(result) {

		var object = JSON.decode(result);
		if (object.success) {
			$('featureContainer').removeClass('error');
			$('errorMessage').innerHTML = '';
			$('message').setStyle('display', 'none');

			var basketData = JSON.decode(object.basketdata);
			var basketEntries = JSON.decode(object.basketentries);
			$$('.totaalprijs').each(function(el) {
				el.firstChild.data = basketData.price;
			});
			$$('.totaalitems').each(function(el) {
				el.firstChild.data = basketData.quantity;
			});
			rebuildShoppingCart( basketEntries, basketData.quantity, basketData.price, document.getElementById('baseProductCode').value);
			$('shoppingcartPopup').setStyle('display', 'block');
			setTimeout("hide()", 5000);
			
			var quantityLeft = object.variantReservableQuantity;		
			if (quantityLeft && quantityLeft == '1') {
				showLastItemWarning();
			} else {
				hideLastItemWarning();
			}
			
		} else {
			var errorMessage = object.message;
			if (object.quantity != null && object.quantity.length > 0) {
				errorMessage = errorMessage + " Het maximum aantal is "
						+ object.quantity[object.quantity.length - 1];
			}
			$('featureContainer').addClass('error');
			$('errorMessage').innerHTML = errorMessage;
			$('message').setStyle('display', 'block');
		}
	};

	Seam.Remoting.displayLoadingMessage = function() {
	};
	Seam.Remoting.hideLoadingMessage = function() {
	};
	Seam.Remoting.loadingMessage = "";

	Seam.Component.getInstance("checkoutController").addToShoppingCart(document.getElementById('selectedVariantPK').value, $('aantalProducten').value, callback);
}

function hide() {
	$('shoppingcartPopup').setStyle('display', 'none');
	$('shoppingcartPopup').removeProperty('style');
}

function rebuildShoppingCart(entries, quantity, totalPrijs, baseProductCode, displayInWebsite) {

	var shoppingcartList = $('shoppingcartList');
	while (shoppingcartList.hasChildNodes()) {
		shoppingcartList.removeChild(shoppingcartList.firstChild);
	}
	for ( var i = 0; i < entries.length; i++) {
		var entry = JSON.decode(entries[i].entry);
		var listItem = new Element('li');
		var prijs = new Element('strong');
		prijs.innerHTML = entry.price;
		var imageLink = new Element('a', {
			'href' : '#'
		});
		var image = new Element('img', {
			'width' : '29',
			'height' : '34',
			'alt' : entry.thumbnailalt,
			'src' : entry.thumbnailurl
		});
		var textHolder = new Element('div', {
			'class' : 'text-holder'
		});
		if(baseProductCode != undefined){
			var textLink = new Element(
					'a',
					{
						'href' : '/fh_detail.jsf?fhquery=fh_location%3D%2F%2Fcatalog01%2Fnl_NL%26fh_secondid%3D' + baseProductCode.toLowerCase()//entry.baseid
					});
			textLink.innerHTML = entry.quantity + ' x ' + entry.name
			textLink.inject(textHolder);
		}
		else{
			var productDescription = new Element('span');
			productDescription.innerHTML = entry.quantity + ' x ' + entry.name
			productDescription.inject(textHolder);
		}	
		
		listItem.inject(shoppingcartList);
		prijs.inject(listItem);
		imageLink.inject(listItem);
		image.inject(imageLink);
		textHolder.inject(listItem);
		
	}

	var shoppingcartTotal = $('shoppingcartTotal');
	while (shoppingcartTotal.hasChildNodes()) {
		shoppingcartTotal.removeChild(shoppingcartTotal.firstChild);
	}

	var totalStrong = new Element('strong');
	var totalSpan = new Element('span', {
		'class' : 'totaalprijs'
	});
	totalSpan.innerHTML = totalPrijs;
	var totalA = new Element('a', {
		'href' : '/checkout/cart.jsf'
	});
	if (quantity == "1") {
		totalA.innerHTML = "1 Artikel";
	} else {
		totalA.innerHTML = quantity + " Artikelen";
	}

	totalStrong.inject(shoppingcartTotal);
	totalSpan.inject(totalStrong);
	totalA.inject(shoppingcartTotal);

}


function addToFolderShoppingCart() {
	var callback = function(result) {

		var object = JSON.decode(result);
		if (object.success) {
			$('featureContainer').removeClass('error');
			$('errorMessage').innerHTML = '';
			$('message').setStyle('display', 'none');

			var basketData = JSON.decode(object.basketdata);
			var basketEntries = JSON.decode(object.basketentries);
			$$('.totaalprijs').each(function(el) {
				el.firstChild.data = basketData.price;
			});
			$$('.totaalitems').each(function(el) {
				el.firstChild.data = basketData.quantity;
			});
			rebuildFolderShoppingCart( basketEntries, basketData.quantity, basketData.price, document.getElementById('baseProductCode').value);
			if ($chk(document.getElementById('callBackOn')) && document.getElementById('callBackOn').value == 'true'){				
				parent.window.updateCart(basketData.quantity);
			}
			
			_gaq.push(['_trackEvent',  document.getElementById('folderId').value, 'addToBasketViaFolder', document.getElementById('selectedVariantPK').value]);
			$('shoppingcartPopup').setStyle('display', 'block');
			setTimeout("hide()", 5000);
		} else {
			var errorMessage = object.message;
			if (object.quantity != null && object.quantity.length > 0) {
				errorMessage = errorMessage + " Het maximum aantal is "
						+ object.quantity[object.quantity.length - 1];
			}
			$('featureContainer').addClass('error');
			$('errorMessage').innerHTML = errorMessage;
			$('message').setStyle('display', 'block');
		}
	};

	
	Seam.Remoting.displayLoadingMessage = function() {
	};
	Seam.Remoting.hideLoadingMessage = function() {
	};
	Seam.Remoting.loadingMessage = "";

	Seam.Component.getInstance("checkoutController").addToShoppingCart(document.getElementById('selectedVariantPK').value, $('aantalProducten').value, callback);
	
}

function rebuildFolderShoppingCart(entries, quantity, totalPrijs, baseProductCode) {

	var shoppingcartList = $('shoppingcartList');
	while (shoppingcartList.hasChildNodes()) {
		shoppingcartList.removeChild(shoppingcartList.firstChild);
	}
	for ( var i = 0; i < entries.length; i++) {
		var entry = JSON.decode(entries[i].entry);
		var listItem = new Element('li');
		var prijs = new Element('strong');
		prijs.innerHTML = entry.price;
		var imageLink = new Element('div');
		var image = new Element('img', {
			'width' : '29',
			'height' : '34',
			'alt' : entry.thumbnailalt,
			'src' : entry.thumbnailurl
		});
		var textHolder = new Element('div', {
			'class' : 'text-holder'
		});
		var textLink = new Element('div');
		textLink.innerHTML = entry.quantity + ' x ' + entry.name

		listItem.inject(shoppingcartList);
		prijs.inject(listItem);
		imageLink.inject(listItem);
		image.inject(imageLink);
		textHolder.inject(listItem);
		textLink.inject(textHolder);
	}

	var shoppingcartTotal = $('shoppingcartTotal');
	while (shoppingcartTotal.hasChildNodes()) {
		shoppingcartTotal.removeChild(shoppingcartTotal.firstChild);
	}

	var totalStrong = new Element('strong');
	var totalSpan = new Element('span', {
		'class' : 'totaalprijs'
	});
	totalSpan.innerHTML = totalPrijs;
	var totalA = new Element('div');
	if (quantity == "1") {
		totalA.innerHTML = "1 Artikel";
	} else {
		totalA.innerHTML = quantity + " Artikelen";
	}
	
	totalStrong.inject(shoppingcartTotal);
	totalSpan.inject(totalStrong);
	totalA.inject(shoppingcartTotal);
}

function inspect(obj, maxLevels, level) {
	var str = '', type, msg;

	// Start Input Validations
	// Don't touch, we start iterating at level zero
	if (level == null)
		level = 0;

	// At least you want to show the first level
	if (maxLevels == null)
		maxLevels = 1;
	if (maxLevels < 1)
		return '<font color="red">Error: Levels number must be > 0</font>';

	// We start with a non null object
	if (obj == null)
		return '<font color="red">Error: Object <b>NULL</b></font>';
	// End Input Validations

	// Each Iteration must be indented
	str += '<ul>';

	// Start iterations for all objects in obj
	for (property in obj) {
		try {
			// Show "property" and "type property"
			type = typeof (obj[property]);
			str += '<li>(' + type + ') ' + property
					+ ((obj[property] == null) ? (': <b>null</b>') : (''))
					+ '</li>';

			// We keep iterating if this property is an Object, non null
			// and we are inside the required number of levels
			if ((type == 'object') && (obj[property] != null)
					&& (level + 1 < maxLevels))
				str += inspect(obj[property], maxLevels, level + 1);
		} catch (err) {
			// Is there some properties in obj we can't access? Print it red.
			if (typeof (err) == 'string')
				msg = err;
			else if (err.message)
				msg = err.message;
			else if (err.description)
				msg = err.description;
			else
				msg = 'Unknown';

			str += '<li><font color="red">(Error) ' + property + ': ' + msg
					+ '</font></li>';
		}
	}

	// Close indent
	str += '</ul>';

	return str;
}

