var sessionCookie = null;
var page = 1;
var adjacentPages = 2;
var documentLocation = document.location.href.split('pagina.php');
var sessionMinPrijs = null;
var sessionMaxPrijs = null;
var currencySymbol = '\u20ac';
var homepageItemCounter = 0;
var showHideTimeout = 5000;
var checkedVarFound = false;
var useSorting = false;
var productData = false;
var resultsPerPage = 15;


$(document).ready(function() {

	$.cookie('previousPage', $.cookie('currentPage'));
	$.cookie('currentPage', document.location.href);
	if ($.cookie('previousPage') != $.cookie('currentPage')) {
		$.cookie('checkedBoxesCookie', null);
		$.cookie('selectedMinPrijsCookie', null);
		$.cookie('selectedMaxPrijsCookie', null);
	}

	if ($.cookie('resultsPerPageCookie') != null) {
		resultsPerPage = $.cookie('resultsPerPageCookie');
	}

	if ($('.head_productGroup').length == 0 && $('.itemOverview').length > 0 && $('.content_bb > h1').html() != 'Nieuwe stoffen') {
		$('.itemOverview').css('display', 'none');
	}

	//fade items on left side of screen
	homepageItemCounter = $('.homepageItem').length;
	if (homepageItemCounter > 1) {
		$('.homepageItem').hide();
		$('.homepageItem').first().show();
		setTimeout('showHideItems(\'.homepageItem\')',showHideTimeout);
	}

	//popeye zoomer with photo's
	if ($('.ppy').length > 0) {
		//only load this script when needed
		addScript('/javascript/jquery.popeye-2.0.4.min.js')
		$('.ppy').popeye({
				direction:  'left'
		});
	}

	if ($('.tabs').length > 0) {
	    $.featureList(
	        $(".tabs li a"),
	        $("#output li"), {
	            start_item    :    1
	        }
	    );
	}
	
	
	if ($('.letter').length != 0) {
		$('.letter').hide();
		$('.abc').click(function() {
			var abcLetter = $(this).attr('id').split('_');
			if ($('#abcLetter_'+abcLetter[1]).css('display') == 'none') {
				$('#abcLetter_'+abcLetter[1]).slideDown();
			} else {
				$('#abcLetter_'+abcLetter[1]).slideUp();
			}
		});
	}

	//back link from productdetail to searchresult
	if ($('a#bpLink').length != 0)	{
		var curLink = $('a#bpLink').attr('href');
		//check for real link
		var cLink = curLink.split('.');
		if (cLink[1].substring(0,4) == 'html' || cLink[1].substring(0,3) == 'php')	{
			//check if the p get var is incomming
			var getP = getVar('p');
			var getFb = getVar('fb');
			if(getP != '')	{
				//oke, generate the link
				if (cLink[1].substring(0,4) == 'html')	{
					var newLink = curLink + '?bp='+getP;
				}else	{
					var newLink = curLink + '&bp='+getP;
				}
				//replace
				$('a#bpLink').attr('href',newLink);
				//for the brand pages
			}else if (getFb != '' && getFb == 't')	{
				//oke, generate the link
				var newLink = 'Javascript:history.back()';
				//replace
				$('a#bpLink').attr('href',newLink);
			}
		}
	}

	/*
	if ($('#menu').length != 0) {
		$('#menu li a' ).click(function() {
			var menuTeller = $(this).attr('id').split('_');

			if ($('#submenu_items_'+menuTeller[1]).css('display') == 'none') {
				$('#submenu_items_'+menuTeller[1]).slideDown('fast');
			} else {
				$('#submenu_items_'+menuTeller[1]).slideUp('fast');
			}
		});
	}
	*/

	if ($('#menu').length != 0) {
		$('#menu li a' ).not('#menu li ul.submenu li a').click(function() {
			menuItem = $(this).next();

			$('#menu li ul.submenu').prev().removeClass('active');
			$('#menu li ul.submenu').slideUp('fast', function() {
				$(this).css('none');
			});

			if (menuItem.css('display') == 'none') {
				menuItem.slideDown('fast');
				 $(this).addClass('active');
			} else {
				menuItem.slideUp('fast');
			 	$(this).removeClass('active');
			}


		});

		if (activeFound == false) {
			//$('#menu li:first a:first').addClass('active').next().slideDown('fast');
		}
	}


	if ($('#productdetail').length != 0)	{
		sessionCookie = JSON.parse($.cookie('checkedBoxesCookie'));
		//$.getScript('/handleFilterSession.php?action=loadSession&currentGroupID='+currentProductGroupID, function(data) {
			$.getJSON('/json/products_'+currentProductGroupID+'_' + flag + '.json', false, function(data, textStatus){
				productData = data;

				product = data.products[currentProductID];

				if (showActie ( product ) ) {

					// dit is een product als actie

					$("span.#nu_prijs").text( currencySymbol + removeCurrencySymbol( product.actie.prijs ) );

					// vervang alle productid's met actieid
					var productForm = $("#product_acc_form").html();
					//productForm = productForm.replace( currentProductID , product.actie.id );
					productForm = str_replace ( currentProductID, product.actie.id , productForm );
					$("#product_acc_form").html( productForm );

					var test = '<div class="prijs prijs_actie">Actie'
								+	'<span class="van" style="text-decoration: line-through;">' +  product.actie.prijs_van + '</span>'
								+	'<span class="voor">' + product.actie.prijs + '</span>'
								+ '</div>'
								+ '<div class="clear"> </div>';

					$("#productHoofdAfbeelding").prepend(test);


				}

			});//end getJSON

		//});//end getScript

	}

	if ($('#merkdetail').length != 0)	{
		//is uitgeschakeld omdat we het flitsen wilden voorkomen0
		//handleBrands( page );

	}	//productfilter
	if ($('#filter').length != 0) {

		sessionCookie = JSON.parse($.cookie('checkedBoxesCookie'));

		//$.getScript('/handleFilterSession.php?action=loadSession&currentGroupID='+currentProductGroupID+'&time='+Math.random(), function(data) {
			$.getJSON('/json/products_'+currentProductGroupID+'_' + flag + '.json?time='+Math.random(), false, function(data, textStatus){
				productData = data;

				var tagsAdded = new Array();
				var taggroupsAdded = new Array();
				var productExamplesAdded = new Array();
				var sizesAdded = new Array();
				var productCount = 0;
				var minProductPrice = 0;
				var maxProductPrice = 0;
				$.each(data.products, function() {


					// breken max en min prijs voor slider
					if (this.in_actie == 1) {
						var productPrijs = this.actie.prijs_unformatted;
					} else {
						var productPrijs = this.prijs_unformatted;
					}
				 	productPrijs = Number(productPrijs.replace(',','.'));


					 if ( productPrijs) {
						 minProductPrice = Math.min( minProductPrice, productPrijs);
						 maxProductPrice = Math.max( maxProductPrice, productPrijs);
					 }

					//voorkomende tags toevoegen aan de style fieldset
					tagGroupCounter = 0;
					if (this.taggroups != undefined) {
						$.each(this.taggroups, function(tagGroupID, currentTagGroup) {
							if (!in_array(tagGroupID, taggroupsAdded)) {
								taggroupsAdded[taggroupsAdded.length] = tagGroupID;
								//taggroups
								taggroupHTML = '<div class="filter_head" id="tg_' + tagGroupID + 'Header"><h3>' + currentTagGroup.name + ':</h3></div>';
								taggroupHTML += '<div class="scroller" id="tg_' + tagGroupID + 'Scroller">';
								taggroupHTML += '	<fieldset id="tg_' + tagGroupID + 'Fieldset" class="tagsFieldset">';
								taggroupHTML += '		<legend>&nbsp;</legend>';
								taggroupHTML += '	</fieldset>';
								taggroupHTML += '	';
								taggroupHTML += '</div>';
								$('#taggroups').append(taggroupHTML);
							}
							$.each(currentTagGroup.tags, function(i, val) {
								if (!in_array(i, tagsAdded)) {
									tagsAdded[tagsAdded.length] = i;
									$('#tg_' + tagGroupID + 'Fieldset').append('<input class="checkbox floatLeft" type="checkbox" name="tg_' + tagGroupID + '[]" id="tg_' + tagGroupID + '_' + i + '" value="' + i + '" onclick="handleSearch()"><label class="active" for="tg_' + tagGroupID + '_' + i + '">' + val.naam + '</label><div class="clear">&nbsp;</div>');
									if (sessionCookie && sessionCookie.tags) {
										if (in_array(i, sessionCookie.tags)) {
											$('#tg_' + tagGroupID + '_'+i).attr('checked', true);
											checkedVarFound = true;
										}
									}
								}
							});
							tagGroupCounter++;
						});
					}

					//voorkomende maten toevoegen aan de size fieldset
					//if (this.artikelen != undefined) {
//						$.each(this.artikelen, function (i, val) {
//							if (!in_array(i, sizesAdded)) {
//								sizesAdded[sizesAdded.length] = i;
//								$('#sizesFieldset').append('<input class="checkbox floatLeft" type="checkbox" name="size[]" id="size_' + i + '" value="' + i + '" onclick="handleSearch()"><label class="active" for="size_' + i + '">' + val.artikelnaam + '</label><br>');
//								if (sessionCookie && sessionCookie.sizes) {
//									if (in_array(i, sessionCookie.sizes)) {
//										$('#size_'+i).attr('checked', true);
//										checkedVarFound = true;
//									}
//								}
//							}
//						});
//					}

					//if (this.artikelen != undefined) {
//						$.each(this.artikelen, function (i, val) {
//							if (!in_array(val.artikelnaam, sizesAdded)) {
//								sizesAdded[sizesAdded.length] = val.artikelnaam;
//								$('#sizesFieldset').append('<input class="checkbox floatLeft" type="checkbox" name="size[]" id="size_' + val.artikelnaam + '" value="' + val.artikelnaam + '" onclick="handleSearch()"><label class="active" for="size_' + val.artikelnaam + '">' + val.artikelnaam + '</label><br>');
//								if (sessionCookie && sessionCookie.sizes) {
//									if (in_array(val.artikelnaam, sessionCookie.sizes)) {
//										$('#size_'+val.artikelnaam).attr('checked', true);
//										checkedVarFound = true;
//									}
//								}
//							}
//						});
//					}

					productCount++;
				});


			// max position for slider based on max product price and saved user setting
			if ($.cookie('selectedMinPrijsCookie') == null) {
				sliderMinValue = minProductPrice;
			} else {
				sliderMinValue = Math.max ( $.cookie('selectedMinPrijsCookie'), minProductPrice);
				checkedVarFound = true;
			}


			// min position for slider based on min product price and saved user setting
			if ($.cookie('selectedMaxPrijsCookie') == null) {
				sliderMaxValue = maxProductPrice;
			} else {
				sliderMaxValue = Math.min ( $.cookie('selectedMaxPrijsCookie'), maxProductPrice);
				checkedVarFound = true;
			}

			// logical slider step based on price range
			sliderStep = calcSliderStep( maxProductPrice - minProductPrice );

			$("#prijsSlider").slider({
				range: true,
				min: minProductPrice,
				max: maxProductPrice,
				values: [ sliderMinValue, sliderMaxValue],
				step: sliderStep,
				slide: function(event, ui) {

					$("#prijsMin").html(currencySymbol + ui.values[0]);
					$("#prijsMax").html(currencySymbol + ui.values[1]);

				},
				change: function(event, ui) {

						if (event.originalEvent != undefined ) {
								handleSearch();
						}
					}


			});

			$("#prijsMin").html(currencySymbol + $("#prijsSlider").slider("values", 0));
			$("#prijsMax").html(currencySymbol + $("#prijsSlider").slider("values", 1));


				$.each(data.brands, function(i, val) {
					$('#brandsFieldset').append('<input class="checkbox floatLeft" type="checkbox" name="brand[]" id="brand_' + i + '" value="' + i + '" onclick="handleSearch()"><label class="active" for="brand_' + i + '">' + val + '</label><br>');
					if (sessionCookie && sessionCookie.brands) {
						if (in_array(i, sessionCookie.brands)) {
							$('#brand_'+i).attr('checked', true);
							checkedVarFound = true;
						}
					}
				});
				if (sessionCookie && sessionCookie.stock) {
					if (sessionCookie.stock[0] == 1) {
						$('#stock').attr('checked', true);
						checkedVarFound = true;
					}
				}

				if (sessionCookie && sessionCookie.nieuw) {
					if (sessionCookie.nieuw[0] == 1) {
						$('#new').attr('checked', true);
						checkedVarFound = true;
					}
				}

				//check for a diff page
				var difP = getVar('bp');
				if (difP != '')	{
					//number?
					var filter=/^[0-9]+$/i
					if (filter.test(difP)) 	{
						handleSearch(difP, true);
					}else	{
						//uitgezet tegen het flikkeren
						if (checkedVarFound) {
							handleSearch(1, true);
						}
					}
				}else	{
					//alert('bb ' + document.referrer +'=='+ document.location.href);
					if ($.cookie('previousPage') == null || $.cookie('previousPage') == '' || $.cookie('previousPage') == $.cookie('currentPage')) {
						//uitgezet tegen het flikkeren
						if (checkedVarFound || resultsPerPage > 15) {
							handleSearch(1, true);
						} else {
							$('.itemOverview').css('display', 'block');
						}

					} else {
						if (resultsPerPage > 15) {
							handleSearch(1, true);
						} else {
							$('.itemOverview').css('display', 'block');
						}
					}

				}
	        });//end getJSON
		//});//end getScript
	}
	if ($('#nieuweStoffen').length > 0) {
		sessionCookie = JSON.parse($.cookie('checkedBoxesCookie'));
		//$.getScript('/handleFilterSession.php?action=loadSession&currentGroupID=0&time='+Math.random(), function(data) {
	 		if (resultsPerPage > 15) {
				handleSearchNew(1, true);
			}
		//});
	}

	addFormAction();

});

