/*
 * Filter class applies dynamic functionality to filters
 * 
 * Requirements
 *	- jQuery >= 1.4
 * 	- Forms class
 * 
 * @author Robin van Baalen <robin@stylr.nl>
 * @link http://stylr.nl
 * @version 0.1.5
 *
 * CHANGELOG
 *	0.1		First release
 *	0.1.1	Fixed "noResults is not a function"-error
 *	0.1.2	noResults is now handled by the server. Thisway, there always is a result.
 *	0.1.3	updateCounter() and updateTitle() are now private functions and executed by update().
 *	0.1.4	Added filter reset button to clear the filter
 *	0.1.5b	New update() function updates the title contents (including result counter).
 *	0.1.5	No results title handler updated and fixed some bugs
 *	0.1.6	Read more links are now external. Temp fix.
 *	0.2.0	Customized for Toolbox Assessment
 * 
 */

function Filter(strFormId){
	this.form 	= "#" + strFormId;
	this.file 	= "/filter";
	this.tpl 	= $("li:first", "#results").clone();
	this.title	= $("h2.dark-big", ".left");
	this.loader = $("li.loader", "#results");
	this.msg	= {
		"defaultTitle" : "Kennisbank",
		"resultTitle" : "Aantal resultaten: ", // keep the last space there!
		"noResults" : "Geen resultaten.",
		"searchResults" : "Zoek resultaten voor: " // Still need to implement this.
	};

	this.load();
}

/**
 * Constructor of the class
 */
Filter.prototype.load = function(){
	var __this = this;
	

	// Template cache
	__this.tpl
		.removeClass("loader")
		.addClass("result")
		.append("<h3><a /></h3>")
		.find("img")
			.attr("src", "");
	
	window.tpl = __this.tpl;

	$(".vf__navigation", __this.form).remove();

	$("#filterOptions div.option:last").remove();
	$(__this.form).append("<div class=\"option\" />").find("div:last").append(	
		Forms.button("Filter wissen", function(){
			$(__this.form)[0].reset();
			$(__this.form).trigger("submit");
			return false;
		})
	);

	$(__this.form)
		.bind("submit", function(){
			var data = $(this).serializeObject();

			__this.loader.show();
			if(data.q == "reset"){
				__this.__reset();
				return false;
			}
			else {
				$.post("/filter.php", $(this).serialize() + "&action=filter&noCache= " + Math.floor(Math.random() * 99999), function(data){
					__this.parseJson(data);
					__this.loader.hide();
				}, "json");
				return false;
			}
		});

	// Trigger submit if there is a default search value parsed
	if($("#q").val() !== ""){
		$(__this.form).trigger("submit");
	}
		
	$("select, :checkbox, :radio", __this.form).each(function(){
		$(this).bind("change", function(){
			$(__this.form).trigger("submit");
		});
	});

	var minIq = parseInt($("#min_iq").val());
	var maxIq = parseInt($("#max_iq").val());
	
	$("#min_iq").bind("blur", function () {
		if (parseInt($(this).val()) >= minIq) {
			if ($(this).next().is("span")) {
				$(this).next().remove();
				$(this).removeAttr("style");
			}
			if (parseInt($("#max_iq").val()) > parseInt($(this).val())) {
				$(__this.form).trigger("submit");
			}		
		} else {
			$(this).css({
				border: "1px red solid"
			}).after("<span style=\"color: red\">Minimaal " + minIq + "</span>");
		}
	});
	
	$("#max_iq").bind("keyup", function () {
		if (parseInt($(this).val()) <= maxIq) {
			if ($(this).next().is("span")) {
				$(this).next().remove();
				$(this).removeAttr("style");
			}
			if (parseInt($("#min_iq").val()) < parseInt($(this).val())) {
				$(__this.form).trigger("submit");
			}		
		} else {
			$(this).css({
				border: "1px red solid"
			}).after("<span style=\"color: red\">Maximaal " + maxIq + "</span>");
		}
	});
}

Filter.prototype.parseJson = function(data){
	var __this		= this;
		
	$("#results").children().remove();
	
	var blnNoResults	= (data === null),
		strTitle		= (blnNoResults) ? __this.msg.noResults : __this.msg.resultTitle,
		intCount		= (blnNoResults) ? "" : data.length;
	
	if(data !== null){
			
		$.each(data, function(){
			var $objItem = window.tpl.clone();

			$("*:not(h3):not(a):not(img)", $objItem).remove();
			$("img", $objItem)
				.attr("width", 60)
				.attr("height", 60)
				.attr("src", this.image);
				
			$("h3 a", $objItem)
				.text(this.name)
				.attr("href", this.link)
				.attr("target", "_blank");
			
			$objItem.append("<p>" + this.summary + "&hellip; <a href=\"" + this.link + "\" rel=\"external\">Lees meer &raquo;</a></p>");
			
			$objItem.appendTo($("#results"));
		});
		
	}
	__this.addTitleBar(intCount, strTitle);
}

Filter.prototype.addTitleBar = function (intCount, strTitle) {
	var __this = this;
	var strTitle = strTitle || __this.msg.resultTitle;
	var intCount = intCount || "";
	var $objTitle = $("<li><h2>" + strTitle + intCount + "</h2></li>");
	
	if ($("#results li:first").find("h2").length > 0) {
		$("#results li:first").find("h2").text(strTitle + intCount);
	} else {
		$objTitle.prependTo($("#results"));		
	}
}

Filter.prototype.resetForm = function(){
	this.form[0].reset();
	this.form.trigger("submit");
}

/**
 * Reset function debugging only.
 */
Filter.prototype.__reset = function(){
	$.post("/ajax", {reset: true}, function(data){
		// console.log(data);
	}, "json");
}
