var LMP = {
	
};

LMP.searchConfig =  {        
	ajax : {
		url			: '/php/server.php',
		type		: 'get',
		success		: function(xml) {LMP.search.processServerResponse(xml)},
		error		: function(XMLHttpRequest, textStatus, errorThrown) {LMP.search.handleAjaxError(XMLHttpRequest, textStatus, errorThrown)} 
	},	
	debug: true
};

LMP.searchfield = {
	defaultText: "Zoek op trefwoord/isbn/uitgever",
	defaultStyle: "color:#a09f9f;font-style:italic;width:200px",
	
	init: function() {
		$("#search").attr('value', this.defaultText);
		$("#search").attr('style', this.defaultStyle);
		$("#titlechecker").hide();
	},
	
	doBlur: function() {
		var currentValue = $("#search").attr('value');
		if(currentValue=='') {
			this.init();
		}
	},
	
	doFocus: function() {
		var currentValue = $("#search").attr('value');
		if(currentValue==this.defaultText) {
			$("#search").attr('value', '');
			$("#search").attr('style', '');
			$("#titlechecker").show();
		}
	}
};

LMP.edurep = {
	sortType: "date",
	sortOrder: "asc",
	totalResults: 0,
	total: 0,
	active: 0,
	pages: 0,
	requestedStartRecord: 0,
	requestedMaximum: 0,
	nextStartRecord: 0,
	previousStartRecord: 0,
	tab_defaultText: ' resultaten Edurep',
	level: '(loaded by ajax)',
	repositories: '(loaded by ajax)',
	query: '(not built yet)',
	
	tabCounter: function () {
		var pAmount = LMP.search.addSeparatorsNF(this.totalResults, '.', ',', '.');
		$("#edurep_span").html(pAmount + this.tab_defaultText);
	},
	
	paginatorGo: function() {
		
		var vorige = '';
		var volgende = '';		 
		
		this.total = Math.ceil ( this.totalResults / this.requestedMaximum );
		this.active = Math.floor ( this.requestedStartRecord / this.requestedMaximum) + 1;
		this.previousStartRecord = this.requestedStartRecord - this.requestedMaximum; 
		
		if(this.active == 1) {
			/* disable 'vorige' */	
			vorige = 'Vorige';
		} else {
			vorige = '<a href="#" data="{type:\'edu_sr\',startRecord:\''+(this.previousStartRecord)+'\',edurepUpdate:\'true\',preventDefault:\'true\'}" class="">Vorige</a>';
		}
		if(this.active == this.total) {
			/* disable 'volgende'*/
			volgende = 'Volgende';
		} else {
			volgende = '<a href="#" data="{type:\'edu_sr\',startRecord:\''+(this.nextStartRecord)+'\',edurepUpdate:\'true\',preventDefault:\'true\'}" class="">Volgende</a>';
		}
		
		var output = vorige + ' | ' + this.active + '/' + this.total + ' | ' + volgende;
		
		$("#edurep_paginator").html(output);
		$("#edurep_paginator").find('a').unbind("click");
		$("#edurep_paginator").find('a').bind("click",LMP.search.processGuiEvent);
	
		$("#edurep_paginator_bot").html(output);
		$("#edurep_paginator_bot").find('a').unbind("click");
		$("#edurep_paginator_bot").find('a').bind("click",LMP.search.processGuiEvent);
		
	}

};