function showHideItems(itemClass)
{
	var currentItem = false;
	var nextItem = false;
	var firstItem = 0;
	$(itemClass).each(function(i) {
		if (i == 0) {
			firstItem = $(this);
		}
		if ($(this).css('display') == 'block') {
			currentItem = $(this);
			if (i == homepageItemCounter-1) {
				nextItem = firstItem
			}
		} else if (currentItem !== false && nextItem === false) {
			nextItem = $(this);
		}
	});

	if (currentItem != undefined && nextItem != undefined) {
		currentItem.fadeOut(500, function() {
			nextItem.fadeIn(1500, function() {
				setTimeout('showHideItems(\'' + itemClass + '\')',showHideTimeout);
			});
		});
	}


}

function handleInfoPopup(item)
{
	//$('a.voorwaarden').click(function() {
		var url = item.href;
		var dialog = $('<div style="display:none"></div>').appendTo('body');
		// load remote content
		dialog.load(url, {},function (responseText, textStatus, XMLHttpRequest) {
		        dialog.dialog({
					width: 750,
					height: 600
		        });
		});
		//prevent the browser to follow the link
		return false;
	//});
}

function showResultsPerPage(results)
{
	$('#productsPerpage').val(results);
	$('#theFilterForm').submit();
}

function is_numeric (mixed_var) {

    return (typeof(mixed_var) === 'number' || typeof(mixed_var) === 'string') && mixed_var !== '' && !isNaN(mixed_var);
}


//Sorting by a field, reverse (true or false) and type of the field (int, string)
function sort_by(field, reverse, primer){

   reverse = (reverse) ? -1 : 1;

   return function(a,b){

       a = a[field];
       b = b[field];

       if (typeof(primer) != 'undefined'){
           a = primer(a);
           b = primer(b);
       }

       if (a<b) return reverse * -1;
       if (a>b) return reverse * 1;
       return 0;

   }
}

