﻿function FiltersView(id,model) {	
	this.htmlid = id;	
	this.model = model;
	this.filterLists = []
	this.init();
} 

FiltersView.prototype.init = function(){
	var htmlid = "#" + this.htmlid;
	var results = this.model.getFilters();
	var searchModel = this.model.searchmodel;
	var filterLists = this.filterLists;

	var filterList;

	$(htmlid).empty();
	
	$.each(results.filters, function(index, filter){
		
		if(filter.filterid == "career" || filter.filterid == "education" || filter.filterid == "business" ){

			filterLists[index] = $("<li></li>").attr('class','openclose').html("<a href='#' class='toggle'>" + filter.name + "</a>");
			$(htmlid).append(filterLists[index]);
			
			$(filterLists[index]).append($("<ul></ul>"));
			filterList = $("ul",$(filterLists[index]));
		}
	});
	this.initEvents();
	this.renderResults()
}
FiltersView.prototype.renderResults = function(){
	
	var htmlid = "#" + this.htmlid;
	var results = this.model.getFilters();
	var searchModel = this.model.searchmodel;
	var filterLists = this.filterLists;
	
	var filterList;
	var filterlistItem;
	var filterLink;
	$.each(results.filters, function(index, filter){
		
		if(filter.filterid == "career" || filter.filterid == "education" || filter.filterid == "business" ){
			
			filterList = $("ul",$(filterLists[index]));
			$(filterList).empty();

			$.each(filter.options, function(index, filteroptie){
				if (searchModel.filterOptionExists(filter.filterid,filteroptie.id,true)){
					filterlistItem =  $("<li></li>").attr('class','active');
					filterList.parent().addClass('active');
					filterList.slideDown("fast")
				}
				else{
					filterlistItem =  $("<li></li>");
				}
				$(filterList).append(filterlistItem)
				if(filteroptie.aantal =="0"){
					filterLink =  $("<a></a>").attr('class','filternoresult').attr('name',filter.filterid+"_"+filteroptie.id+"_"+filteroptie.name).html("<span>"+filteroptie.aantal+"</span>"+filteroptie.name );
				}
				else{
					filterLink =  $("<a></a>").attr('class','filteroption').attr('name',filter.filterid+"_"+filteroptie.id+"_"+filteroptie.name).html("<span>"+filteroptie.aantal+"</span>"+filteroptie.name );
				}
				
				$(filterlistItem).append(filterLink)
			});
		}
	});
}

FiltersView.prototype.initEvents = function(){

	$("#filter > li.openclose a.toggle").click(
	      function (e) {
			e.preventDefault();
			if($(this).parent().hasClass('active')){
				$(this).next().slideUp("fast",function(){
					$(this).parent().removeClass('active');
				});
			}else{
				$(this).parent().addClass('active');
				$(this).next().slideDown("fast");
				
			}

		}
	);

	
}