LMP.search = {		
	aInterfaceItems: new Array,
	prim_active: false,
	oInterfaceState: {},
	bLoaded: false,
	processEvents : true,
	sortType: "rijkheid",
	sortOrder: "desc",
	edu_sortType : "",
	edu_sortOrder: 0,
	numberOfResults: "10",
	pageStart: 1,
	activeTab: 0,
	friendlyBreadcrumb: "", 
	totalResults: 0,
	kclResults: 0,
	edurepResults: 0,
	trefwoord: "",
	animationSpeed: 0,
	defaultStatusText: "Selecteer hierboven eerst &#233;&#233;n of meer kenmerken.",
	tab_defaultText: ' resultaten SLO',
	compareListItems: new Array, 
	edurepAjaxInst: new XMLHttpRequest(),
	edu_startRecord: 1,
	tab: 0,
	
	init: function(){
		this.config = LMP.searchConfig;
		$.ajaxSetup(this.config.ajax);
		this.trace ('init');
		this.doCustomBindings();			
		this.loadInterface();
		this.doTabs();
		$('#waitMessage').css('left',300);
		$('#waitMessage').css('top',300);
		$().mousemove(function(e){
			$('#waitMessage').css('left',e.pageX+10);
			$('#waitMessage').css('top',e.pageY+10);
 				});
		$('#'+this.sortType).addClass('active');
		if(LMP.search.sortOrder == 'desc') {
			$('#'+this.sortType).append('<img class="lockicon" src="/wp-content/themes/leermiddelenplein/images/icons/ico_down.gif" />');
		} else {
			$('#'+this.sortType).append('<img class="lockicon" src="/wp-content/themes/leermiddelenplein/images/icons/ico_up.gif" />');
		}
		
		$('#nor'+this.numberOfResults).addClass('active');
	},
	
	addSeparatorsNF: function (nStr, inD, outD, sep) {
		nStr += '';
		var dpos = nStr.indexOf(inD);
		var nStrEnd = '';
		if (dpos != -1) {
			nStrEnd = outD + nStr.substring(dpos + 1, nStr.length);
			nStr = nStr.substring(0, dpos);
		}
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(nStr)) {
			nStr = nStr.replace(rgx, '$1' + sep + '$2');
		}
		return nStr + nStrEnd;
	},
          
	processGuiEvent : function (oE){
	
		var oJSON = {};
		LMP.search.trace('guiEvent: '+oE.type);
		if(!LMP.search.processEvents){ // Cancel the event if a data call is in progress
			return false;
		}
		/* Test if the data attribute is an object */
		if(typeof eval('('+$(this).attr('data')+')') =='object'){
			oJSON = eval('('+$(this).attr('data')+')');
			LMP.search.trace(oJSON);
			
			switch(oJSON.type){
			
			case "searchcheck":
			
				var currentValue = $("#search").attr('value');
				if($("#search_checked").attr('checked')) {
					if((currentValue == '') || (currentValue==LMP.searchfield.defaultText)) {
						oJSON.triggersUpdate = false;
						$("#search_checked").attr('checked', false);
					} 
				} else {
					LMP.searchfield.init();
				}				
			break;
			
			case "sort":
				if(LMP.search.sortType == oJSON.sortType){ /* Sort type is the same so let's reverse the sortOrder */
					LMP.search.sortOrder = (LMP.search.sortOrder == 'asc') ? LMP.search.sortOrder = 'desc' : LMP.search.sortOrder ='asc';
				}
				LMP.search.sortType = oJSON.sortType;
				$('#sort_by').find('a').removeClass('active');
				$('#sort_by').find('a').find('img').remove();
				
				$(this).addClass('active');
				if(LMP.search.sortOrder == 'desc') {
					$(this).append('<img class="lockicon" src="/wp-content/themes/leermiddelenplein/images/icons/ico_down.gif" />');
				} else {
					$(this).append('<img class="lockicon" src="/wp-content/themes/leermiddelenplein/images/icons/ico_up.gif" />');
				}
			break;
			
			case "edu_sort":
				if(LMP.search.edu_sortType == oJSON.sortType){ /* Sort type is the same so let's reverse the sortOrder */
					LMP.search.edu_sortOrder = (LMP.search.edu_sortOrder == '0') ? LMP.search.edu_sortOrder = '1' : LMP.search.edu_sortOrder ='0';
				}
				LMP.search.edu_sortType = oJSON.sortType;
				
				$('#edurep_sort_by').find('a').removeClass('active');
				$('#edurep_sort_by').find('a').find('img').remove();
				
				$(this).addClass('active');
				if($(this).text()=='alfabet') {
					if(LMP.search.edu_sortOrder == '1') {
						$(this).append('<img class="lockicon" src="/wp-content/themes/leermiddelenplein/images/icons/ico_down.gif" />');
					} else {
						$(this).append('<img class="lockicon" src="/wp-content/themes/leermiddelenplein/images/icons/ico_up.gif" />');
					}					
				}
			break;			
			
			case "nor":
				LMP.search.numberOfResults = oJSON.nor;
				$('#shownumber').find('a').removeClass('active');
				$(this).addClass('active');
				LMP.search.pageStart = 1; // Always reset the paginator to 1 on a nor change
			break;
			
			case "pn":
				LMP.search.pageStart = oJSON.pageStart;					
			break;
			
			case "edu_sr":
				LMP.search.edu_startRecord = oJSON.startRecord;
			break;
			
			
			case "bc":
				oE.preventDefault();
				var oSingleBreadcrumb = $(this).parents(".bc_listitem"); 
				oSingleBreadcrumb.fadeOut("fast"); // Direct hide of the breadcrumb item.
				
				if(oJSON.id == 'search' ) {
					$("#search").attr("value",""); // Reset the searchbox
					LMP.searchfield.init();
					LMP.search.server.load(LMP.search.getInterfaceState()); // Search box contents changed - do a servercall.
					//$("#search_checked").attr('checked', false);
				}else{
					var refElement = $('#'+oJSON.id).find("[value="+oJSON.value+"]");
					if(refElement.length > 0){
						refElement.removeAttr('checked');
						/* retrieve the data object from the referenced element: */
						if(typeof eval('('+refElement.attr('data')+')') =='object'){
							oElementData = eval('('+refElement.attr('data')+')');
							/* Check if we should do a server call: */
							if(oElementData.triggersUpdate == 'true'){
								LMP.search.server.load(LMP.search.getInterfaceState());
							}
						}
					}else{	// This is an orphaned breadcrumb element - do a server call to update the state
						LMP.search.server.load(LMP.search.getInterfaceState());
					}
				}
					
			break;
							
			}
			
			
			if(oJSON.preventDefault){
				oE.preventDefault();
			}
			
			if(oJSON.triggersUpdate){
				this.edu_startRecord = 1;
				var oCurrentState = LMP.search.getInterfaceState();
				LMP.search.trace('triggersupdate found');
				if(oJSON.ignoreEdurep) {
					oCurrentState.ec = 'ignoreEdurep';
				} else {
					LMP.search.edu_startRecord = 1;
				}
				
				
				var nameArr = explode('_', $(this).attr('id'));
				var filtername = trim(nameArr[0]);
				var filtervalue = trim($(this).parent().text());
				var filter = filtername + " " + filtervalue;
				
				LMP.search.trace(filter);
				
				pageTracker._trackEvent('Zoekfilter', 'Click', filter);
				
				LMP.search.server.load(oCurrentState);
			}
			
			if(oJSON.edurepUpdate){
				var oCurrentState = LMP.search.getInterfaceState();
				LMP.search.trace('edurepUpdate found');
				oCurrentState.c = 'edurep';
				oCurrentState.edu_sortType = LMP.search.edu_sortType;
				oCurrentState.edu_sortOrder = LMP.search.edu_sortOrder;				
				LMP.search.edurep_server.load(oCurrentState);
			}			
			
		}
		
		
		if(oE.type =='click' && oE.target.id == 'startAgain'){ //does a complete interface reset
			LMP.search.reset();
		}
		
		if(oE.type =='click' && oE.target.id == 'opslaan'){ //Handle bookmark click
			LMP.search.doBookmark();
		}
	},
	
	reset: function(){
		LMP.search.aInterfaceItems =  new Array,
		LMP.search.oInterfaceState = {},
		LMP.search.pageStart = 1;
		LMP.search.tab = 0;
		LMP.search.edu_startRecord = 1;
     	LMP.search.bLoaded = false,	
		LMP.search.server.load({c:'initial'});
		$('#search').attr('value','');
		LMP.searchfield.init();
		LMP.search.outSecondary();
		LMP.search._registerInterfaceItem('trefwoord'); // Needs (re)registering as it will not be done by the server.
	},
	
	doCustomBindings: function(){ // Binds interface elements from the loaded template.
		$("#startAgain").bind("click",LMP.search.processGuiEvent);
		$("#sortresults").find("a").bind("click",LMP.search.processGuiEvent);
		$("#edurep_sortresults").find("a").bind("click",LMP.search.processGuiEvent);
		$("#search_checked").bind("click", LMP.search.processGuiEvent);
		$("#btn_search").bind("click",LMP.search.processGuiEvent);
		LMP.search._registerInterfaceItem('trefwoord');
		$("#search").keypress (function(e){ // Binds the Enter key to trigger the button click
		 		if(e.which == 13){
					$('#btn_search').trigger('click');
				}
			}									
		);
		
		$("#opslaan").bind("click",LMP.search.processGuiEvent);
		LMP.search.verfijnButtons();
	},
	
	verfijnButtons: function() {
		$("#primary_filters").find(".filtersection").each(function() {
			$(this).bind("mouseover", LMP.search.showVerfijnBtn);
			$(this).bind("mouseout", LMP.search.hideVerfijnBtn);
		});		
		
		$("#primary_filters").find(".verfijnen").each(function() {
			$(this).bind("click", LMP.search.goSecondary);
		});		
	},
	
	showVerfijnBtn: function() {
		var current = LMP.search.checkWho(this);
		var isHidden = $("#verfijn_" + current).is(':hidden');
		
		if(isHidden) {
			$("#verfijn_" + current).show();
		}
	},		
	
	hideAllBtns: function() {
		$("#verfijn_doelgroepen").hide();
		$("#verfijn_vakken").hide();
		$("#verfijn_eigenschappen").hide();
		$("#verfijn_onderdeloep").hide();	
	},	
	
	hideVerfijnBtn: function() {
		LMP.search.hideAllBtns();
		
		if($("#collapsed").is(':hidden')) {
			var tabi = $("#tab_container > ul").tabs('option','selected');
			
			switch(tabi) {
				case 0:
					$("#verfijn_doelgroepen").show();
				break;
				case 1:
					$("#verfijn_vakken").show();
				break
				case 2:
					$("#verfijn_eigenschappen").show();
				break;
				case 3:
					$("#verfijn_onderdeloep").show();
				break;
			}
			
		}
		
	},
	
	switchVerfijnBtn: function() {
	
		LMP.search.hideAllBtns();
		
		var tabi = $("#tab_container > ul").tabs('option','selected');
				
		switch(tabi) {
			case 0:
				$("#verfijn_doelgroepen").show();
			break;
			case 1:
				$("#verfijn_vakken").show();
			break
			case 2:
				$("#verfijn_eigenschappen").show();
			break;
			case 3:
				$("#verfijn_onderdeloep").show();
			break;
		}
		
	},	

	checkWho: function( pElement ) {
		var current = "undefined";
		
		if($(pElement).hasClass("doelgroepen")) {
			current = "doelgroepen";
		}
		if($(pElement).hasClass("vakken")) {
			current = "vakken";
		}
		if($(pElement).hasClass("eigenschappen")) {
			current = "eigenschappen";
		}
		if($(pElement).hasClass("onderdeloep")) {
			current = "onderdeloep";
		}
		
		return current;
	},
	
	goSecondary: function() {
		LMP.search.hideVerfijnBtn();
		
		$("#collapsed").hide(LMP.search.animationSpeed);
		$("#expanded").show(LMP.search.animationSpeed);		
			
		var current = LMP.search.checkWho(this);
		var tabNumber = 0;
		switch(current) {
			case 'doelgroepen':
				tabNumber = 0;
				break;
			case 'vakken':
				tabNumber = 1;
				break;
			case 'eigenschappen':
				tabNumber = 2;
				break;
			case 'onderdeloep':
				tabNumber = 3;
				break;
			default:
				tabNumber = 0;
				break;
		}
		
		LMP.search.activeTab = tabNumber;
		$("#tab_container > ul").tabs('select',LMP.search.activeTab);

	},
	
	outSecondary: function() {
		$("#collapsed").show(LMP.search.animationSpeed);
		$("#expanded").hide(LMP.search.animationSpeed);
		LMP.search.hideAllBtns();
	},

	doExternalClick: function(oE){
		/* prevent the default click on an HREF */
		oE.preventDefault();
		
		switch(oE.data){
			case "detail":
			case "detailtab":
			case "readmore":
			case "compare":
				var sHref = $(this).attr('href');
				var sHash = document.location.hash.substring(1) + "&tab=" + $("#tab_area > ul").tabs('option', 'selected');
				document.location.hash = sHash;
				var jsonBookmark = LMP.search.bookmarkToJson(); 
				if (LMP.search.trefwoord != '') { 
					jsonBookmark.search = escape(LMP.search.trefwoord);
				}
				
				var sVars = "&" + $.param(jsonBookmark).replace('+',' ');
				sVars += "&bc=" + escape(LMP.search.friendlyBreadcrumb);
				var total = parseInt(LMP.search.totalResults) + parseInt(LMP.edurep.totalResults);
				sVars += "&tr=" + escape(total);				
					
				document.location.href = sHref+sVars;
			break;
		}	
	},
	
	primaryActive: function() {
		if(this.prim_active) {
			var total = this.addSeparatorsNF(parseInt(LMP.search.totalResults) + parseInt(LMP.edurep.totalResults), '.', ',', '.');
			$("#status_text").html('<p class="inline">Er zijn </p><p class="pink">' + total + ' </p><p class="inline"> resultaten. <a class="statuslink" href="#" onclick="LMP.search.goSecondary();">Klik hier om de resultaten te verfijnen.</a></p>');
		}
		
	},
	
	moveElement: function (from,to){
		var container = document.getElementById(from);
		var targetContainer =  $('#'+to);
		var calcWidth = container.offsetWidth;
		if(!$.browser.msie){
			var root = $('#'+from);
			var children = root.find('ol');
			calcWidth = calcWidth+(children.length*45/2);
		} else {
			
			var root = $('#'+from);
			var children = root.find('ol');
			calcWidth = calcWidth+(children.length*45/2);	

		}
		targetContainer.html('');
		targetContainer.css("width",calcWidth+22+"px");		
		if ($(container).html() == '') {
			targetContainer.html("<p>Het is niet mogelijk om met de huidige zoekcriteria verder te verfijnen.</p>");
		} else {
			$(container).find('ol').appendTo(targetContainer);
		}
	},
	
	appendElementsTo: function (source1, source2, to) {
		var container1 = document.getElementById(source1);
		var container2 = document.getElementById(source2);
		
		var targetContainer =  $('#'+to);
		
		var calcWidth = container1.offsetWidth + container2.offsetWidth;
		
		targetContainer.html('');
		targetContainer.css("width","100%");				
		$(container1).find('.content').appendTo(targetContainer);
		$(container2).find('.content').appendTo(targetContainer);					
		
	},
	
	doTabs: function(){
		$("#tab_container > ul").tabs();
		$("#tab_container > ul").show();
		if(typeof LMP.search.activeTab !='undefined'){
			$("#tab_container > ul").tabs('select',LMP.search.activeTab);	
		}
		
		$("#tab_container > ul").bind('tabsshow', function(event, ui) {
		
		    // Objects available in the function context:
		    //ui.tab     // anchor element of the selected (clicked) tab
		    //ui.panel   // element, that contains the selected/clicked tab contents
		    //ui.index   // zero-based index of the selected (clicked) tab
		   LMP.search.switchVerfijnBtn();
		
		});			
		
		$("#tab_area > ul").tabs();
		$("#tab_area > ul").show();
		if(typeof LMP.search.tab !='undefined'){
			$("#tab_area > ul").tabs('select',parseInt(LMP.search.tab));
		}		
			
		$('.tab_info').cluetip({splitTitle: '|'});	
		
	},
		
	doBookmark: function(){
		var currentURL = document.location.href + "&tab=" + $("#tab_area > ul").tabs('option', 'selected');;
		var friendlyName = "SLO Lmp - zoekres. voor "+ this.friendlyBreadcrumb.replace(/,/g," - ");

		if (window.sidebar) { // Mozilla Firefox Bookmark
			window.sidebar.addPanel(friendlyName, currentURL,"");
		} else if( window.external ) { // IE Favorite
			window.external.AddFavorite( currentURL, friendlyName); 
		} else if(window.opera && window.print) { // Opera Hotlist
			return true; 
		};
	},

	paginator: {
			total: 0,
			active: 0,
			from: 0,
			to: 0,
			max: 5,
			range: 2,
			elLinks: null, 
			elContainer: null,
			
			go: function(){
				var vorige = '';
				var volgende = '';
				if(this.active == 1) {
					/* disable 'vorige' */	
					vorige = 'Vorige';
				} else {
					vorige = '<a href="#" data="{type:\'pn\',pageStart:\''+(this.active-1)+'\',triggersUpdate:\'true\', ignoreEdurep:\'true\',preventDefault:\'true\'}" class="">Vorige</a>';
				}
				if(this.active == this.total) {
					/* disable 'volgende'*/
					volgende = 'Volgende';
				} else {
					volgende = '<a href="#" data="{type:\'pn\',pageStart:\''+(this.active+1)+'\',triggersUpdate:\'true\', ignoreEdurep:\'true\',preventDefault:\'true\'}" class="">Volgende</a>';
				}
				
				var output = vorige + ' | ' + this.active + '/' + this.total + ' | ' + volgende;
				
				$("#new_paginator").html(output);
				$("#new_paginator").find('a').unbind("click");
				$("#new_paginator").find('a').bind("click",LMP.search.processGuiEvent);
				
				$("#new_paginator_bot").html(output);
				$("#new_paginator_bot").find('a').unbind("click");
				$("#new_paginator_bot").find('a').bind("click",LMP.search.processGuiEvent);
				
			},
			
			calculateRange: function(){
				this.from = this.active - this.range;
				this.to = this.active + this.range;
				
				if(this.from < 1){
					this.from = 1;
					this.to = this.max;
				}
				
				if(this.to > this.total){
					this.from = (this.total-this.max+1 >=1) ? this.total-this.max+1 : 1;
					this.to = this.total;
				}				  
			},
			
			createElements: function(){
				if(this.active !=1){							
					elNavigator = document.createElement('A');
					elNavigator.setAttribute("href","#");
					elNavigator.setAttribute("data","{type:'pn',pageStart:'1',triggersUpdate:'true',preventDefault:'true'}");
					elNavigator.setAttribute("title","Ga naar eerste pagina");
					elNavigator.innerHTML = '&laquo;&nbsp;';
					this.elLinks.append(elNavigator);
					elNavigator.innerHTML = '';
					elNavigator = document.createElement('A');
					elNavigator.setAttribute("href","#");
					elNavigator.setAttribute("data","{type:'pn',pageStart:'"+(this.active-1)+"',triggersUpdate:'true',preventDefault:'true'}");
					elNavigator.setAttribute("title","Ga 1 pagina terug");
					elNavigator.innerHTML = '&lsaquo;&nbsp;&nbsp;';
					this.elLinks.append(elNavigator);
					elNavigator.innerHTML = '';
					
				}
					
				for(var i=this.from;i <= this.to;i++){
					elLink = document.createElement('A');
					elLink.setAttribute("href","#");
					elLink.setAttribute("data","{type:'pn',pageStart:'"+i+"',triggersUpdate:'true',preventDefault:'true'}");
					
					if(i==this.active){
						elLink.className = "active";
					}else{
						elLink.className = "";
					}
					if(i == this.to || i == this.total){
						elLink.innerHTML = " "+i;
					}else{
						elLink.innerHTML = " "+i+" |";
					}
					this.elLinks.append(elLink);							
				}
				
				if(this.active !=this.total){
					elNavigator = document.createElement('A');
					elNavigator.setAttribute("href","#");
					elNavigator.setAttribute("data","{type:'pn',pageStart:'"+(this.active+1)+"',triggersUpdate:'true',preventDefault:'true'}");
					elNavigator.setAttribute("title","Ga 1 pagina verder");
					elNavigator.innerHTML = '&nbsp;&nbsp;&rsaquo;';
					this.elLinks.append(elNavigator);
					elNavigator.innerHTML = '';								
					elNavigator = document.createElement('A');
					elNavigator.setAttribute("href","#");
					elNavigator.setAttribute("data","{type:'pn',pageStart:'"+this.total+"',triggersUpdate:'true',preventDefault:'true'}");
					elNavigator.setAttribute("title","Ga naar laatste pagina");
					elNavigator.innerHTML = '&nbsp;&raquo;';
					this.elLinks.append(elNavigator);
					elNavigator.innerHTML = '';
				}

			},
			
			bind: function(){
					this.elLinks.find('a').unbind("click");
					this.elLinks.find('a').bind("click",LMP.search.processGuiEvent);
			}

	},
	
	_bindBreadcrumb : function(){ // Called from server response. Binds the breadcrumb delete buttons 
		var oBreadcrumbItems = $("#bc_list").find("span").filter("[class=delete]");
		$(oBreadcrumbItems).unbind("click");
		$(oBreadcrumbItems).bind("click",LMP.search.processGuiEvent);
		LMP.search.trace("Found "+oBreadcrumbItems.length+" breadcrumb items to bind");
	},
          
	server: {
		load: function (data) {
			LMP.search.ajStop(); 
			LMP.search.trace(data);
			LMP.search.wait(true);
			$("#kcl_span").html('...SLO gegevens worden opgehaald...');
			$("#tab_area > ul").tabs("disable",0);
			$.ajax({data: data}) 
		}
	},
	
	edurep_server: {
		load: function (data) {
			LMP.search.trace(data);
			LMP.search.wait(false);
			$("#edurep_results").html('');
			$("#edurep_paginator").html('');
			$("#edurep_span").html('...Edurep gegevens worden opgehaald...');
			$("#edu_loading").show();
			$("#tab_area > ul").tabs("disable",1);
			LMP.search.edurepAjaxInst = $.ajax({data: data})
		}
	},
	
	ajStop: function () {
		LMP.search.edurepAjaxInst.abort();
	},
	
	goEdurep: function () {
		dataJSON = {};
		dataJSON.c = 'edurep';
		dataJSON.edu_startRecord = this.edu_startRecord;
		dataJSON.edu_sortType = this.edu_sortType;
		dataJSON.edu_sortOrder = this.edu_sortOrder;
		this.edurep_server.load(dataJSON);
	},
          
	wait: function(wait){
		if(wait){
			$("#waitMessage").show();
			this.processEvents = false;
		}else{
			$("#waitMessage").hide();
			this.processEvents = true;
		}
	},
	
	processServerResponse : function (xml){    
		LMP.search.trace('ProcessServerResponse');
		LMP.search.trace("Raw response:");
		if(typeof console =='object' && LMP.searchConfig.debug == true){
			if(typeof console.dirxml == 'function'){
				console.dirxml( xml);
			}
		}
		try {
			eval($(xml).find("execute").text());
		}
		catch(err){ LMP.search.processError(err,'js-execute'); }
		
		LMP.search.processData($(xml).find("data"));
				
		try{
			eval($(xml).find("execute-after").text());
		}
		catch(err){ 
			LMP.search.processError(err,'js-execute-after');
		}
		LMP.search.wait(false);
		LMP.search.processAfter();
		LMP.search._setBookmark(LMP.search.getInterfaceState());
	},
          
          
	processData: function (xml){
		/* Parse data blocks and insert them in the subsequent ID's */
		$("content",xml).each (function(i){
			if(document.getElementById($(this).attr("for"))){
				switch ($(this).attr("mode")){
					case 'append':
						$('#'+$(this).attr("for")).append ($(this).text());
					break;				
					case 'replace':
						$('#'+$(this).attr("for")).html ($(this).text());
					break;
					default:
						$('#'+$(this).attr("for")).html ($(this).text());
					break;
				}
			}else{
				LMP.search.processError("Server trying to write to DIV that does not exist: ", 'div: '+$(this).attr("for") + " could not be found in the DOM");
			}
		});
	},
	
	processAfter: function(){ /* Can be used to perform processing after a server call.*/
		LMP.search.trace("processAfter");
		$(".options").find("[class=delete]").parent().hide();
		LMP.search.buildComparison();
		
	},

	loadInterface: function(){	
		if(!this.bLoaded){
			oCurrentBookmark = this.bookmarkToJson();
			oCurrentBookmark.c = 'initial';
			this.sortType = oCurrentBookmark.sortType || this.sortType;
			this.sortOrder = oCurrentBookmark.sortOrder || this.sortOrder;
			this.numberOfResults = oCurrentBookmark.numberOfResults || this.numberOfResults;
			this.pageStart = oCurrentBookmark.pageStart || this.pageStart;
			this.tab = oCurrentBookmark.tab || this.tab;
			this.edu_startRecord = oCurrentBookmark.edu_startRecord || this.edu_startRecord;
			if(oCurrentBookmark.CID) {
				this.compareListItems = explode(',', oCurrentBookmark.CID);
			}
			oCurrentBookmark.sortType = this.sortType;
			oCurrentBookmark.sortOrder = this.sortOrder;
			oCurrentBookmark.numberOfResults = this.numberOfResults;
			LMP.search.server.load(oCurrentBookmark);
		}
	},
	
	_registerInterfaceItem: function(sID){	
		this.trace('Registering interface item with ID: '+sID);
		for(var i=0; i< this.aInterfaceItems.length; i++)
			if(LMP.search.aInterfaceItems[i] == sID){
				LMP.search.trace('interface item with id '+sID+' was already registered');
				return;
			}
		LMP.search.aInterfaceItems.push(sID);
	},
	
	updateCounter : function () {
		var sCounterValue = parseInt(LMP.search.totalResults) + parseInt(LMP.edurep.totalResults); 
		var pAmount = this.addSeparatorsNF(sCounterValue, '.', ',', '.');
		var elCounter = $("#bc_counter");
		if(sCounterValue == '' || sCounterValue=='0') {sCounterValue = "0"; elCounter.css('color','red');}else{elCounter.css('color','black');}
		elCounter.html(pAmount);	
	},
	
	tabCounter: function () {
		var pAmount = this.addSeparatorsNF(this.totalResults, '.', ',', '.')
		$("#kcl_span").html(pAmount + this.tab_defaultText);	
	},	
	
	
	addToCompare : function ( sCID, sCTitle ) {
	
		setCookie(sCID, sCTitle);
	
		var index = array_search(sCID, LMP.search.compareListItems);
		
		if(!index) {

			var comparisonlist = $("#comparelist");
			comparisonlist.parent().hide();

			var appendix = '<dt id="'+sCID+'"><span class="delete"></span><span class="title">'+sCTitle+'</span><span class="readmore"><a class="readmore" href="/php/detail.php?id='+sCID+'" title="Ga naar detailpagina">ga naar detailpagina <img src="/wp-content/themes/leermiddelenplein/images/new_interface/loep.png" /></a></span></dt>';
			comparisonlist.append(appendix);
							
			LMP.search.compareListItems.push(sCID);
			LMP.search.evaluateList();

			comparisonlist.find("a").filter("[class=readmore]").bind("click", "readmore" ,LMP.search.doExternalClick);
			comparisonlist.find("#"+sCID).find("span").filter("[class=delete]").bind("click", sCID ,LMP.search.deleteFromCompare);
		
			comparisonlist.parent().fadeIn(2000);
			
			LMP.search._setBookmark(LMP.search.getInterfaceState());
			
			var btn = $("#CID_addBtn_" + sCID);
			$(btn).attr("class", "remove");
			$(btn).html("weghalen vergelijking");
			
		} else {
			LMP.search.deleteFromCompare_byUnclick(sCID);
		}
		
	},
	
	deleteFromCompare : function ( sCID ) {
		var comparisonlist = $("#comparelist");
		comparisonlist.parent().hide();
		
		var index = array_search(sCID.data, LMP.search.compareListItems);

		LMP.search.compareListItems.splice(index, 1);
		LMP.search.evaluateList();
		
		var item = comparisonlist.find("#" + sCID.data);
		item.remove();
	
		comparisonlist.parent().fadeIn(2000);
		
		LMP.search._setBookmark(LMP.search.getInterfaceState());
		
		var btn = $("#CID_addBtn_" + sCID.data);
		$(btn).attr("class", "vergelijk");
		$(btn).html("voeg toe aan vergelijking");
	},
	
	deleteFromCompare_byUnclick : function ( sCID ) {
		var comparisonlist = $("#comparelist");
		comparisonlist.parent().hide();
		
		var index = array_search(sCID, LMP.search.compareListItems);

		LMP.search.compareListItems.splice(index, 1);
		LMP.search.evaluateList();
		
		var item = comparisonlist.find("#" + sCID);
		item.remove();
	
		comparisonlist.parent().fadeIn(2000);
		
		LMP.search._setBookmark(LMP.search.getInterfaceState());
		
		var btn = $("#CID_addBtn_" + sCID);
		$(btn).attr("class", "vergelijk");
		$(btn).html("voeg toe aan vergelijking");
	},			
	
	evaluateList : function () {
		var commentLine = $("#compare_comment");
		var compareBtn	= $(".btn_compare");
		if (LMP.search.compareListItems.length > 1) {
			commentLine.hide();
			compareBtn.show();
		} else {
			commentLine.show();
			compareBtn.hide();
		}			
	},
	
	buildComparison : function () {
	
		var comparisonlist = $("#comparelist");
		comparisonlist.html('');
		for(i=0; i<this.compareListItems.length; i++) {
			var sCID = this.compareListItems[i];
			var sCTitle = getCookie(sCID);
			if (sCTitle != "") {
				var appendix = '<dt id="'+sCID+'"><span class="delete"></span><span class="title">'+sCTitle+'</span><span class="readmore"><a class="readmore" href="/php/detail.php?id='+sCID+'" title="Ga naar detailpagina">ga naar detailpagina <img src="/wp-content/themes/leermiddelenplein/images/new_interface/loep.png" /></a></span></dt>';
				comparisonlist.append(appendix);
								
				comparisonlist.find("a").filter("[class=readmore]").bind("click", "readmore" ,LMP.search.doExternalClick);
				comparisonlist.find("#"+sCID).find("span").filter("[class=delete]").bind("click", sCID ,LMP.search.deleteFromCompare);
				
				var btn = $("#CID_addBtn_" + sCID);
				$(btn).attr("class", "remove");
				$(btn).html("weghalen vergelijking");						
			} else {
				this.compareListItems = new Array;					
			}
		}
					
		LMP.search._setBookmark(this.getInterfaceState());
		LMP.search.evaluateList();	
		
	},
	
	
	getInterfaceState: function(){
		this.oInterfaceState = {};
		for(var i=0;i< LMP.search.aInterfaceItems.length;i++) {
			/* Loop through registered interface items en find the checked/selected or text states of input elements */
			var sID = LMP.search.aInterfaceItems[i];
			if($('#'+sID)){
				/* test for CHECKBOXES */
				var oCheckboxes = $('#'+sID).find(':checkbox');
				var a = 0;
				var aCheckboxes =[];
				for(var c=0; c< oCheckboxes.length;c++){
					if(oCheckboxes[c].checked){					
						aCheckboxes[a] = $(oCheckboxes[c]).attr('value');
						a++;
					}
				}
				if(aCheckboxes.length > 0){
					this.oInterfaceState[sID] = aCheckboxes.join(",");
				}
				/* test for TEXT INPUTS */
				var oTextinputs = $('#'+sID).find(':text');					
				var a = 0;
				var aTextinputs =[];
				for(var t=0; t< oTextinputs.length;t++){
					if(($(oTextinputs[t]).attr('value') !='') && ($(oTextinputs[t]).attr('value') != LMP.searchfield.defaultText)) {
						this.oInterfaceState[$(oTextinputs[t]).attr('id')] = escape($(oTextinputs[t]).attr('value'));
					}
				}
			}
		}
		
		/* Add compareListItems if any */
		if (LMP.search.compareListItems.length>0) {
			this.oInterfaceState.CID = LMP.search.compareListItems.join(",");
		}
		
		/* Add sort and number of results to request */
		this.oInterfaceState.sortType = LMP.search.sortType;
		this.oInterfaceState.sortOrder = LMP.search.sortOrder;
		this.oInterfaceState.numberOfResults = LMP.search.numberOfResults;
		this.oInterfaceState.pageStart = LMP.search.pageStart;
		this.oInterfaceState.edu_startRecord = LMP.search.edu_startRecord;
		return this.oInterfaceState;			
	},

	_setBookmark: function (oBookmarkItems) {		
		/* Expects JSON object containing the interface state */
		this.trace('_setBookmark called');	
		
		var sRequest = $.param(oBookmarkItems);
		
		if(sRequest){
			document.location.hash = sRequest; 
		}else{
			document.location.hash = "#";	
		}
	},
	
	bookmarkToJson: function(){ 
		/* Called on a pageload. Determines the hash values and extracts the correct vars to load the initial state of the interface */
		if(document.location.hash){
			var sHash = document.location.hash.substring(1);
			var aItems = sHash.split('&');
			var oDataJSON = {};
			for(var i=0; i< aItems.length;i++) {
					aItem = aItems[i].split('=');
					sKey = aItem[0];

					if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
						sValue = aItem[1];
					} else {
						sValue = Url.decode(aItem[1]);
					}
										
					oDataJSON[sKey] = sValue;
					
			}
			return oDataJSON;						
		}else{
			this.trace('Initial state empty');
			return {};
		}
	},
	
	trace: function (trace){
		if(LMP.search.config.debug){
			if(typeof console =='object') {
				if(typeof trace =='string' || typeof console.dir !='function'){
					console.info("Trace: "+trace);
				}else{
					console.dir(trace);
				}
			}
		}
	
	},
	
	handleAjaxError : function (XMLHttpRequest, textStatus, errorThrown){
		this.processError('AJAX Error: '+ textStatus +" "+ errorThrown,'$.ajax');
		this.trace("XMLHTTP STATUS: " + XMLHttpRequest.status);
		this.trace("XMLHTTP Response: " + XMLHttpRequest.responseText);
		this.trace("Reported Error: " + textStatus+" "+errorThrown);
	},
	
	processError : function(err,type){
		LMP.search.wait(false);
		if(LMP.search.config.debug && typeof console =='object'){
			console.warn ("ERROR OCCURED ("+type+"):");
			if(typeof err == 'object'){
				console.dir(err);
			}else{
				console.warn("Message: "+ err + " in "+type);
			}
		}
	}
}