//Handles the filtering of the arg data(json) and orders it by the sortfield and given sortorder (false / true)
function handleFilterSorting(data,sortField,sortOrder)
{
	/*
	* Sorting order
	*/

	var x = data; //the main object with the data
	var yA = [data]; //the main object as an array
	var yAA = yA[0]; //the main object with direct key access
	var sortedData = new Object(); //the new sorted object


	var ini = new Array(); //array with the sortitems and the stuctuurid
	var def = new Array(); //array with only the correct sorted structuurids

	var eC = 0;
	$.each(x, function(count, c)	{

		//fill the ini array with the needed field
		ini[eC] = new Array(1);
		ini[eC][0] = this[sortField];
	    ini[eC][1] = this.structuurID;
	    eC = eC+1;

	});

	//print_r(ini,true);

	//check for result
	if (eC > 0)	{

		//decide the kindof data
		if (is_numeric(ini[0][0]))	{
			//sort the array on the sortedkey item (number)
			ini.sort(sort_by(0, sortOrder, parseInt));
		}else	{
			//sort the array on the sortedkey item (tekst)
			ini.sort(sort_by(0, sortOrder, function(a){return a.toUpperCase()}));
		}

		//push the structuurid in the def array
		$.each(ini, function(id, da)	{
			def.push(da[1]);
		});

		//chrome sorting object bugfix
		var ch = 0;
		//set the new order in the sortedData object
		$.each(def, function(ab, cd)	{
			sortedData[ch] = new Object();
			sortedData[ch] = yAA[cd];
			ch = ch+1;
		});

		return sortedData;

	}else	{
		return data;
	}


	/*
	* End sorting order
	*/
}


function getCompleteHtml(currentPage, isFirst, productsData, skipSave, isNewCall)
{
	if (isFirst == undefined) {
		$('#loadingFilter').css('opacity', '0.6');
		$('#loadingFilter').fadeIn(100);
		$('#loadingProducts').css('opacity', '0.6');
		$('#loadingProducts').fadeIn(100);
	}
	if (currentPage == undefined) {
		page = 1;
	} else {
		page = currentPage;
	}

	if ($('#productGroepID').length > 0) {
		var productGroepID = $('#productGroepID')[0].value;
	} else {
		var productGroepID = false;
	}

	var checkedBoxes = '';
	var checkedBoxesForCookie = new Object();
	checkedBoxesForCookie.brands = new Array();
	checkedBoxesForCookie.stock = new Array();
	checkedBoxesForCookie.nieuw = new Array();
	checkedBoxesForCookie.tags = new Array();
	var checkedBrands = $('#brandsFieldset > input:checked');
	checkedBrandIDs = new Array();
	$.each(checkedBrands, function (i, val) {
		checkedBrandIDs[checkedBrandIDs.length] = val.value;
		checkedBoxes += '&brands[]=' + val.value;
		checkedBoxesForCookie.brands[checkedBoxesForCookie.brands.length] = val.value;
	});

	var checkedStock = $('#stockFieldset > input:checked');
	checkedStockIDs = new Array();
	$.each(checkedStock, function (i, val) {
		checkedStockIDs[checkedStockIDs.length] = val.value;
		checkedBoxes += '&stock[]=' + val.value;
		checkedBoxesForCookie.stock[checkedBoxesForCookie.stock.length] = val.value;
	});
	var checkedNew = $('#newFieldset > input:checked');
	checkedNewIDs = new Array();
	$.each(checkedNew, function (i, val) {
		checkedNewIDs[checkedNewIDs.length] = val.value;
		checkedBoxes += '&new[]=' + val.value;
		checkedBoxesForCookie.nieuw[checkedBoxesForCookie.nieuw.length] = val.value;
	});

	var checkedTags = $('.tagsFieldset > input:checked');
	checkedTagIDs = new Array();
	$.each(checkedTags, function (i, val) {
		var currentTagInputID = val.id;
		var splitted = currentTagInputID.split('_');
//		if (checkedTagIDs[splitted[1]] == undefined) {
//			checkedTagIDs[splitted[1]] = new Array();
//		}
		//checkedTagIDs[splitted[1]][checkedTagIDs[splitted[1]].length] = val.value;
		var tmp = new Array();
		tmp[tmp.length] = splitted[1];
		tmp[tmp.length] = val.value;
		checkedTagIDs[checkedTagIDs.length] = tmp;
		checkedBoxes += '&tags[]=' + val.value;
		checkedBoxesForCookie.tags[checkedBoxesForCookie.tags.length] = val.value;
	});
	var selectedMinPrijs = $("#prijsSlider").slider("values", 0);
	var selectedMaxPrijs = $("#prijsSlider").slider("values", 1);

	var productHTML = headerHTML = '';
	var productCountTotal = productCountFound = 0;
	var teller = 1;
	var countMe = 0;



	$.each(productsData, function(i, currentProduct) {
		//bepaap met welke prijs er gefilterd moet worden
		if ( showActie (this )  ) {
			var productPrijsVoorFilter = this.actie.prijs_unformatted;
		}	else {
			var productPrijsVoorFilter = this.prijs_unformatted;
		}

		//prijs hoger dan min slider
		if ( selectedMinPrijs <= productPrijsVoorFilter) {
			minPrijsFound = true;
		} else {
			minPrijsFound = false;
		}

		//prijs lager dan max slider
		if ( selectedMaxPrijs >= productPrijsVoorFilter ) {
			maxPrijsFound = true;
		} else {
			maxPrijsFound = false;
		}

		// product valt binnen prijs range
		if (( minPrijsFound && maxPrijsFound ) || isNewCall != undefined) {

			//merk gevonden in aangevinkte brands
			if (checkedBrandIDs.length == 0 || in_array(this.merk, checkedBrandIDs)) {

				//product doorzoeken op tags
				tagsFound = 1;

				//$.each(checkedTagIDs, function (tagGroupID,tagGroupTagsChecked) {

				$.each(checkedTagIDs, function (x,xTag) {
					tagGroupID = xTag[0];
					tagGroupTagsChecked = new Array();
					tagGroupTagsChecked[0] = xTag[1];
					if (tagsFound > 0 && tagGroupTagsChecked != undefined) {
						tagsFound = 0;
						if (tagGroupTagsChecked != undefined) {
							if (currentProduct.taggroups != undefined) {
								$.each(currentProduct.taggroups, function (productTagGroupID, productTagGroupTags) {
									$.each(productTagGroupTags.tags, function (productTagID, val) {
										if (in_array(productTagID, tagGroupTagsChecked)) {
											tagsFound++;
										}
									});
								});
							}
						}
					}
				});


				//stijl gevonden in aangevinkte stijlen
				if (checkedTagIDs.length == 0 || tagsFound > 0 ) {

					//doorzoeken van producten op voorraad
//					stockFound = 0;
//					if (checkedStockIDs.length > 0) {
//						if (this.artikelen != undefined) {
//							$.each(this.artikelen, function (i, val) {
//								if (val.voorraad > 0) {
//									stockFound++;
//								}
//							});
//						}
//					}

					//doorzoeken van producten op new
					newFound = 0;
					if (checkedNewIDs.length > 0 || isNewCall) {
						if (this.isNew > 0) {
							newFound++;
						}
					}



					//alle maten die zijn aangevinkt zijn op voorraad
					//if (checkedStockIDs.length == 0 || stockFound > 0) {
					if (checkedNewIDs.length == 0 || newFound > 0) {
						//if (productCountTotal == 0) {
							if ( (productCountFound >= ( (page-1) * resultsPerPage) )
								&& (productCountFound < (page * resultsPerPage) )
							)
							{

								productHTML += getProductHTML(currentProduct, page, teller);


								if (teller == 3) teller = 0;

								teller++;
							}
						//}
						productCountFound++;
					}

				}
			}
		}

		productCountTotal++;
	});

	if (productHTML == '' || productCountFound == 0) {
		productHTML = 'Er zijn geen resultaten gevonden.';
	}

	if (isNewCall != undefined) {
		functionCall = 'handleSearchNew';
	} else {
		functionCall = undefined;
	}
	pagingHTML = $.getPaging(page, productCountFound, resultsPerPage, functionCall);
	$('.pageNr').html(pagingHTML);
	$('.itemOverview').html('<div class="pageNr">'  + pagingHTML + '</div>' + productHTML + '<div class="clear">&nbsp;</div><div class="pageNr">'  + pagingHTML + '</div>');
	$('#loadingFilter').fadeOut(200);
	$('#loadingProducts').fadeOut(200);



	//save checked items to session through ajax
	if (skipSave == undefined || skipSave != true) {
//		$.ajax({
//			url: "/handleFilterSession.php",
//			type: "POST",
//			data: 'action=saveSession&productGroepID=' + productGroepID + checkedBoxes + '&min_prijs=' + selectedMinPrijs  + '&max_prijs=' + selectedMaxPrijs,
//			dataType: "html",
//			cache: false
//		});
		$.cookie('productGroepIDCookie', productGroepID);
		$.cookie('selectedMinPrijsCookie', selectedMinPrijs);
		$.cookie('selectedMaxPrijsCookie', selectedMaxPrijs);
		$.cookie('checkedBoxesCookie', JSON.stringify(checkedBoxesForCookie));
	}

	/**
	* Process sortering clicks
	*/

	//decide the sorting use
	if (useSorting && $(".sortering").length > 0)	{

		//check the current sorting
		$.getScript('/handleFilterSession.php?action=loadSorting&currentGroupID='+currentProductGroupID, function(dataSorting) {

			//check the vars
			if (currentSortingField != '')	{

				//get the classtype
				if (currentSortingOrder)	{
					var curClass = 'sort_down';
				}else	{
					var curClass = 'sort_up';
				}

				//set the classes
				$("a.sortering[rel="+currentSortingField+"]").addClass(curClass);

			}
		});


		//handle the clicks
		$("a.sortering").click(function()	{

			//sorting info
			var sortField = $(this).attr("rel");
			var sortOrder = 1;

			if ($(this).hasClass("sort_down"))	{
				$(this).removeClass("sort_down").addClass("sort_up");
				var sortOrder = 0;
			}else if ($(this).hasClass("sort_up"))	{
				$(this).removeClass("sort_up").addClass("sort_down");
				var sortOrder = 1;
			}else 	{
				//no class atall
				$(this).addClass("sort_down");
			}
			//remove the existing sorting
			$("a.sortering").not($(this)).removeClass("sort_up").removeClass("sort_down");

			//save the new sorting order to the session
			$.ajax({
				url: "/handleFilterSession.php",
				type: "POST",
				data: 'action=saveSorting&productGroepID=' + productGroepID + '&sortingField=' + sortField + '&sortingOrder=' + sortOrder,
				dataType: "html",
				cache: false,
				complete: function(XMLHttpRequest, textStatus) {
					handleSearch(1, true);
				}
			});

		})

	}

	/**
	* End process sortering clicks
	*/

}

