
/*
 * Manage the catalog section
 * 
 */

/* global directory_uri $ window */

$(function () {
	
	jQuery( "input.search-checkbox" ).checkboxradio({
      icon: false
    });
	
	if(jQuery('.list-loading').length){
		
		function disableBack() {		
			
			var sCurrentGroup = sessionStorage.getItem('active_group') !== null ? sessionStorage['active_group'] : '';
			var sCurrentSubGroup = sessionStorage.getItem('active_sub_group') !== null ? sessionStorage['active_sub_group'] : '';
			var sCurrentSubSubGroup = sessionStorage.getItem('active_sub_sub_group') !== null ? sessionStorage['active_sub_sub_group'] : '';
				
			if(sCurrentSubSubGroup != ''){
				sessionStorage.removeItem('active_sub_sub_group');
				sessionStorage['return_page'] = 'return';
				window.history.forward();		
			} else if(sCurrentSubGroup != ''){
				sessionStorage['return_page'] = 'return';
				sessionStorage.removeItem('active_sub_group');				
				window.history.forward();		
			} else if(sCurrentGroup != ''){
				sessionStorage['return_page'] = 'return';
				sessionStorage.removeItem('active_group');				
				window.history.forward();		
			} else {
				jQuery.clearConcept();
		
				sessionStorage.removeItem('active_sub_sub_group');
				sessionStorage.removeItem('active_sub_group');				
				sessionStorage.removeItem('active_group');
				sessionStorage.removeItem('active_article');
			}
		}
		
		setTimeout(disableBack(), 0);
		window.onunload = function () { null };
	
	}
	
	"use strict";

	var oArticlesContain = jQuery('div.articles-contain'),
		oArticlesResultCounter = jQuery('span.number-of-results'),
		oArticlesPageSelector = jQuery('div.page-selector'),		
		oArticleSet = false,		
		oSavedArticleSet = false,		
		oArticleFilterSets = [];		
		
	showWelcomeMessage();
	
	if(oArticlesContain.length > 0){
		
		var iItemsPerPage	= oArticlesContain.data('itemsperpage'),
			iPaginationId	= oArticlesContain.data('page'),
			sDataSource		= oArticlesContain.data('source');

		/*
		 * Init
		 */

		setLoadingOverlay('fadein');
		
		const data = {
			
			datasource:		sDataSource,
			itemsperpage:	iItemsPerPage,
			paginationid:	iPaginationId,
			keyword:		'',
			group:			'',
			category:		'',
			sorting:		''
			
		};
				
		getArticles(data);
		getCategories();
	
	}
	
	function showWelcomeMessage(){
		var filterButton = sessionStorage.getItem('filter_section_button') !== null ? sessionStorage['filter_section_button'] : '';				
		
		$('#welcome-container').addClass('active');				
	}	
	
	function showFilterButton(){	
		//jQuery('#welcome-container').removeClass('active');		
		jQuery('#filters-container').addClass('active');	
	}
	
	function getCategories() {
		
		oSavedCategoriesSet = sessionStorage.getItem('categories_set') !== null ? sessionStorage['categories_set'] : '';
						
		if(oSavedCategoriesSet != ''){
			
			var oData = $.parseJSON(oSavedCategoriesSet);
			
			oCategoriesSet = (oData === false ? false : oData);
			
			/*
			 * Parse articles			 
			 */
				
		} else {
		
			$.post(baseHref() + 'catalog', { 

				module: 'getCategories'
				
			}, function(data) {
				
				sessionStorage['categories_set'] = data;
				
				var oData = $.parseJSON(data),
					iTotalItems,
					sHTML;
				
							
				oCategoriesSet = (oData === false ? false : oData);
				
				sessionStorage['categories_set'] = data;
				
				/*
				 * Parse articles			 
				 */

			});
		}		

	}
	
	function getArticles(data) {
		
		var sDataSource		= data.datasource,
			iItemsPerPage	= data.itemsperpage,
			iPaginationId	= data.paginationid,
			sKeyword		= data.keyword,
			sGroup			= data.group,
			sCategory		= data.category,
			sSort			= data.sorting;
		
		oSavedArticleSet = ''; //sessionStorage.getItem('article_set') !== null ? sessionStorage['article_set'] : '';
				
		if(oSavedArticleSet != ''){
			
			var oData = $.parseJSON(oSavedArticleSet);
			
			oArticleSet = (oData === false ? false : oData);
			
			/*
			 * Parse articles			 
			 */

			parseArticles(iPaginationId, iItemsPerPage);

			/*
			 * Lazy load
			 */

			//lazyLoad();
				
		} else {
			
			$.post(baseHref() + 'catalog', { 

				module: 'getArticles',
				department: sDataSource,
				paginationid: iPaginationId,
				itemsperpage: iItemsPerPage,
				keyword: sKeyword,
				group: sGroup,
				category: sCategory,
				sort: sSort
				
			}, function(data) {
				
				var oData = $.parseJSON(data),
					iTotalItems,
					sHTML;
				
							
				oArticleSet = (oData === false ? false : oData);
				
				//sessionStorage['article_set'] = data;
				
				/*
				 * Parse articles			 
				 */

				parseArticles(iPaginationId, iItemsPerPage);

				/*
				 * Lazy load
				 */

				//lazyLoad();

			});
		}		

	}
	
	function setPagination(iTotalItems, iPaginationId, iItemsPerPage) {
				
		var pages = Math.ceil(iTotalItems/iItemsPerPage);		
		var pagesNext = iPaginationId+1;		
		var pagesPrevious = iPaginationId-1;

		jQuery('.page-selector').data('iTotalItems',iTotalItems);		
		jQuery('.page-selector').data('iItemsPerPage',iItemsPerPage);
		
		var sHTML = '';
		
		if(iPaginationId > 1){				
			sHTML += '<span id="to-previous" class="previous" data-page="' + pagesPrevious + '"></span> ';
		} else {
			sHTML += '<span class="previous inactive"></span> ';
		}		
		
		sHTML += '<select id="select-page" class="select-page" name="page">';
			
			for (let i = 1; i <= pages; i++) {
			
				sHTML += '<option value="' + i + '"' + (iPaginationId == i ? ' selected' : false) + '>' + i + '/' + pages + '</option>';
			
			}	
			
		sHTML += '</select>';		
		
		if(iPaginationId < (pages)){				
			sHTML += ' <span id="to-next" class="next" data-page="' + pagesNext + '"></span>';
		} else {
			sHTML += ' <span class="next inactive"></span>';
		}
		
		oArticlesPageSelector.html(sHTML);
		
		return;
		
	}
	
	jQuery(document).on("click","#parse-search",function() {
				
		setLoadingOverlay('fadein');
        
		var iNewPage = '1';
		var iTotalItems = jQuery('.page-selector').data('iTotalItems');		
		var iItemsPerPage = jQuery('.page-selector').data('iItemsPerPage');

		// categorie
		var filterCategoryVal = typeof  jQuery('#filter-for-category') != 'undefined' && jQuery('#filter-for-category').val() != '0' ? jQuery('#filter-for-category').val() : '';
		
		if(filterCategoryVal == '' || typeof filterCategoryVal == 'undefined'){
			sessionStorage.removeItem('filter_category');
		} else {
			sessionStorage['filter_category'] = filterCategoryVal;
		}
		
		// merk
		var filterBrandVal = typeof  jQuery('#filter-for-brand') != 'undefined' && jQuery('#filter-for-brand').val() != '0' ? jQuery('#filter-for-brand').val() : '';
		
		if(filterBrandVal == '' || typeof filterBrandVal == 'undefined'){
			sessionStorage.removeItem('filter_brand');
		} else {
			sessionStorage['filter_brand'] = filterBrandVal;
		}
		
		// bouwjaar
		var filterConstructionYearVal = typeof  jQuery('#filter-for-constructionyear') != 'undefined' && jQuery('#filter-for-constructionyear').val() != '0' ? jQuery('#filter-for-constructionyear').val() : '';
		
		if(filterConstructionYearVal == '' || typeof filterConstructionYearVal == 'undefined'){
			sessionStorage.removeItem('filter_constructionyear');
		} else {
			sessionStorage['filter_constructionyear'] = filterConstructionYearVal;
		}		
		
		var filterStockVal = typeof  jQuery('#filter-for-stock') != 'undefined' && jQuery('#filter-for-stock').is(':checked') ? true : false;
		if(filterStockVal){
			sessionStorage['filter_stock'] = filterStockVal;
		} else {
			sessionStorage.removeItem('filter_stock');
		}
		
		var filterExpectedVal = typeof  jQuery('#filter-for-expected') != 'undefined' && jQuery('#filter-for-expected').is(':checked') ? true : false;
		if(filterExpectedVal){
			sessionStorage['filter_expected'] = filterExpectedVal;
		} else {
			sessionStorage.removeItem('filter_expected');
		}
		
		var filterReservedVal = typeof  jQuery('#filter-for-reserved') != 'undefined' && jQuery('#filter-for-reserved').is(':checked') ? true : false;
		if(filterReservedVal){
			sessionStorage['filter_reserved'] = filterReservedVal;
		} else {
			sessionStorage.removeItem('filter_reserved');
		}
		
		var filterSoldVal = typeof  jQuery('#filter-for-sold') != 'undefined' && jQuery('#filter-for-sold').is(':checked') ? true : false;
		if(filterSoldVal){
			sessionStorage['filter_sold'] = filterSoldVal;
		} else {
			sessionStorage.removeItem('filter_sold');
		}
		
		var filterKeywordVal = typeof  jQuery('#filter-for-keyword') != 'undefined' && jQuery('#filter-for-keyword').val();
		if(filterKeywordVal){
			sessionStorage['filter_keyword'] = filterKeywordVal;
		} else {
			sessionStorage.removeItem('filter_keyword');
		}
		
		var filterChassisnumberVal = typeof  jQuery('#filter-for-chassisnumber') != 'undefined' && jQuery('#filter-for-chassisnumber').val();
		if(filterChassisnumberVal){
			sessionStorage['filter_chassisnumber'] = filterChassisnumberVal;
		} else {
			sessionStorage.removeItem('filter_chassisnumber');
		}
		
		parseSearch(iNewPage, iItemsPerPage);
    });
	
	jQuery(document).on("change","#select-page",function() {
		
		setLoadingOverlay('fadein');
        
		var iNewPage = parseInt(jQuery(this).val());
		var iTotalItems = jQuery('.page-selector').data('iTotalItems');		
		var iItemsPerPage = jQuery('.page-selector').data('iItemsPerPage');
		
		jQuery(window).scrollTop(0);
		
		parseArticles(iNewPage,iItemsPerPage);
    });
	
	jQuery(document).on("click","#to-next",function() {
		
		setLoadingOverlay('fadein');
        
		var iNewPage = parseInt(jQuery(this).data('page'));
		var iTotalItems = jQuery('.page-selector').data('iTotalItems');		
		var iItemsPerPage = jQuery('.page-selector').data('iItemsPerPage');
		
		jQuery(window).scrollTop(0);
				
		parseArticles(iNewPage,iItemsPerPage);
    });
	
	jQuery(document).on("click","#to-previous",function() {
		
		setLoadingOverlay('fadein');
        
		var iNewPage = parseInt(jQuery(this).data('page'));
		var iTotalItems = jQuery('.page-selector').data('iTotalItems');		
		var iItemsPerPage = jQuery('.page-selector').data('iItemsPerPage');
		
		jQuery(window).scrollTop(0);
		
		parseArticles(iNewPage,iItemsPerPage);
    });
	
	function setResultsFound(iTotal) {
		
		if(iTotal == '0'){
			oArticlesResultCounter.html('');
		} else if(iTotal == '1') {
			oArticlesResultCounter.html( ' (' + iTotal + ')');			
		} else {
			oArticlesResultCounter.html(' (' + iTotal + ')');			
		}		
	}	
	
	function parseSearch(iPaginationId,iItemsPerPage) {		
		
		jQuery('body').removeClass('filters-active');
	
		parseArticles(iPaginationId,iItemsPerPage);
	}
	
	function parseArticles(iPaginationId,iItemsPerPage) {
		
		sessionStorage.removeItem('temp_article');
		
		if(typeof oArticleSet.articles.data == 'undefined'){
			
			var sHTML = '<div class="no-items-available">Er zijn momenteel geen advertenties beschikbaar.<br><br>Start met het aanmaken van een advertentie</div>';
			var oListContain = jQuery('div.articles-contain');
		
			oListContain.html(sHTML);
			
			setLoadingOverlay('fadeout');
			
			return;
		} else if(oArticleSet.articles.data == 'false' || oArticleSet.articles.data == false){
			var sHTML = '<div class="no-items-timeout">Er kunnen momenteel geen advertenties worden opgehaald.</div>';
			var oListContain = jQuery('div.articles-contain');
		
			oListContain.html(sHTML);
			
			setLoadingOverlay('fadeout');
			
			return;
		}		
		
		var oArticleSetNew = [];
		var countNewItems = 0;
		
		var filterConstructionYearSet = [];
		var filterCategorySet = [];
		var filterCategoryNames = {};
		var filterBrandSet = [];
				
		var filterCategory = sessionStorage.getItem('filter_category') !== null ? sessionStorage['filter_category'] : '';
		var filterBrand = sessionStorage.getItem('filter_brand') !== null ? sessionStorage['filter_brand'] : '';
		var filterConstructionYear = sessionStorage.getItem('filter_constructionyear') !== null ? sessionStorage['filter_constructionyear'] : '';
		
		var filterKeyword = sessionStorage.getItem('filter_keyword') !== null ? sessionStorage['filter_keyword'] : '';
		var filterChassisnumber = sessionStorage.getItem('filter_chassisnumber') !== null ? sessionStorage['filter_chassisnumber'] : '';
			
		var filterStock = sessionStorage.getItem('filter_stock') !== null ? sessionStorage['filter_stock'] : '';
		var filterExpected = sessionStorage.getItem('filter_expected') !== null ? sessionStorage['filter_expected'] : '';
		var filterReserved = sessionStorage.getItem('filter_reserved') !== null ? sessionStorage['filter_reserved'] : '';
		var filterSold = sessionStorage.getItem('filter_sold') !== null ? sessionStorage['filter_sold'] : '';
						
		if(filterCategory != '' || filterBrand != '' || filterConstructionYear != '' || filterStock != '' || filterExpected != '' || filterReserved != '' || filterSold != '' || filterKeyword != '' || filterChassisnumber != ''){
			jQuery('#filters').addClass('active_search');
		} else {
			jQuery('#filters').removeClass('active_search');
		}
		
		jQuery.each(oArticleSet.articles.data, $.proxy(function(index, item) {
			
			var iSkipThisStatus = false;
			
			// filter status	
			if(filterStock != '' || filterExpected != '' || filterReserved != '' || filterSold != '' || filterKeyword != ''  || filterChassisnumber != '' ){				
				
				var iSkipForStock = false;
				var iSkipForExpected = false;
				var iSkipForReserved = false;
				var iSkipForSold = false;
				var iSkipForKeyword = false;
				var iSkipForChassisnumber = false;
				
				if((filterStock != '' && item.stock == false)){					
					iSkipForStock = true;
				}

				if((filterExpected != '' && item.expected == false)){					
					iSkipForExpected = true;
				}

				if((filterReserved != '' && item.reserved == false)){					
					iSkipForReserved = true;
				}

				if((filterSold != '' && item.sold == false)){					
					iSkipForSold = true;
				}
				
				var sThisTitle = item.title;
				var sThisId = item.id;

				if((filterKeyword != '')){					
					if(sThisTitle.includes(filterKeyword) || sThisId == filterKeyword){
					} else {					
						iSkipForKeyword = true;
					}
				}
				
				var sThisChassisnumber = item.title;

				if((filterChassisnumber != '')){					
					if(sThisChassisnumber.includes(filterChassisnumber)){
					} else {					
						iSkipForChassisnumber = true;
					}
				}
								
				if((filterChassisnumber != '' && !iSkipForChassisnumber) || (filterKeyword != '' && !iSkipForKeyword) || (filterStock != '' && !iSkipForStock) || (filterExpected != '' && !iSkipForExpected) || (filterReserved != '' && !iSkipForReserved) || (filterSold != '' && !iSkipForSold)){	
					iSkipThisStatus = false;
				} else {
					iSkipThisStatus = true;
				}				
			}			
			
			// filter bouwjaar opties	
			if(item.constructionYear != '0'){				
				var iThisConstructionYear = parseInt(item.constructionYear);				
				filterConstructionYearSet.indexOf(iThisConstructionYear) === -1 ? filterConstructionYearSet.push(iThisConstructionYear) : false;
			}
			
			// filter merk opties	
			if(item.brand != ''){				
				filterBrandSet.indexOf(capitalizeFirstLetterOfString(item.brand)) === -1 ? filterBrandSet.push(capitalizeFirstLetterOfString(item.brand)) : false;
			}
			
			// filter category opties	
			if(item.category != ''){
				
				var sCurrentCategoryNameOriginal = item.category;
				var sCurrentCategoryName = item.category;
				
				if(sCurrentCategoryName == 'Tenttrailer'){
					sCurrentCategoryName = 'vouwwagen';
				} else if(sCurrentCategoryName == 'Mobilehome'){
					sCurrentCategoryName = 'stacaravan';				
				} else if(sCurrentCategoryName == 'Boat'){
					sCurrentCategoryName = 'boot';				
				} else if(sCurrentCategoryName == 'Boattrailer'){
					sCurrentCategoryName = 'boottrailer';				
				} else if(sCurrentCategoryName == 'Engine'){
					sCurrentCategoryName = 'motor';				
				} else if(sCurrentCategoryName == 'Trailer'){
					sCurrentCategoryName = 'aanhangwagen';				
				}

				var postDataCategory = {};
				
				postDataCategory.categoryOriginal = sCurrentCategoryNameOriginal;
				postDataCategory.category = capitalizeFirstLetterOfString(sCurrentCategoryName);
								
				//if(filterCategorySet.indexOf(capitalizeFirstLetterOfString(sCurrentCategoryNameOriginal)) === -1){				
					//filterCategorySet.push({[sCurrentCategoryNameOriginal] : postDataCategory});				
					filterCategorySet[sCurrentCategoryNameOriginal] = postDataCategory;	

					filterCategoryNames[sCurrentCategoryNameOriginal] = capitalizeFirstLetterOfString(sCurrentCategoryName);
				//}
				
				//filterCategorySet.indexOf(capitalizeFirstLetterOfString(sCurrentCategoryNameOriginal)) === -1 ? filterCategorySet.push(sCurrentCategoryNameOriginal,postDataCategory) : false;
			}		
			
			var skipThisItem = false;

			if(filterCategory != ''){
				if(item.category != filterCategory){
					skipThisItem = true;					
				}
			}

			if(filterBrand != ''){
				if(item.brand != filterBrand){
					skipThisItem = true;					
				}
			}

			if(filterConstructionYear != ''){
				if(item.constructionYear != filterConstructionYear){
					skipThisItem = true;					
				}
			}
			
			if(iSkipThisStatus){
				skipThisItem = true;
			}
			
			if(!skipThisItem){			
				countNewItems++;
				oArticleSetNew[countNewItems] = item;
			}
			
		}, this));

		jQuery.initMarktplaats();
		
		filterCategoryNames = sortObj(filterCategoryNames);		
		var filterCategoryKeys = Object.keys(filterCategoryNames);
		
		filterCategorySet.sort();		
		
		filterBrandSet.sort();
		
		filterConstructionYearSet.sort();
		filterConstructionYearSet.reverse();
		
		oArticleFilterSets['category'] = filterCategoryKeys;
		oArticleFilterSets['categorySet'] = filterCategoryNames;
		oArticleFilterSets['brand'] = filterBrandSet;
		oArticleFilterSets['constructionYear'] = filterConstructionYearSet;
		
		oArticleFilterSets['stock'] = filterStock;
		oArticleFilterSets['expected'] = filterExpected;
		oArticleFilterSets['reserved'] = filterReserved;
		oArticleFilterSets['sold'] = filterSold;	
		
		oArticleFilterSets['keyword'] = filterKeyword;	
		oArticleFilterSets['chassisnumber'] = filterChassisnumber;	
		
		oArticleFilterSets['price'] = '';
		
		activateFilters(oArticleFilterSets);
		
		oArticleSet.articles.dataFiltered = oArticleSetNew;
		
		var oArticleSetNewReverse = oArticleSetNew.reverse();	
		
		var sHTML = '';
		var oListContain = jQuery('div.articles-contain');
				
		sHTML = generateArticlesHTML(oArticleSet, iPaginationId, iItemsPerPage);
		
		oListContain.html(sHTML);
			
		/*
		 * Pagination
		 */

		//setPagination(countNewItems, iPaginationId, iItemsPerPage);
		
		/*
		 * Show the amount of results found
		 */
		 
		setResultsFound(countNewItems);	
		
		/*
		 * Show filters buttony
		 */
		
		showFilterButton();
		
		/*
		 * Loading overlay
		 */
		
		setLoadingOverlay('fadeout');
		
	}
	
	function activateFilters(oArticleFilterSets) {
		
		if(oArticleFilterSets.stock){
			if(jQuery('#filter-for-stock').length){
				if(oArticleFilterSets.stock){
					jQuery('#filter-for-stock').prop('checked', true);
					jQuery('#filter-for-stock').button( "refresh" );
				}
			}			
		}
		
		if(oArticleFilterSets.expected){
			if(jQuery('#filter-for-expected').length){
				if(oArticleFilterSets.expected){
					jQuery('#filter-for-expected').prop('checked', true);
					jQuery('#filter-for-expected').button( "refresh" );
				}
			}			
		}
		
		if(oArticleFilterSets.reserved){
			if(jQuery('#filter-for-reserved').length){
				if(oArticleFilterSets.reserved){
					jQuery('#filter-for-reserved').prop('checked', true);
					jQuery('#filter-for-reserved').button( "refresh" );
				}
			}			
		}
		
		if(oArticleFilterSets.sold){
			if(jQuery('#filter-for-sold').length){
				if(oArticleFilterSets.sold){
					jQuery('#filter-for-sold').prop('checked', true);
					jQuery('#filter-for-sold').button( "refresh" );
				}
			}			
		}	
		
		if(oArticleFilterSets.keyword){
			if(jQuery('#filter-for-keyword').length){
				if(oArticleFilterSets.keyword){
					jQuery('#filter-for-keyword').val(oArticleFilterSets.keyword);
				}
			}			
		}		
		
		if(oArticleFilterSets.chassisnumber){
			if(jQuery('#filter-for-chassisnumber').length){
				if(oArticleFilterSets.chassisnumber){
					jQuery('#filter-for-chassisnumber').val(oArticleFilterSets.chassisnumber);
				}
			}			
		}		

		if(oArticleFilterSets.category){
			
			var filterCategorySelected = sessionStorage.getItem('filter_category') !== null ? sessionStorage['filter_category'] : '';
			
			jQuery('#filter-category').html(
				jQuery(document.createElement('select')).prop({
					class: 'filter-select',
					id: 'filter-for-category',
					name: 'category',
					'data-placeholder': 'Kies een categorie',
					'data-allow-clear': 'false'
				})
			);
			
			jQuery('#filter-for-category').append(jQuery(document.createElement('option')).prop({}));			
			
			jQuery.each(oArticleFilterSets.category, $.proxy(function(indexCategory, nameCategory) {
			
				if(nameCategory == filterCategorySelected){
					jQuery('#filter-for-category').append(jQuery(document.createElement('option')).prop({
						value: nameCategory,
						text: oArticleFilterSets.categorySet[nameCategory],
						selected: true 
					}));
				} else {				
					jQuery('#filter-for-category').append(jQuery(document.createElement('option')).prop({
						value: nameCategory,
						text: oArticleFilterSets.categorySet[nameCategory]
					}));
				}
			}, this));
			
			jQuery('#filter-for-category').select2({
				allowClear: true,
				width: '100%',
				placeholder: 'Kies categorie',
				language: "nl",
				minimumResultsForSearch: -1,
				dropdownParent: jQuery('#filter-container-category')
			});
			
			jQuery('#filter-for-category').on('select2:clear', function (e) {			
				jQuery(this).data('unselecting', true);
			});	

			jQuery('#filter-for-category').on('select2:opening', function (e) {
				
				 if (jQuery(this).data('unselecting')) {
					jQuery(this).removeData('unselecting');
					e.preventDefault();
				}
			});
		}		
		
		if(oArticleFilterSets.brand){
			
			var filterBrandSelected = sessionStorage.getItem('filter_brand') !== null ? sessionStorage['filter_brand'] : '';
			
			jQuery('#filter-brand').html(
				jQuery(document.createElement('select')).prop({
					class: 'filter-select',
					id: 'filter-for-brand',
					name: 'brand',
					'data-placeholder': 'Kies een merk',
					'data-allow-clear': 'false'
				})
			);
			
			jQuery('#filter-for-brand').append(jQuery(document.createElement('option')).prop({}));
			
			jQuery.each(oArticleFilterSets.brand, $.proxy(function(index, brand) {
				
				if(brand == filterBrandSelected){
					jQuery('#filter-for-brand').append(jQuery(document.createElement('option')).prop({
						value: brand,
						text: brand,
						selected: true 
					}));
				} else {				
					jQuery('#filter-for-brand').append(jQuery(document.createElement('option')).prop({
						value: brand,
						text: brand 
					}));
				}
			}, this));			
			
			jQuery('#filter-for-brand').select2({
				allowClear: true,
				width: '100%',
				placeholder: 'Kies merk',
				language: "nl",
				dropdownParent: jQuery('#filter-container-brand')
			});
		
			jQuery('#filter-for-brand').on('select2:clear', function (e) {			
				jQuery(this).data('unselecting', true);
			});	

			jQuery('#filter-for-brand').on('select2:opening', function (e) {
				
				 if (jQuery(this).data('unselecting')) {
					jQuery(this).removeData('unselecting');
					e.preventDefault();
				}
			});
		}
		
		if(oArticleFilterSets.constructionYear){
			
			var filterConstructionYearSelected = sessionStorage.getItem('filter_constructionyear') !== null ? sessionStorage['filter_constructionyear'] : '';
			
			jQuery('#filter-constructionyear').html(
				jQuery(document.createElement('select')).prop({
					class: 'filter-select',
					id: 'filter-for-constructionyear',
					name: 'constructionyear',
					'data-placeholder': 'Kies een bouwjaar',
					'data-allow-clear': 'false'
				})
			);
			
			jQuery('#filter-for-constructionyear').append(jQuery(document.createElement('option')).prop({}));
			
			jQuery.each(oArticleFilterSets.constructionYear, $.proxy(function(index, constructionYear) {
				
				if(constructionYear == filterConstructionYearSelected){
					jQuery('#filter-for-constructionyear').append(jQuery(document.createElement('option')).prop({
						value: constructionYear,
						text: constructionYear,
						selected: true 
					}));
				} else {				
					jQuery('#filter-for-constructionyear').append(jQuery(document.createElement('option')).prop({
						value: constructionYear,
						text: constructionYear 
					}));
				}
			}, this));			
			
			jQuery('#filter-for-constructionyear').select2({
				allowClear: true,
				width: '100%',
				placeholder: 'Kies bouwjaar',
				language: "nl",
				dropdownParent: jQuery('#filter-container-constructionyear')
			});
		
			jQuery('#filter-for-constructionyear').on('select2:clear', function (e) {			
				jQuery(this).data('unselecting', true);
			});	

			jQuery('#filter-for-constructionyear').on('select2:opening', function (e) {
				
				 if (jQuery(this).data('unselecting')) {
					jQuery(this).removeData('unselecting');
					e.preventDefault();
				}
			});
		}
	}
	
	function generateArticlesHTML(oData,iPaginationId,iItemsPerPage) {	

		var SHTML = '';			
		var countItems = 0;
		var startItems = (iPaginationId*iItemsPerPage)-iItemsPerPage;
		var stopItems = (iPaginationId*iItemsPerPage);
		
		
		
		jQuery.each(oData.articles.dataFiltered, $.proxy(function(index, itemArticle) {
				
			if(typeof itemArticle != 'undefined'){			
					
				countItems++;
				
				//var hiddenElement = 'invisible';
				var hiddenElement = 'visible';
				var sSpecs = '';
				
				if(countItems > startItems && countItems <= stopItems){
					//hiddenElement = 'visible';			
				}			
					
				SHTML += '<div class="griditem-container">';
					SHTML += '<a href="/edit/' + itemArticle.id + '/" class="griditem '+ hiddenElement + (countItems == 1 ? ' first' : false) + '" id="artice-' + itemArticle.id + '">';
						SHTML += '<div class="griditem-main" >';
							SHTML += '<div class="image' + (itemArticle.image != '' ? '" style="background-image:url(' + itemArticle.image + ');' : ' placeholder') + '"></div>';
							SHTML += '<div class="title">' + itemArticle.title + '</div>';
							SHTML += '<div class="specs">';
								
								if(itemArticle.constructionYear != '' && itemArticle.constructionYear > '0'){
									if(sSpecs == ''){
										sSpecs += itemArticle.constructionYear;
									} else {
										sSpecs += ' | ' + itemArticle.constructionYear;								
									}
								}
								
								if(itemArticle.licensePlate != ''){
									if(sSpecs == ''){
										sSpecs += itemArticle.licensePlate;
									} else {
										sSpecs += ' | ' + itemArticle.licensePlate;								
									}
								}
								
								SHTML += sSpecs;
								
							SHTML += '</div>';
							SHTML += '<div class="status">';
							
								var sOnlineOrOffLine = 'offline';
								var sStockStatus = 'stock';						
								
								SHTML += '<span class="status-extra-info">';
								
									if(itemArticle.expected){
										sStockStatus = 'expected';
										//SHTML += '- Verwacht -';
									}
									
									if(itemArticle.reserved){
										sStockStatus = 'reserved';
										//SHTML += '- Gereserveerd -';
									}
									
									if(itemArticle.sold){
										sStockStatus = 'sold';
										//SHTML += '- Verkocht -';
									}

								SHTML += '</span><br>';
							
								if(typeof itemArticle.verlopen != 'undefined' && itemArticle.verlopen === true){
									sOnlineOrOffLine = 'offline';
									SHTML += '<span class="statusindicator expired">' + itemArticle.afloopdatum + '</span>';
								} else if(itemArticle.stock){
									sOnlineOrOffLine = 'online';
									SHTML += '<span class="statusindicator online">Online</span>';
								} else {
									sOnlineOrOffLine = 'offline';
									SHTML += '<span class="statusindicator offline">Offline</span>';							
								}
								
							SHTML += '</div>';
							SHTML += '<div class="price">&euro; ' + accounting.formatNumber(itemArticle.price,0,".", ",") + '</div>';
						SHTML += '</div>';		
					SHTML += '</a>';

					var mpArticleStatus = '';
					
					if(typeof itemArticle.marktplaatStatus != 'undefined' && itemArticle.marktplaatStatus == 'active'){
						mpArticleStatus = ' active';						
					} else if(typeof itemArticle.marktplaatStatus != 'undefined' && itemArticle.marktplaatStatus == 'pending'){
						mpArticleStatus = ' pending';
					}
					
					SHTML += '<div class="marktplaats marktplaats-actions '+ mpArticleStatus +'" id="marktplaats-status-' + itemArticle.id + '" data-articleid="' + itemArticle.id + '">Marktplaats</div>';
				SHTML += '</div>';		
			}
			
		}, this));		
		
		return SHTML;
		
	}
	
	jQuery(document).on("click",".griditem-main",function(e) {
		
		var thisParent = jQuery(this).closest('.griditem');		
		jQuery('.griditem').not(thisParent).removeClass('active');		
		thisParent.toggleClass('active');
		
	});
	
	jQuery(document).on("click",".parse-status",function(e) {	

		var sReturnOnlineStatus = jQuery('input[name="set-online-status"]:checked').val();
		var sReturnStockStatus = jQuery('input[name="set-stock-status"]:checked').val();
		var sCurrentArticleID = jQuery('#set-status-item-id').val();
		
		if(typeof jQuery('#artice-'+sCurrentArticleID) != 'undefined' && jQuery('#artice-'+sCurrentArticleID).length == 1 && sCurrentArticleID > 0){
			
			jQuery('#artice-'+sCurrentArticleID).find('.statusindicator').removeClass('offline').removeClass('online').addClass(sReturnOnlineStatus).html(sReturnOnlineStatus);			
			jQuery('#artice-'+sCurrentArticleID).find('.set-status').data('online',sReturnOnlineStatus);
			jQuery('#artice-'+sCurrentArticleID).find('.set-status').data('status',sReturnStockStatus);
						
			if(sReturnStockStatus == 'stock'){				
				jQuery('#artice-'+sCurrentArticleID).find('.status-extra-info').html('');
			} else {
				
				if(sReturnStockStatus == 'reserved'){
					sReturnStockStatus = 'Gereserveerd';
				} else if(sReturnStockStatus == 'expected'){
					sReturnStockStatus = 'Verwacht';					
				} else if(sReturnStockStatus == 'sold'){
					sReturnStockStatus = 'Verkocht';
				}
				
				jQuery('#artice-'+sCurrentArticleID).find('.status-extra-info').html('-' + sReturnStockStatus + '-');
			}
		}		
			
		jQuery('body').removeClass('status-active');
		
	});		
});