function handleResultsPerPage(currentResultsPerPage, isNewSearch)
{
	var setNew = '';
	if (isNewSearch == 'true' || isNewSearch == true) {
		setNew = '&setNewKillRest=true';
	}

	$('.content_bb').css('background-image','url(/grafix/loader.gif)');
	$('.content_bb').css('background-position', 'center');
	$('.content_bb').css('background-repeat','no-repeat');
	$('.itemOverview').css('display','none');
	resultsPerPage = currentResultsPerPage;

	$.cookie('resultsPerPageCookie', resultsPerPage);
	if (isNewSearch == 'true' || isNewSearch == true) {
		handleSearchNew(1, false, true);
	} else {
		handleSearch(1, false, true);
	}
	$('.content_bb').css('background-image','');
	$('.content_bb').css('background-position', 'center');
	$('.content_bb').css('background-repeat','no-repeat');
	$('.itemOverview').css('display','block');


//	$.ajax({
//		url: "/handleFilterSession.php",
//		type: "POST",
//		data: 'action=saveResultsPerPage&resultsPerPage=' + currentResultsPerPage + setNew,
//		dataType: "html",
//		cache: false,
//		complete: function() {
//			if (isNewSearch == 'true' || isNewSearch == true) {
//				handleSearchNew(1, false, true);
//			} else {
//				handleSearch(1, false, true);
//			}
//		}
//	});
}

function handleSearchNew(currentPage, isFirst, skipSave)
{

	$.getJSON('/json/new_' + flag + '.json', false, function(data, textStatus){
		getCompleteHtml(currentPage, isFirst, data.products, skipSave, true);
		bindImgPreview();
		//update favorieten
		checkUseFavoSystem();
		$('.itemOverview').css('display','block');
		//activateSifr();
		Cufon.replace('h1,h2', { });
	});
}



function handleSearch(currentPage, isFirst, skipSave)
{

	//load products in this productgroup
	//$.getJSON('/json/products_'+currentProductGroupID+'_' + flag + '.json', false, function(data, textStatus){
		data = productData;

		//check sorting enabled
		if (useSorting)	{

			//get the current sorting
		   	$.getScript('/handleFilterSession.php?action=loadSorting&currentGroupID='+currentProductGroupID, function(dataSorting) {

				//check the vars
				if (currentSortingField != '')	{
					newSortedData = handleFilterSorting(data.products,currentSortingField,currentSortingOrder);
				}else	{
					//use the basic
					newSortedData = data.products;
				}

				getCompleteHtml(currentPage, isFirst, newSortedData);

			});
		}else	{
			//alert('test');
			newSortedData = data.products;
			getCompleteHtml(currentPage, isFirst, newSortedData, skipSave);
		}

		//update zoom images
		bindImgPreview();
		//update favorieten
		checkUseFavoSystem();
		//$.getScript('/javascript/sifr-config.js');
		$('.itemOverview').css('display','block');
		Cufon.replace('h1,h2', { });
		//activateSifr();
	//});
}

$.getPaging = function(page, productCountFound, resultsPerPage, functionCall)
{
	var prev = parseInt(page) - 1;                            					//previous page is page - 1
	var next= parseInt(page) + 1;                            						//next page is page + 1
	var lastpage = Math.ceil(productCountFound / resultsPerPage);       //lastpage is = total pages / items per page, rounded up.
	var lpm1 = lastpage - 1;                      						//last page minus 1
	var isNew = undefined;

	if (functionCall == undefined) {
		functionCall = 'handleSearch';
	} else if (functionCall == 'handleSearchNew') {
		isNew = true;
	}

	var pagingHTML = '';

	if (productCountFound > 0) {
		pagingHTML += 'Resultaten per pagina <select name="resultsPerPage" onchange="handleResultsPerPage(this.options[this.selectedIndex].value, '+ isNew + ');">';
		pagingHTML += '<option value="15" ';
		if (resultsPerPage == 15) {
			pagingHTML += ' selected="selected"';
		}
		pagingHTML += '>15</option>';
		pagingHTML += '<option value="25" ';
		if (resultsPerPage == 25) {
			pagingHTML += ' selected="selected"';
		}
		pagingHTML += '>25</option>';
		pagingHTML += '<option value="50" ';
		if (resultsPerPage == 50) {
			pagingHTML += ' selected="selected"';
		}
		pagingHTML += '>50</option>';
		pagingHTML += '<option value="100" ';
		if (resultsPerPage == 100) {
			pagingHTML += ' selected="selected"';
		}
		pagingHTML += '>100</option>';
		pagingHTML += '</select>';
	}

	if (lastpage > 1) {


		//previous button
		if (page > 1) {
			pagingHTML += '<a href="Javascript:' + functionCall + '(' + prev + ');" class="page_next">Vorige</a>';
		} else {
			pagingHTML += '<span class="disabled">Vorige</span>';
		}

		//don't break up
		if (lastpage < 7 + (adjacentPages * 2)) {
			for (i = 1; i <= lastpage; i++) {
				if (i == page)	{
		            pagingHTML += '<span class="current">' + i + '</span>';
				} else {
		            pagingHTML += '<a href="Javascript:' + functionCall + '(' + i + ');">' + i + '</a>';
				}
			}
		} else if (lastpage > 5 + (adjacentPages * 2) ) {//enough pages to hide some
		    //close to beginning; only hide later pages
		    if(page < 1 + (adjacentPages * 2)) {
		        for (i = 1; i < 4 + (adjacentPages * 2); i++) {
		            if (i == page)	{
		                pagingHTML += '<span class="current">' + i + '</span>';
					}else	{
		                pagingHTML += '<a href="Javascript:' + functionCall + '(' + i + ');">' + i + '</a>';
					}
		        }
		        pagingHTML += '<strong>...</strong>';
		        pagingHTML += '<a href="Javascript:' + functionCall + '(' + lpm1 + ');">' + lpm1 + '</a>';
		        pagingHTML += '<a href="Javascript:' + functionCall + '(' + lastpage + ');">' + lastpage + '</a>';
		    } else if(lastpage - (adjacentPages * 2) > page && page > (adjacentPages * 2)) {

	    		//in middle; hide some front and some back
		        pagingHTML += '<a href="Javascript:' + functionCall + '(1)">1</a>';
		        pagingHTML += '<a href="Javascript:' + functionCall + '(2)">2</a>';
		        pagingHTML += '<strong>...</strong>';
		        for (i = page - adjacentPages; i <= page + adjacentPages; i++)
		        {
		            if (i == page)	{
		                pagingHTML += '<span class="current">' + i + '</span>';
					}else	{
		                pagingHTML += '<a href="Javascript:' + functionCall + '(' + i + ')">' + i + '</a>';
					}
		        }
		        pagingHTML += '<strong>...</strong>';
		        pagingHTML += '<a href="Javascript:' + functionCall + '(' +  lpm1 + ')">' + lpm1 + '</a>';
		        pagingHTML += '<a href="Javascript:' + functionCall + '(' + lastpage + ')">' + lastpage + '</a>';
		    } else {
	    		//close to end; only hide early pages
		        pagingHTML += '<a href="Javascript:' + functionCall + '(1)">1</a>';
		        pagingHTML += '<a href="Javascript:' + functionCall + '(2)">2</a>';
		        pagingHTML += '<strong>...</strong>';
		        for (i = lastpage - (2 + (adjacentPages * 2)); i <= lastpage; i++)
		        {
		            if (i == page)	{
		                pagingHTML += '<span class="current">' + i + '</span>';
					}else	{
		                pagingHTML += '<a href="Javascript:' + functionCall + '(' + i + ')">' + i + '</a>';
					}
		        }
		    }
		}

		//next button
		if ( next <= lastpage) {
			pagingHTML += '<a href="Javascript:' + functionCall + '(' + next + ');" class="page_next">Volgende</a>';
		} else {
			pagingHTML += '<span class="disabled">Volgende</span>';
		}
	}
	return pagingHTML;
}

function getVar( name )
{
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null ) {
		return "";
	} else {
		return results[1];
	}
}

function checkStock(number, articleID)
{
	if (articleID > 0) {
		$.getJSON('/json/products_'+currentProductGroupID+'_' + flag + '.json', false, function(data, textStatus){
			var validStock = false;
			var stockFound = 0;
			$.each(data.products, function() {
				if (this.artikelen != undefined) {
					$.each(this.artikelen, function (i, val) {
						if (i == articleID) {
							if (number <= val.voorraad) {
								validStock = true;
							} else {
								stockFound = val.voorraad;
							}
						}
					});
				}
			});
			if (!validStock) {
				if (stockFound == 0) {
					alert('Er zijn helaas geen artikelen op voorraad!');
				} else if (stockFound == 1) {
					alert('Er is helaas nog maar ' + stockFound + ' artikel op voorraad!');
				} else {
					alert('Er zijn helaas nog maar ' + stockFound + ' artikelen op voorraad!');
				}
				$('#quantity').val(stockFound);
			}
		});
	}
}

$.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
	$("<img>").attr("src", arguments[i]);
  }
}

function showResultsPerPage(results)
{
	$('#productsPerpage').val(results);
	$('#theFilterForm').submit();
}

function submitFilterForm()
{
	$('#page').val('1');
	$('#theFilterForm').submit();
}

//add action to filterform
function addFormAction()
{
	$('#theFilterForm').submit(function() {
		//display loadingdiv
		$("#loadingFilter").css('opacity', '0.5');
		$("#loadingFilter").css('display','block');
		$("#loadingProducts").css('opacity', '0.5');
		$("#loadingProducts").css('display','block');
		var inputs = $("#theFilterForm :input");
		var filterUrl = '';
		//create filterAjaxurl
		inputs.each(function(i){
			if ($(this).attr('type') == 'checkbox' && $(this).attr('checked') == true) {
				if (filterUrl == '') {
					filterUrl =  $(this).attr('name') + '=' + $(this).val()
				} else {
					filterUrl =  filterUrl + '&' + $(this).attr('name') + '=' + $(this).val()
				}
			} else if ($(this).attr('type') == 'text' || $(this).attr('type') == 'hidden') {
				if (filterUrl == '') {
					filterUrl =  $(this).attr('name') + '=' + $(this).val()
				} else {
					filterUrl =  filterUrl + '&' + $(this).attr('name') + '=' + $(this).val()
				}
			}
 		});

 		//process ajaxrequest
		$.ajax({
			url: "/filterProducts.php",
			type: "POST",
			data: filterUrl,
			dataType: "html",
			//cache: false,
			success: function(responseHtml) {
				var $holder = $('<div/>').html(responseHtml);
				//update filterDiv
				$('#productFilter').html($('#productFilter', $holder).html());
				//update productresultdiv
				$('.content_bb').html($('#productsFound', $holder).html());

				$("#loadingFilter").css('display','none');
				$("#loadingProducts").css('display','none');
				addFormAction();
			}
		});
		return false;
	});
}

function showLoginError(elementName){

	var element = document.getElementById(elementName);

	$.modal($(element),{

    	minHeight:17,
		containerCss:{backgroundColor:"#fff",height:130,padding:0,width:322},

		onOpen: function(dialog)
		{
			dialog.overlay.fadeIn('fast', function () {
				dialog.container.slideDown('normal', function () {
					dialog.data.fadeIn('normal');

					if (element != null) {
						element.style.visibility = 'visible';
					}
					//$.getScript('/javascript/sifr-config.js');
					//activateSifr();
					Cufon.replace('h1,h2', { });

				});
			});
		},
		onClose: function(dialog)
		{
			dialog.overlay.fadeOut('fast', function () {
				dialog.container.fadeOut('fast', function () {
					dialog.data.fadeOut('fast', function () {

						$.modal.close(); // must call this!
						$("#klantLoginFoutMeldingen").remove(); // and this too!

					});
				});
			});
		}

	});
}


function showHideFilter()
{
	if ($("#filter").css('display') == 'block') {
		$("#filter").slideUp('slow', function() {
			$("#headFilter").css('margin-bottom', '10px');
		});

		$("#headFilter").removeClass('head_filter_active');
	} else {
		$("#filter").slideDown('slow');
		$("#headFilter").addClass('head_filter_active');
		$("#headFilter").css('margin-bottom', '0px');

	}
}

function showResultPage(number)
{
	$('#page').val(number);
	$('#theFilterForm').submit();
}

function uncheckFilter(id)
{
	$('#' + id + 'Fieldset > input').attr('checked', false);
	$('#theFilterForm').submit();
}

// check whether fieldvalue is unique or not
function checkFieldValue( structuurid, eigenschapnaam, element ){

		// error span verwijderen
		var id = $(element).attr('id') + '_error';
		var value = element.value;

		if (value.length > 0) {

			filterUrl =  'action=checkduplicate&id='+ structuurid + '&esnaam=' + eigenschapnaam + '&value=' + value;

 			//process ajaxrequest
			$.ajax({
				url: "/ajaxrequests.php",
				type: "POST",
				data: filterUrl,
				dataType: "html",
				cache: false,
				success: function(responseHtml) {


					if (responseHtml != 'false') {

						$("#"+id+"").remove();
						// add span
						$(element).after('<span id="' + id +'" class="error">' + responseHtml + '</span>');
						//for (var x in element ) alert(x);

					}
				}
			});

		}
}

// check length of field value
function checkFieldLength( element, min, max ){

		// error span verwijderen
		var id = $(element).attr('id') + '_error';
		var value = element.value;

		$("#"+id+"").remove();

		if ((value.length < min) || (value.length > max)){
			// add span
			$(element).after('<span id="' + id +'" class="error">Aanbevolen lengte is tussen ' + min + ' en ' + max + '.</span>');
			//for (var x in element ) alert(x);

		}
}


//laden van netto prijzen, in structuurIDPrices zitten 1 of meerdere structuren met hun prijs structuurID:prijs;structuurID2;prijs2
function loadDiscountPrices(structuurIDPrices)
{
	$.ajax({
		url: "/ajaxrequests.php",
		type: "POST",
		data: 'action=loadDiscountPrices&structuurIDPrices='+structuurIDPrices,
		dataType: "html",
		success: function(responseHtml) {
			var $holder = $('<div/>').html(responseHtml);
			var $children = $holder.children('div');
			$.each($children, function(val, i) {
				$('#' + i.id).html(i.innerHTML);
			});
		}
	});

}

function calcSliderStep( priceDiff )
{
	if (priceDiff > 50000)
		return 1000;
	else if (priceDiff > 20000)
		return 500;
	else if (priceDiff > 5000)
		return 100;
	else if (priceDiff > 2000)
		return 50;
	else if (priceDiff > 500)
		return 10;
	else if (priceDiff > 200)
		return 5;
	else return 1;
}

function showActie( product )
{
	if (product.in_actie == 1) {

		// check of datum tussen publicatiedatum en archiveringsdatum ligt
		var tsNow = Math.round(new Date().getTime() / 1000);
		var tsVan = product.actie.publicatiedatum;
		var tsTot = product.actie.archiveringsdatum;

		if (( tsNow > tsVan ) && ( tsNow <  tsTot ))
				return true;
		else 	return false;

	}
}

function resetProductFilter( )
{

	var minVal = $("#prijsSlider").slider( "option", "min");
	var maxVal = $("#prijsSlider").slider( "option", "max");

	$("#prijsSlider").slider({	values: [ minVal, maxVal ]	});
	$("#prijsMin").html(currencySymbol + minVal);
	$("#prijsMax").html(currencySymbol + maxVal);

	$('#brandsFieldset > input:checked').each( function (i) {
		$(this).attr("checked", false);
	});


	$('#taggroups > .scroller > .tagsFieldset > input:checked').each( function (i) {
		$(this).attr("checked", false);
	});


	$('#stylesFieldset > input:checked').each( function (i) {
		$(this).attr("checked", false);
	});

	$('#newFieldset > input:checked').each( function (i) {
		$(this).attr("checked", false);
	});

    if (useSorting)	{
		$.ajax({
			url: "/handleFilterSession.php",
			type: "POST",
			data: 'action=resetSorting',
			dataType: "html",
			cache: false
		});
	}

}

var actions = new Array();
var numberOfActions = 0;
var currentAction = 0;
function loadActions()
{
	$.ajax({
		url: "/ajaxrequests.php",
		type: "POST",
		data: 'action=loadActions',
		dataType: "html",
		cache: false,
		success: function(responseHtml) {
			var $holder = $('<div/>').html(responseHtml);
			numberOfActions = $('#numberOfActions', $holder).html();
			if (numberOfActions > 0) {
				$('#actieBalk').show();
				for (i = 1; i <= numberOfActions; i++) {
					actions[actions.length] = $('#actie_' + i, $holder).html();
				}
				showAction(true);
			}
		}
	});
}

function showAction(first)
{
	currentAction++;
	if (first == undefined) {
		$('#actionContainer').fadeOut(1000, function() {
			$('#actionContainer').html(actions[currentAction]);
			$('#actionContainer').fadeIn(1000);
		});
	} else {
		currentAction = 0;
		$('#actionContainer').html(actions[currentAction]);
	}

	if (currentAction == numberOfActions) {
		currentAction = 0;
	}
	if (numberOfActions > 1) {
		setTimeout('showAction();', 8000);
	}
}


function getProductHTML(product, page, teller)
{
	var productHTML='';

	/*
	if (teller == 3) {
		productLastClass = ' ';
	} else {
		productLastClass = '';
	}
	if (documentLocation.length == 1) {
		currentLink = product.link_static + '?p='+page;
	} else {
		currentLink = product.link_dynamic + '&p='+page;
	}
	*/

	if (product.type == 'stof' ) {

		productHTML = getProductStof(product);

	} else if (product.type == 'accessoire' ) {

		productHTML = getProductAccesoire(product);

	} else if (product.type == 'patroon' ) {

		productHTML = getProductPatroon(product);

	} else if (product.type == 'fournituur' ) {

		productHTML = getProductFournituur(product);

	} else {

		productHTML = getProductStof(product);

	}

	//alert(productHTML);
	return productHTML;

}


function getProductAccesoire(product) {

	var productHTML='';

	productHTML += '<div class="head" style="width:610px;">'
	productHTML += '<img class="head_left" height="25" width="6" alt="head_left" src="grafix/head_left.gif">'
	productHTML += ''
	productHTML += '			<h2 class="productOverview floatLeft">' + product.productnaam + '</h2>';
	productHTML += getVoorbeeldLinkHeader( product );
	productHTML += ''
	productHTML += '		<img class="head_right" height="25" width="6" alt="head_left" src="grafix/head_right.gif">'
	productHTML += '</div>'
	productHTML += ''
	productHTML += '<div class="box boxOverview relative">';
	if (product.isNew == 1) {
		productHTML += '<img class="newProduct" height="17" width="62" alt="nieuw_nl.png" src="/grafix/nieuw_nl.png">'
	}
	if (product.omschrijving == null) {
		product.omschrijving = '';
	}
	
	productHTML += '<a class="floatLeft zoom" href="/media/328x246/' + product.voorzijde +  '" rel="prettyPhoto" title="' + product.productnaam + '" >';
	productHTML += '<img class="floatLeft" src="/media/164x123/' + product.voorzijde +  '" alt="' + product.productnaam + '">';
	productHTML += '</a>'
	productHTML += '<div class="inhoud">'
	productHTML += '<table width="420" class="overzicht" style="font-size:12px;">'
	productHTML += '	<tr>'
	productHTML += '		<td colspan="3"><strong style="float:left;">Omschrijving:</strong><div class="floatLeft" style="text-indent:5px; width:330px;height:16px; overflow:hidden;">' + product.omschrijving + '</div><br>';
	productHTML += '		<strong style="float:left;">Eenheid:</strong> <div style="text-indent:5px; width:340px;height:16px; overflow:hidden;">' + product.eenheid + '</div><br>'
	productHTML += '		</td>'
	productHTML += '	</tr>'
	productHTML += ''
	productHTML += '	<tr>'
	productHTML += '		<td  colspan="3">'
	productHTML += ''
	productHTML += '			<div style="width:230px; height:16px; overflow:hidden;" class="floatLeft"><strong style="float:left; padding-right:5px;">Kleur:</strong> ' + product.kleur + '</div>'
	productHTML += '			<div class="floatRight" style="width:190px;"><strong style="float:left;padding-right:5px;">Prijs:</strong> <span class="userPrice floatLeft">' + product.prijs + '</span></div>'
	productHTML += ''
	productHTML += '		</td>'
	productHTML += '	</tr>'
	productHTML += '	<tr>'
	productHTML += '		<td colspan="2" >'
	productHTML += ''
	productHTML += '			<div class="floatLeft" style="width:420px;">'
	productHTML += '				<div class="floatLeft favoriteDetail" id="favo_' + product.structuurID + '">&nbsp;</div>';
	productHTML += '				<input style="margin-top:8px; float:right;" type="submit" class="submit_inSC submit_inSC_nl" value="&nbsp;" onclick="AddOrder(\'' + product.structuurID + '\',\'cartDiv\',\'nl\',\'add\');">';
	productHTML += '				<input style="margin-top:8px; float:right;" type="text" class="field quantity" name="quantity_' + product.structuurID + '" id="quantity_' + product.structuurID + '" size="1" value="1" onFocus="leegmaken(this.id, \'1\');" onBlur="vullen(this.id, \'1\');">';
	productHTML += '				<div class="floatRight"><strong style="margin-top:10px; margin-right:5px; float:right;">Aantal:</strong>&nbsp;</div>';
	productHTML += '			</div>'
	productHTML += '		</td>'
	productHTML += '	</tr>'
	productHTML += '</table>'
	productHTML += '</div>'
	productHTML += '<div class="clear">&nbsp;</div>'
	productHTML += '</div>'

	productHTML += getVoorbeeldLinks(product);

return productHTML;

}

function getProductPatroon(product) {

	var productHTML='';

	productHTML += '<div class="head" style="width:610px;">'
	productHTML += '<img class="head_left" height="25" width="6" alt="head_left" src="grafix/head_left.gif">'
	productHTML += '			<h2 class="productOverview floatLeft">' + product.productnaam + '</h2>';
	productHTML += getVoorbeeldLinkHeader( product );
	productHTML += '		<img class="head_right" height="25" width="6" alt="head_left" src="grafix/head_right.gif">'
	productHTML += '</div>'
	productHTML += '<div class="box boxOverview relative">';
	if (product.isNew == 1) {
		productHTML += '<img class="newProduct" height="17" width="62" alt="nieuw_nl.png" src="/grafix/nieuw_nl.png">'
	}
	if (product.omschrijving == null) {
		product.omschrijving = '';
	}
	productHTML += '<a class="floatLeft zoom" href="/media/328x246/' + product.voorzijde +  '" rel="prettyPhoto" title="' + product.productnaam + '" >';

	
	productHTML += '<img class="floatLeft" src="/media/164x123/' + product.voorzijde +  '" alt="' + product.productnaam + '">'
	productHTML += '</a>'
	productHTML += '<div class="inhoud">'
	productHTML += '<table width="420" class="overzicht" style="font-size:12px;">'
	productHTML += '	<tr>'
	productHTML += '		<td colspan="3"><strong style="float:left; ">Omschrijving:</strong> <div class="floatLeft" style="padding-left:5px; margin-top:-1px; width:340px;height:40px; line-height:18px;overflow:hidden;">' + product.omschrijving + '</div><br>'
	productHTML += '	<br><br>'
	productHTML += '		</td>'
	productHTML += '	</tr>'
	productHTML += '	<tr>'
	productHTML += '		<td  colspan="3">'
	productHTML += '			<div class="floatRight" style="width:160px;"><strong style="float:left;padding-right:5px;">Prijs:</strong> <span class="userPrice floatLeft">' + product.prijs + '</span><div class="floatLeft" style=" margin-left:5px;font-size:11px; width:60px; height:16px; overflow:hidden;">' + product.eenheid + '</div></div>'
	productHTML += '		</td>'
	productHTML += '	</tr>'
	productHTML += '	<tr>'
	productHTML += '		<td colspan="2" >'
	productHTML += '		<br>'
	productHTML += '			<div class="floatLeft" style="width:420px;">'
	productHTML += '				<div class="floatLeft favoriteDetail" id="favo_' + product.structuurID + '">&nbsp;</div>';
	productHTML += '				<input style="margin-top:8px; float:right;" type="submit" class="submit_inSC submit_inSC_nl" value="&nbsp;" onclick="AddOrder(\'' + product.structuurID + '\',\'cartDiv\',\'nl\',\'add\');">';
	productHTML += '				<input style="margin-top:8px; float:right;" type="text" class="field quantity" name="quantity_' + product.structuurID + '" id="quantity_' + product.structuurID + '" size="1" value="1" onFocus="leegmaken(this.id, \'1\');" onBlur="vullen(this.id, \'1\');">';
	productHTML += '				<div class="floatRight"><strong style="margin-top:10px; margin-right:5px; float:right;">Aantal:</strong>&nbsp;</div>';
	productHTML += '			</div>'
	productHTML += '		</td>'
	productHTML += '	</tr>'
	productHTML += '</table>'
	productHTML += '</div>'
	productHTML += '<div class="clear">&nbsp;</div>'
	productHTML += '</div>'

	productHTML += getVoorbeeldLinks(product);


	return productHTML;

}
function getProductFournituur(product) {

	var productHTML='';

	productHTML += '<div class="head" style="width:610px;">'
	productHTML += '	<img class="head_left" height="25" width="6" alt="head_left" src="grafix/head_left.gif">'
	productHTML += '			<h2 class="productOverview floatLeft">' + product.productnaam + '</h2>';
	productHTML += getVoorbeeldLinkHeader( product );
	productHTML += '			<img class="head_right" height="25" width="6" alt="head_left" src="grafix/head_right.gif">'
	productHTML += '	</div>'
	productHTML += '	<div class="box boxOverview relative">';
	if (product.isNew == 1) {
		productHTML += '<img class="newProduct" height="17" width="62" alt="nieuw_nl.png" src="/grafix/nieuw_nl.png">'
	}
	if (product.omschrijving == null) {
		product.omschrijving = '';
	}
	productHTML += '	<a class="floatLeft zoom" href="/media/328x246/' + product.voorzijde +  '" rel="prettyPhoto" title="' + product.productnaam + '" >';
	productHTML += '		<img class="floatLeft" src="/media/164x123/' + product.voorzijde +  '" alt="' + product.productnaam + '">';
	productHTML += '	</a>';
	productHTML += '	<div class="inhoud">'
	productHTML += '	<table width="420" class="overzicht" style="font-size:12px;">'
	productHTML += '		<tr>'
	productHTML += '			<td colspan="3"><strong style="float:left;">Omschrijving:</strong> <div class="floatLeft" style="text-indent:5px; width:340px;height:32px; overflow:hidden;">' + product.omschrijving + '</div><br>'
	productHTML += '			<strong style="float:left;">Geschikt voor:</strong> <div style="text-indent:5px; width:330px;height:16px; overflow:hidden;">' + product.geschikt_voor + '</div>'
	productHTML += '			</td>'
	productHTML += '		</tr>'
	productHTML += '		<tr>'
	productHTML += '			<td  colspan="3">'
	productHTML += '				<div style="width:230px; height:16px; overflow:hidden;" class="floatLeft"><strong style="float:left; padding-right:5px;">Kleur:</strong> ' + product.kleur +'</div>'
	productHTML += '				<div class="floatRight" style="width:170px;"><strong style="float:left;padding-right:5px;">Prijs:</strong> <span class="userPrice floatLeft">' + product.prijs +'</span><div class="floatLeft" style=" margin-left:5px;font-size:11px; width:60px; height:16px; overflow:hidden;">' + product.eenheid +'</div></div>'
	productHTML += '				<div class="clear">&nbsp;</div><div class="floatLeft"><strong style="float:left;padding-right:5px;">Breedte:</strong> ' + product.breedte + '</div>'
	productHTML += '			</td>'
	productHTML += '		</tr>'
	productHTML += '		<tr>'
	productHTML += '			<td colspan="2" >'
	productHTML += '				<div class="floatLeft" style="width:420px;">'
	productHTML += '				<div class="floatLeft favoriteDetail" id="favo_' + product.structuurID + '">&nbsp;</div>';
	productHTML += '				<input style="margin-top:8px; float:right;" type="submit" class="submit_inSC submit_inSC_nl" value="&nbsp;" onclick="AddOrder(\'' + product.structuurID + '\',\'cartDiv\',\'nl\',\'add\');">';
	productHTML += '				<input style="margin-top:8px; float:right;" type="text" class="field quantity" name="quantity_' + product.structuurID + '" id="quantity_' + product.structuurID + '" size="1" value="1" onFocus="leegmaken(this.id, \'1\');" onBlur="vullen(this.id, \'1\');">';
	productHTML += '				<div class="floatRight"><strong style="margin-top:10px; margin-right:5px; float:right;">Aantal:</strong>&nbsp;</div>';
	productHTML += '				</div>'
	productHTML += '			</td>'
	productHTML += '		</tr>'
	productHTML += '	</table>'
	productHTML += '	</div>'
	productHTML += '	<div class="clear">&nbsp;</div>'
	productHTML += '</div>'

	productHTML += getVoorbeeldLinks(product);


	return productHTML;


}

function getVoorbeeldLinkHeader( product ) {

	var html = '';

	if (product.productvoorbeeld != undefined) {

		// only first item
		var pvb = product.productvoorbeeld[0];

		html = '<a style="font-weight:normal; margin-right:10px;" class="floatRight" href="/media/400x400/' + pvb.img + '" rel="prettyPhoto[gallery_' + pvb.id + ']">Productvoorbeeld</a>';

		}

		return html;
}

function getVoorbeeldLinks( product ) {

	var html = '';

	if (product.productvoorbeeld != undefined) {

		$.each(product.productvoorbeeld, function( index, pvb ) {

			// first already present in header
			if (index > 0 ) {

				html += '<a style="font-weight:normal; margin-right:10px;" class="floatRight" href="/media/400x400/' + pvb.img + '" rel="prettyPhoto[gallery_' + pvb.id + ']"></a>';

			}

		});
	}

	return html;

}




function getProductStof(product) {

	var productHTML='';

	productHTML += '<div class="head" style="width:610px;">';
	productHTML += '	<img class="head_left" height="25" width="6" alt="head_left" src="grafix/head_left.gif">';
	productHTML += '			<h2 class="productOverview floatLeft">' + product.productnaam + '</h2>';
	productHTML += getVoorbeeldLinkHeader( product );

	productHTML += '			<img class="head_right" height="25" width="6" alt="head_left" src="grafix/head_right.gif">';
	productHTML += '	</div>';
	productHTML += '';
	productHTML += '	<div class="box boxOverview relative">';
	if (product.isNew == 1) {
		productHTML += '<img class="newProduct" height="17" width="62" alt="nieuw_nl.png" src="/grafix/nieuw_nl.png">'
	}
	if (product.omschrijving == null) {
		product.omschrijving = '';
	}
	productHTML += '	<a class="floatLeft zoom" href="/media/328x246/' + product.voorzijde +  '" rel="prettyPhoto" title="' + product.productnaam + '" >';
	productHTML += '		<img class="floatLeft" src="/media/164x123/' + product.voorzijde +  '" alt="' + product.productnaam + '">';
	productHTML += '	</a>';
	productHTML += '	<div class="inhoud">';
	productHTML += '	<table width="420" class="overzicht" style="font-size:12px;">';
	productHTML += '		<tr>';
	productHTML += '			<td colspan="3"><strong style="float:left;">Omschrijving:</strong><div class="floatLeft" style="text-indent:5px; width:335px;height:32px; overflow:hidden;">' + product.omschrijving + '</div><br>';
	productHTML += '			<strong style="float:left;">Geschikt voor:</strong> <div style="text-indent:5px; width:340px;height:16px; overflow:hidden;">' + product.geschikt_voor + '</div>';
	productHTML += '			</td>';
	productHTML += '		</tr>';
	productHTML += '		<tr>';
	productHTML += '			<td  colspan="3">';
	productHTML += '				<div style="width:230px; height:16px; overflow:hidden;" class="floatLeft"><strong style="float:left; padding-right:5px;">Kleur:</strong> ' + product.kleur + '</div>';
	productHTML += '				<div class="floatRight" style="width:170px;"><strong style="float:left;padding-right:5px;">Prijs:</strong> <span class="userPrice floatLeft">' + product.prijs + '</span> <div class="floatLeft" style=" margin-left:5px;font-size:11px; width:70px; height:16px; overflow:hidden;">' + product.eenheid + '</div></div>';
	productHTML += '				<div class="clear">&nbsp;</div><div class="floatLeft"><strong style="float:left;padding-right:5px;">Breedte:</strong> ' + product.breedte + '</div>';
	productHTML += '			</td>';
	productHTML += '		</tr>';
	productHTML += '		<tr>';
	productHTML += '			<td colspan="2" >';
	productHTML += '				<div class="floatLeft" style="width:420px;">';
	productHTML += '				<div class="floatLeft favoriteDetail" id="favo_' + product.structuurID + '">&nbsp;</div>';
	productHTML += '				<input alt="Voeg ' + product.productnaam + ' toe aan uw winkelwagen" style="margin-top:8px; float:right;" type="submit" class="submit_inSC submit_inSC_nl" value="&nbsp;" onclick="AddOrder(\'' + product.structuurID + '\',\'cartDiv\',\'nl\',\'add\');">';
	productHTML += '				<input style="margin-top:8px; float:right;" type="text" class="field quantity" name="quantity_' + product.structuurID + '" id="quantity_' + product.structuurID + '" size="1" value="1" onFocus="leegmaken(this.id, \'1\');" onBlur="vullen(this.id, \'1\');">';
	productHTML += '				<div class="floatRight"><strong style="margin-top:10px; margin-right:5px; float:right;">Aantal:</strong>&nbsp;</div>';
	productHTML += '				</div>';
	productHTML += '			</td>';
	productHTML += '		</tr>';
	productHTML += '	</table>';
	productHTML += '	</div>';
	productHTML += '	<div class="clear">&nbsp;</div>';
	productHTML += '</div>';
	productHTML += getVoorbeeldLinks(product);

	return productHTML;

}


function handleBrands(currentPage) {
alert('nothing');
		var productCountFound = productCountTotal = 0;
		var productHTML = '';
		var teller = 1;

		if (currentPage == undefined) {
			page = 1;
		} else {
			page = currentPage;
		}


		$.getScript('/handleFilterSession.php?action=loadSession&currentGroupID='+currentBrandID, function(data) {
			$.getJSON('/json/brands_'+currentBrandID+'_' + flag + '.json', false, function(data, textStatus){

				$.each(data.products, function() {
					if ( this.merk == currentBrandID) {
						if ( (productCountFound >= ( (page-1) * resultsPerPage) )
							&& (productCountFound < (page * resultsPerPage) )
						) {

							productHTML += getProductHTML(this, page, teller);

							if (teller == 3) {
								teller = 0;
							}

							teller++;
						}
						productCountFound++;
					}

					productCountTotal++;

				});

				pagingHTML = $.getPaging(page, productCountFound, resultsPerPage, 'handleBrands');
				$('.pageNr').html(pagingHTML);
				$('#concent_bb_search').html('<div class="pageNr">'  + pagingHTML + '</div><div class="clear"></div>' + productHTML + '<div class="clear"></div><div class="pageNr">'  + pagingHTML + '</div>');

			});//end getJSON

		});//end getScript

}

function addScript(url)
{
	var script=document.createElement('script');
	script.type='text/javascript';
	script.src=url;

	$("body").append(script);
}


function removeCurrencySymbol( price) {

	price = str_replace ('&#8364;', '', price, 1)

	return price;
}

function showAnswer(id,qid)
{
	if ($('#'+id).css('display') == 'none') {
		$('.opened_answer').removeClass('opened_answer').slideUp(500);
		$('.opened_question').removeClass('opened_question');
		$('#'+id).slideDown(500).addClass('opened_answer');
		$('#'+qid).addClass('opened_question');
		
	} else {
		$('#'+id).removeClass('opened_answer').slideUp(500);
		$('#'+qid).removeClass('opened_question');
	}
}


