var fragment = "";

function monitorURI() { 
	var frag = window.location.hash; 
	if (frag.substr(0,1) == '#') { 
		if(fragment != frag.substr(1)) {
			$('page').set('value', frag.substr(1));
		}
	}
	fragment = frag.substr(1);
	setTimeout('monitorURI()', 300);
}

var originalPageTitle = '';


var search = function(){
	
	monitorURI();
	
//	// Get and set the page number
//	var currentAnchor = document.location.hash;
//	if(!currentAnchor){
//		var pageNum = 1;
//	} else {
//		var pageNum = currentAnchor.substring(1);
//	}
	
//	$('page').set('value', pageNum);
	
	
	// Create a fancy loading thingy
	var tmp = '<li class="th"><ul class="breadcrumbs"><li>De gegevens worden opgehaald... even geduld...</li></ul><div class="clear"></div></li>';
	tmp = tmp + '<li class="loading"><img src="/design/images/layout/ajax-loader.gif" alt="Laden..." /></li>';
	
	// Clear out the main UL
	$$('ul.table')[0].innerHTML = tmp;
	
	var keyword		= $('keyword').get('value');
	var regime		= $('regime').get('value');
	var category	= $('category').get('value');
	var page		= $('page').get('value');
	var province	= $('province').get('value');
	var city		= $('city').get('value');
	var dominant	= $('dominant').get('value');
	
	var request = new Request.JSON({
		url: '/vacatures/ajax/',
		onSuccess: handleResults,
		async: true
	}).post({
		'keyword': keyword,
		'regime': regime,
		'category': category,
		'page': page,
		'province': province,
		'city': city,
		'dominant': dominant
	});
	
}

var generateHeader = function(result, footer) {
	
	var li_prev_disabled = false;
	var li_next_disabled = false;
	
	// Calculate how many pages in total we have
	var pages = Math.ceil(result.count.total/result.count.perpage);
	var currpage = result.currpage;
	
	// How many records we have on this page
	var pageTotal = '';
	
		// Total amount of records smaller than allowed per page?
		if (result.count.total < result.count.perpage){
			pageTotal = result.count.total;
			
		// More records, so multiple pages
		} else {
			var assumed = currpage * result.count.perpage;
			if (assumed > result.count.total){
				assumed = result.count.total;
			}
			pageTotal = assumed;
		}
	
	
	// See if we have a previous button
	if ((currpage-1) == 0){
		li_prev_disabled = true;
	}
	
	// See if we have a next button
	if (currpage == pages){
		li_next_disabled = true;
	}
	
	// Build the table row
	var table = $$('div.content ul.table')[0];
	
	if(footer == true)
		var row = new Element('li').addClass('th lastth');
	else
		var row = new Element('li').addClass('th');
		
		var list = new Element('ul').addClass('breadcrumbs');
			var li_first = new Element('li', {'html': '<a href="/">Home</a> <span class="breadcrumb"><a name="zoekresultaten">&raquo;</a></span>'});
			if(result.keyword != ''){
				var li_second = new Element('li', {'html': '<span class="total"></span> zoekresultaten - <span class="page_total">'+pageTotal+'</span> van <span class="total">'+result.count.total+'</span>'}).addClass('results');
			} else {
				var li_second = new Element('li', {'html': '<span class="total"></span> zoekresultaten - <span class="page_total">'+pageTotal+'</span> van <span class="total">'+result.count.total+'</span>'}).addClass('results');
			}
			
		var pagination = new Element('ul').addClass('pagination');
			if(li_prev_disabled)
				var li_prev = new Element('li', {'html': '<a class="left disabled" href="javascript:void(0)" onclick="return false;">Vorige</a>'});
			else 
				var li_prev = new Element('li', {'html': '<a class="left" href="javascript:void(0)" onclick="prevPage()">Vorige</a>'});
				
			var li_info = new Element('li', {'html': currpage + ' van ' + pages});
			
			if(li_next_disabled)
				var li_next = new Element('li', {'html': '<a class="right disabled" href="javascript:void(0)" onclick="return false;">Volgende</a>'});
			else
				var li_next = new Element('li', {'html': '<a class="right" href="javascript:void(0)" onclick="nextPage()">Volgende</a>'});
	
			var clear = new Element('div', {'html': ''}).addClass('clear');
	
		var rss = new Element('ul').addClass('rss');
			
			var rssFeedUrl = document.location.href.replace('/vacatures', '/rss');
			var li_rss = new Element('li', {'html': '<a rel="nofollow" href="' + rssFeedUrl + '">RSS</a>'});
			
		var emailAlert = new Element('ul').addClass('emailAlert');
			var li_emailAlert = new Element('li', {'html': '<a href="#" onclick="showMailDialog();" rel="nofollow"><strong>Nieuwe jobs via e-mail?</strong></a>'});
	
	// Inject everything
	li_first.inject(list);
	li_second.inject(li_first, 'after');
	
	li_prev.inject(pagination);
	li_info.inject(li_prev, 'after');
	li_next.inject(li_info, 'after');
	
	list.inject(row);
	pagination.inject(list, 'after');
	
	li_rss.inject(rss);
	rss.inject(pagination, 'after');
	
	li_emailAlert.inject(emailAlert);
	emailAlert.inject(rss, 'after');
	
	if (footer != true)
		clear.inject(emailAlert, 'after');
	
	row.inject(table);
}




var generateRow = function(record) {
	
	// Build the table row
	var table = $$('div.content ul.table li.th.lastth')[0];
	
	if(record.isLast){
		var row = new Element('li').addClass('tr lasttr');
	} else {
		var row = new Element('li').addClass('tr');
	}
	
		var first = new Element('div').addClass('td-first');
			var cell_place = new Element('span', {'html': record.city_name}).addClass('place');
			var cell_date = new Element('span', {'html': record.date_readable}).addClass('date');
		
		var second = new Element('div').addClass('td-second');
			var cell_function = new Element('span', {'html': '<a href="/vacature/detail/'+record.id+'/'+record.quicklink+'/" title="'+htmlentities(record.title)+'">' + prepTitle(record.title) + '</a>'}).addClass('function');
			var cell_company = new Element('span', {'html': htmlentities(record.company)}).addClass('company');
		
		var last = new Element('div').addClass('td-last');
			var cell_regime = new Element('span', {'html': record.regime_name}).addClass(record.regime_name.toLowerCase());
	
	
	// Inject everything into eachother
	
		// First column
		cell_place.inject(first);
		cell_date.inject(cell_place, 'after');
		
		// Second column
		cell_function.inject(second);
		cell_company.inject(cell_function, 'after');
		
		// Last column
		cell_regime.inject(last);
		
			// Inject the columns into the row
			first.inject(row);
			second.inject(first, 'after');
			last.inject(second, 'after');
			
				// Inject the row into the table
				row.inject(table, 'before');

}

var generateFilterDate = function(data){
	
	// Variables for easy access
	var ul			= $('dateFilter');
	var last2		= data.count.date.last2;
	var last7		= data.count.date.last7;
	var last14		= data.count.date.last14;
	
	var li_last2 	= new Element('li', {'html': 'Laatste 48 uur <span>(0)</span>'});
	var li_last7 	= new Element('li', {'html': 'Laatste 7 dagen <span>(0)</span>'});
	var li_last14 	= new Element('li', {'html': 'Laatste 14 dagen <span>(0)</span>'});
	
	// Clear the UL
	ul.innerHTML = '';
	
	// Build list items
	if ($('date').get('value') != ''){
		var li_alles = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'date\', \'\')">Toon alles</a>'});
		li_alles.inject(ul);
	} else {
		var li_alles = new Element('li', {'html': '<strong><a href="javascript:void(0)" onclick="applyFilter(\'date\', \'\')">Toon alles</a></strong>'});
		li_alles.inject(ul);
	}
	
	
	if (last2 > 0){
		if($('date').get('value') != '2'){
			li_last2 = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'date\', 2)">Laatste 48 uur</a> <span>(' + last2 + ')</span>'});
		} else {
			li_last2 = new Element('li', {'html': '<strong><a href="javascript:void(0)" onclick="applyFilter(\'date\', 2)">Laatste 48 uur</a></strong> <span>(' + last2 + ')</span>'});
		}
		li_last2.inject(ul);
	}
		
	if (last7 > 0){
		if($('date').get('value') != '7'){
			li_last7 = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'date\', 7)">Laatste 7 dagen</a> <span>(' + last7 + ')</span>'});
		} else {
			li_last7 = new Element('li', {'html': '<strong><a href="javascript:void(0)" onclick="applyFilter(\'date\', 7)">Laatste 7 dagen</a></strong> <span>(' + last7 + ')</span>'});
		}
		li_last7.inject(ul);
	}
		
	if (last14 > 0){
		if($('date').get('value') != '14'){
			li_last14 = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'date\', 14)">Laatste 14 dagen</a> <span>(' + last14 + ')</span>'});
		} else {
			li_last14 = new Element('li', {'html': '<strong><a href="javascript:void(0)" onclick="applyFilter(\'date\', 14)">Laatste 14 dagen</a></strong> <span>(' + last14 + ')</span>'});
		}
		li_last14.inject(ul);
	}
	
	
}


var generateFilterRegime = function(data){
	
	// Variables for easy access
	var ul			= $('regimeFilter');
	var deeltijds	= data.count.regimes.deeltijds.count;
	var voltijds	= data.count.regimes.voltijds.count;
	var freelance	= data.count.regimes.freelance.count;
	
	var filtertype	= $('filtertype').get('value');
	
	var li_deeltijds = new Element('li', {'html': 'Deeltijds <span>(0)</span>'});
	var li_voltijds = new Element('li', {'html': 'Voltijds <span>(0)</span>'});
	var li_freelance = new Element('li', {'html': 'Freelance <span>(0)</span>'});
	
	// Clear the UL
	ul.innerHTML = '';
	
	
	// Build list items
//	var origin = window.location.href.split('?')[1].split('=')[0];
//	if(origin != 'category' && origin != 'city'){
		if ($('regime').get('value') != '' && filtertype == 'regime'){
			if (data.keyword != ''){
				var li_alles = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'regime\', \'\')">Toon alles voor &lsquo;'+myDecode(data.keyword)+'&rsquo;</a>'});
			} else {
				var li_alles = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'regime\', \'\')">Toon alles</a>'});
			}
			li_alles.inject(ul);
		} else {
			if (data.keyword != '') {
				var li_alles = new Element('li', {'html': '<strong><a href="javascript:void(0)" onclick="applyFilter(\'regime\', \'\')">Toon alles voor &lsquo;'+myDecode(data.keyword)+'&rsquo;</a></strong>'});
			} else {
				var li_alles = new Element('li', {'html': '<strong><a href="javascript:void(0)" onclick="applyFilter(\'regime\', \'\')">Toon alles</a></strong>'});
			}
			li_alles.inject(ul);
		}
//	}
	
	
	// The user selected something from the regime-filter menu
	if(filtertype == 'regime'){
		
		if (freelance > 0){
			if($('regime').get('value') != '3'){
				
				// 'Parent' category
				li_freelance = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'regime\', 3)">Freelance</a> <span>(' + freelance + ')</span>'});
				
			} else {
				
				// 'Parent' category
				li_freelance = new Element('li', {'html': '<strong><a href="javascript:void(0)" onclick="applyFilter(\'regime\', 3)">Freelance</a></strong> <span>(' + freelance + ')</span>'});
				
				// Insert sub list
				var sub_ul = new Element('ul');
				sub_ul.inject(li_freelance);
				
				// Loop and display the categories
				var cats = new Hash(data.count.regimes.freelance.categories);
				
				cats.each(function(el){
					count		= el.count;
					name		= el.name;
					quicklink	= el.quicklink;
					
					current 	= $('category').get('value');
					
					if (current == quicklink){
						var li = new Element('li', {'html': '<strong><a href="javascript:void(0)" onclick="applyFilter(\'category\', \''+quicklink+'\', \'regime\')">'+name+'</a></strong>&nbsp;<span>(' + count + ')</span>'});
					} else {
						var li = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'category\', \''+quicklink+'\', \'regime\')">'+name+'</a>&nbsp;<span>(' + count + ')</span>'});
					}
					
					li.inject(sub_ul);
				});
				
			}
		} else {
			li_freelance = new Element('li', {'html': 'Freelance&nbsp;<span>(0)</span>'});
		}
		li_freelance.inject(ul);
			
		
		if (deeltijds > 0){
			if($('regime').get('value') != '1'){
				li_deeltijds = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'regime\', 1)">Deeltijds</a>&nbsp;<span>(' + deeltijds + ')</span>'});
			
			} else {
				li_deeltijds = new Element('li', {'html': '<strong><a href="javascript:void(0)" onclick="applyFilter(\'regime\', 1)">Deeltijds</a></strong>&nbsp;<span>(' + deeltijds + ')</span>'});
			
				// Insert sub list
				var sub_ul = new Element('ul').addClass('test');
				sub_ul.inject(li_deeltijds);
				
				// Loop and display the categories
				var cats = new Hash(data.count.regimes.deeltijds.categories);
				
				cats.each(function(el){
					count		= el.count;
					name		= el.name;
					quicklink	= el.quicklink;
					
					current 	= $('category').get('value');
					
					if (current == quicklink){
						var li = new Element('li', {'html': '<strong><a href="javascript:void(0)" onclick="applyFilter(\'category\', \''+quicklink+'\', \'regime\')">'+name+'</a></strong>&nbsp;<span>(' + count + ')</span>'});
					} else {
						var li = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'category\', \''+quicklink+'\', \'regime\')">'+name+'</a>&nbsp;<span>(' + count + ')</span>'});
					}
					
					li.inject(sub_ul);
				});
			
			}
		} else {
			li_deeltijds = new Element('li', {'html': 'Deeltijds <span>(0)</span>'});
		}
		li_deeltijds.inject(ul);
		
		
		if (voltijds > 0){
			if($('regime').get('value') != '2'){
				li_voltijds = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'regime\', 2)">Voltijds</a>&nbsp;<span>(' + voltijds + ')</span>'});
			
			} else {
				li_voltijds = new Element('li', {'html': '<strong><a href="javascript:void(0)" onclick="applyFilter(\'regime\', 2)">Voltijds</a></strong>&nbsp;<span>(' + voltijds + ')</span>'});
		
				// Insert sub list
				var sub_ul = new Element('ul').addClass('test');
				sub_ul.inject(li_voltijds);
				
				// Loop and display the categories
				var cats = new Hash(data.count.regimes.voltijds.categories);
				
				cats.each(function(el){
					count		= el.count;
					name		= el.name;
					quicklink	= el.quicklink;
					
					current 	= $('category').get('value');
					
					if (current == quicklink){
						var li = new Element('li', {'html': '<strong><a href="javascript:void(0)" onclick="applyFilter(\'category\', \''+quicklink+'\', \'regime\')">'+name+'</a></strong>&nbsp;<span>(' + count + ')</span>'});
					} else {
						var li = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'category\', \''+quicklink+'\', \'regime\')">'+name+'</a>&nbsp;<span>(' + count + ')</span>'});
					}
					
					li.inject(sub_ul);
				});
			
			}
		} else {
			li_voltijds = new Element('li', {'html': 'Voltijds&nbsp;<span>(0)</span>'});
		}
		li_voltijds.inject(ul);
		
		
		
	// The user selected something from the category menu, so the regime should be to 'show all'
	} else {
				
		if (freelance > 0){
			li_freelance = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'regime\', 3)">Freelance</a>&nbsp;<span>(' + freelance + ')</span>'});
		} else {
			li_freelance = new Element('li', {'html': 'Freelance&nbsp;<span>(0)</span>'});
		}
		li_freelance.inject(ul);
			
		
		if (deeltijds > 0){
			li_deeltijds = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'regime\', 1)">Deeltijds</a>&nbsp;<span>(' + deeltijds + ')</span>'});
		} else {
			li_deeltijds = new Element('li', {'html': 'Deeltijds&nbsp;<span>(0)</span>'});
		}
		li_deeltijds.inject(ul);
		
		
		if (voltijds > 0){
			li_voltijds = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'regime\', 2)">Voltijds</a>&nbsp;<span>(' + voltijds + ')</span>'});
		} else {
			li_voltijds = new Element('li', {'html': 'Voltijds&nbsp;<span>(0)</span>'});
		}
		li_voltijds.inject(ul);
				
	}
	
}


var generateFilterCategory = function(data){
	
	// Variables for easy access
	var ul			= $('sectorFilter');
	var filtertype	= $('filtertype').get('value');
	var dominant	= $('dominant').get('value');
	
	// Clear the UL
	ul.innerHTML = '';
	
	// Init
	var count		= '';
	var name		= '';
	var quicklink	= '';
	var current		= '';
	
	// Put the first 'show all' link
//	var origin = window.location.href.split('?')[1].split('=')[0];
//	if(origin != 'category' && origin != 'city'){
	if(dominant != 'category'){
		if ($('category').get('value') != '' && filtertype == 'category'){
			if(data.keyword != ''){
				var li_alles = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'category\', \'\', \'\')">Toon alles voor &lsquo;'+myDecode(data.keyword)+'&rsquo;</a>'});
			} else {
				var li_alles = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'category\', \'\', \'\')">Toon alles</a>'});
			}
			li_alles.inject(ul);
		} else {
			if(data.keyword != ''){
				var li_alles = new Element('li', {'html': '<strong><a href="javascript:void(0)" onclick="applyFilter(\'category\', \'\', \'\')">Toon alles voor &lsquo;'+myDecode(data.keyword)+'&rsquo;</a></strong>'});
			} else {
				var li_alles = new Element('li', {'html': '<strong><a href="javascript:void(0)" onclick="applyFilter(\'category\', \'\', \'\')">Toon alles</a></strong>'});
			}
			li_alles.inject(ul);
		}
	}
//	}
	
	
	// The user is using the bottom filter (category)
	if(filtertype == 'category'){
		
		// Variables for easy access
		var totalcount	= '';
		
		// Loop and display the categories
		var cats = new Hash(data.count.categories);
//		var cats = data.count.categories;
		
		cats.each(function(el){
			count		= el.count;
			name		= el.name;
			quicklink	= el.quicklink;
			
			current 	= $('category').get('value');
			
			if (current == quicklink){
				var li = new Element('li', {'html': '<strong><a href="javascript:void(0)" onclick="applyFilter(\'category\', \''+quicklink+'\')">'+name+'</a></strong>&nbsp;<span>(' + count + ')</span>'});

				// Append an inline UL
				var sub_ul = new Element('ul');
				sub_ul.inject(li);
				
				// Append the regimes
				// Build list items
				totalcount = el.regimes.freelance;
				if (totalcount > 0){
					if($('regime').get('value') != '3'){
						li_freelance = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'regime\', 3, \'category\')">Freelance</a>&nbsp;<span>(' + totalcount + ')</span>'});
					} else {
						li_freelance = new Element('li', {'html': '<strong><a href="javascript:void(0)" onclick="applyFilter(\'regime\', 3, \'category\')">Freelance</a></strong>&nbsp;<span>(' + totalcount + ')</span>'});
					}
					li_freelance.inject(sub_ul);
				}
					
				
				totalcount = el.regimes.deeltijds;
				if (totalcount > 0){
					if($('regime').get('value') != '1'){
						li_deeltijds = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'regime\', 1, \'category\')">Deeltijds</a>&nbsp;<span>(' + totalcount + ')</span>'});
					} else {
						li_deeltijds = new Element('li', {'html': '<strong><a href="javascript:void(0)" onclick="applyFilter(\'regime\', 1, \'category\')">Deeltijds</a></strong>&nbsp;<span>(' + totalcount + ')</span>'});
					}
					li_deeltijds.inject(sub_ul);
				}
				
				
				totalcount = el.regimes.voltijds;
				if (totalcount > 0){
					if($('regime').get('value') != '2'){
						li_voltijds = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'regime\', 2, \'category\')">Voltijds</a>&nbsp;<span>(' + totalcount + ')</span>'});
					} else {
						li_voltijds = new Element('li', {'html': '<strong><a href="javascript:void(0)" onclick="applyFilter(\'regime\', 2, \'category\')">Voltijds</a></strong>&nbsp;<span>(' + totalcount + ')</span>'});
					}
					li_voltijds.inject(sub_ul);
				}
				
			} else {
				var li = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'category\', \''+quicklink+'\')">'+name+'</a>&nbsp;<span>(' + count + ')</span>'});
			}
			
			li.inject(ul);
		});
		
	// The user is using the regime-filter
	} else {
		
		// Loop and display the categories
		var cats = new Hash(data.count.categories);
		cats.each(function(el){
			count		= el.count;
			name		= el.name;
			quicklink	= el.quicklink;
			
			var li = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'category\', \''+quicklink+'\')">'+name+'</a>&nbsp;<span>(' + count + ')</span>'});
			
			li.inject(ul);
		});
		
	}
	
	
}


var generateFilterProvince = function(data){
	
	// Variables for easy access
	var ul			= $('provinceFilter');
	var filtertype	= $('filtertype').get('value');
	var dominant	= $('dominant').get('value');
	
	// Clear the UL
	ul.innerHTML = '';
	
	// Init
	var count		= '';
	var name		= '';
	var quicklink	= '';
	var current		= '';
	
	// Show all link
	if(dominant != 'province' && dominant != 'city'){
		if ($('province').get('value') != '' && filtertype == 'province'){
				if(data.keyword != ''){
					var li_alles = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'province\', \'\', \'\')">Toon alles voor &lsquo;'+myDecode(data.keyword)+'&rsquo;</a>'});
				} else {
					var li_alles = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'province\', \'\', \'\')">Toon alles</a>'});
				}
				li_alles.inject(ul);
		} else {
			if(data.keyword != ''){
				var li_alles = new Element('li', {'html': '<strong><a href="javascript:void(0)" onclick="applyFilter(\'province\', \'\', \'\')">Toon alles voor &lsquo;'+myDecode(data.keyword)+'&rsquo;</a></strong>'});
			} else {
				var li_alles = new Element('li', {'html': '<strong><a href="javascript:void(0)" onclick="applyFilter(\'province\', \'\', \'\')">Toon alles</a></strong>'});
			}
			li_alles.inject(ul);
		}
	}
	
	// See if we're using the province filter
	if(filtertype == 'province'){
		
		// Variables for easy access
		var totalcount	= '';
		
		// Loop and display the categories
		var provs = new Hash(data.count.provinces);
		
		provs.each(function(el){
			count		= el.count;
			name		= el.name;
			quicklink	= el.quicklink;
			
			current 	= $('province').get('value');
			
			if (current == quicklink){
				var li = new Element('li', {'html': '<strong><a href="javascript:void(0)" onclick="applyFilter(\'province\', \''+quicklink+'\')">'+name+'</a></strong>&nbsp;<span>(' + count + ')</span>'});
			} else {
				var li = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'province\', \''+quicklink+'\')">'+name+'</a>&nbsp;<span>(' + count + ')</span>'});
			}
			
			li.inject(ul);
		});
		
	// Not using the provinces filter
	} else {
		
		// Loop and display the categories
		var provs = new Hash(data.count.provinces);
		
		provs.each(function(el){
			count		= el.count;
			name		= el.name;
			quicklink	= el.quicklink;
			
			var li = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'province\', \''+quicklink+'\')">'+name+'</a>&nbsp;<span>(' + count + ')</span>'});
			
			li.inject(ul);
		});
		
	}
		
}


var generateFilterCity = function(data){
	
	// Variables for easy access
	var ul			= $('cityFilter');
	var filtertype	= $('filtertype').get('value');
	var dominant	= $('dominant').get('value');
	
	// Temp fix
	if(ul == null)
		return;
	
	// Clear the UL
	ul.innerHTML = '';
	
	// Init
	var count		= '';
	var name		= '';
	var quicklink	= '';
	var current		= '';
	
	// Show all link
	if(dominant != 'city'){
		if ($('city').get('value') != '' && filtertype == 'city'){
			if(data.keyword != ''){
				var li_alles = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'city\', \'\', \'\')">Toon alles voor &lsquo;'+myDecode(data.keyword)+'&rsquo;</a>'});
			} else {
				var li_alles = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'city\', \'\', \'\')">Toon alles</a>'});
			}
			li_alles.inject(ul);
		} else {
			if(data.keyword != ''){
				var li_alles = new Element('li', {'html': '<strong><a href="javascript:void(0)" onclick="applyFilter(\'city\', \'\', \'\')">Toon alles voor &lsquo;'+myDecode(data.keyword)+'&rsquo;</a></strong>'});
			} else {
				var li_alles = new Element('li', {'html': '<strong><a href="javascript:void(0)" onclick="applyFilter(\'city\', \'\', \'\')">Toon alles</a></strong>'});
			}
			li_alles.inject(ul);
		}
	}
	
	// See if we're using the province filter
	if(filtertype == 'city'){
		
		// Variables for easy access
		var totalcount	= '';
		
		var cities = new Hash(data.count.cities);
		
		cities.each(function(el){
			count		= el.count;
			name		= el.name;
			quicklink	= el.quicklink;
			
			current 	= $('city').get('value');
			
			if (current == quicklink){
				var li = new Element('li', {'html': '<strong><a href="javascript:void(0)" onclick="applyFilter(\'city\', \''+quicklink+'\')">'+name+'</a></strong>&nbsp;<span>(' + count + ')</span>'});
			} else {
				var li = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'city\', \''+quicklink+'\')">'+name+'</a>&nbsp;<span>(' + count + ')</span>'});
			}
			
			li.inject(ul);
		});
		
	// Not using the cities filter
	} else {
		
		var cities = new Hash(data.count.cities);
		
		cities.each(function(el){
			count		= el.count;
			name		= el.name;
			quicklink	= el.quicklink;
			
			var li = new Element('li', {'html': '<a href="javascript:void(0)" onclick="applyFilter(\'city\', \''+quicklink+'\')">'+name+'</a>&nbsp;<span>(' + count + ')</span>'});
			
			li.inject(ul);
		});
		
	}
		
}



var handleResults = function(data) {
	
	// Clear out the main UL
	$$('ul.table')[0].innerHTML = '';
	
	// Check what the result is
	if(data.success == false){
		
		$$('ul.table')[0].innerHTML = '<p>' + data.message + '</p>';
		
		// Generate the filters
		generateFilterRegime(data);
//		generateFilterDate(data);
		generateFilterCategory(data);
		generateFilterProvince(data);
		generateFilterCity(data);
		
	} else {
		
		if($('clickedprovince').get('value') == 'false' && $('dominant').get('value') != 'province' && $('dominant').get('value') != 'city'){
			$('cityFilterDiv').setStyle('display', 'none');
		} else {
			$('cityFilterDiv').setStyle('display', 'block');
		}
		
		// Set a line of text
		$$('h2.searchtitle').each(function(el){
			if(data.count.total > 1) { var val = 'vacatures' } else { var val = 'vacature' }
			var msg = data.count.total + ' ' + val + ' gevonden';
			if($chk(data.keyword)) { msg += ' voor (' + data.keyword + ')'; };
			if($chk(data.province)) { msg += ' in de provincie ' + data.province; };
			el.innerHTML = msg;
		});
		
		// Alter the page title
		if($chk(data.keyword) || $chk(data.category) || $chk(data.keyword)){
			var documentTitle = '';
			documentTitle += data.keyword || '';
			documentTitle += data.category? ' ' + data.category + ' ' : ' ';
			documentTitle += data.province? ' ' + data.province + ' ' : ' ';
			documentTitle += 'vacatures';
			document.title = documentTitle;
		} else {
			document.title = originalPageTitle;
		}
		
		// Generates the header
		generateHeader(data, false);
		
		// Generates the footer
		generateHeader(data, true);
		
		// Add a 'marker' to the last record, for a fancy CSS line
		data.records.getLast().isLast = true;
		
		// Generates the rows
		data.records.each(function(record){
			generateRow(record);
		});
		
		// Generate the filters
		generateFilterRegime(data);
//		generateFilterDate(data);
		generateFilterCategory(data);
		generateFilterProvince(data);
		generateFilterCity(data);
		
		// Get the nice click
		niceClick();
		
	}
	
	// Scroll up!
	var toTop = new Fx.Scroll($(document.body)).toTop();
}



var mouseOverHandler = function() {
	
	this.setStyle('cursor', 'pointer');
	this.addEvent('click', function(){
		window.location = this.getElement('a').get('href');
	});
	
}

/**
 * U S E R   C O N T R O L S
 */

// Function called when the user goes to the next page
var nextPage = function(){
	
	// Go up one page
	var currpage = $('page').get('value');
	var _nextpage = ++currpage;
	$('page').set('value', (_nextpage));
	
	document.location = 'http://' + document.location.hostname + document.location.pathname + '#' + _nextpage;
	
	// Perform the search again
	search();
	
}

// Function called when the user goes to the previous page
var prevPage = function(){
	
	// Go up one page
	var currpage = $('page').get('value');
	var _prevpage = --currpage;
	$('page').set('value', (_prevpage));
	
	// Set the url has
	//document.location.hash = '#page=' + _prevpage;
	document.location = 'http://' + document.location.hostname + document.location.pathname + '#' + _prevpage;
	
	// Perform the search again
	search();
	
}

// Function to apply a filter to the search
var applyFilter = function(filter, value, parent){
	
	// Reset the page to 1
	$('page').set('value', '1');
	
	var dominant = $('dominant').get('value');
	
	if (parent === undefined){
		
		$('clickedprovince').set('value', 'false');
		
		// The parent was not set, so unset the child
		if(filter == 'regime'){
			if(dominant != 'category')	$('category').set('value', '');
			if(dominant != 'province')	$('province').set('value', '');
			if(dominant != 'city')		$('city').set('value', '');
		} else if(filter == 'category'){
			$('regime').set('value', '');
			
			if(dominant != 'province')	$('province').set('value', '');
			if(dominant != 'city')		$('city').set('value', '');
		} else if(filter == 'province'){
			$('clickedprovince').set('value', 'true');
			$('regime').set('value', '');
			
			if(dominant != 'category')	$('category').set('value', '');
			if(dominant != 'city')		$('city').set('value', '');
		} else if(filter == 'city'){
			$('regime').set('value', '');
			
			if(dominant != 'category')	$('category').set('value', '');
			$('clickedprovince').set('value', 'true');
		}
		
		parent = filter;
	}
	
	// Apply the filter
	$(filter).set('value', value);
	
	// Set which type of filter is being used
	$('filtertype').set('value', parent);
	
	// Perform the search again
	search();
	
}

// Nice list-click
var niceClick = function() {
	$$('div.content ul.table li.tr').each(function(el) {
	
		el.addEvent('mouseover', mouseOverHandler);
	
	});
}

var strlength = '';
var strlengthlimit = 60;
function prepTitle(string){
	strlength = string.length;
	if(strlength > strlengthlimit){
		string = string.substr(0, strlengthlimit) + '...';
		return htmlentities(string);
	} else {
		return htmlentities(string);
	}
}

function htmlentities (string, quote_style) {
    // Convert all applicable characters to HTML entities  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/htmlentities    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: nobbler
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // -    depends on: get_html_translation_table
    // *     example 1: htmlentities('Kevin & van Zonneveld');    // *     returns 1: 'Kevin &amp; van Zonneveld'
    // *     example 2: htmlentities("foo'bar","ENT_QUOTES");
    // *     returns 2: 'foo&#039;bar'
    var hash_map = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();    
    if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }
    hash_map["'"] = '&#039;';    for (symbol in hash_map) {
        entity = hash_map[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }
        return tmp_str;
}


function get_html_translation_table (table, quote_style) {
    // Returns the internal translation table used by htmlspecialchars and htmlentities  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/get_html_translation_table    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // +   bugfixed by: Alex
    // +   bugfixed by: Marco    // +   bugfixed by: madipta
    // +   improved by: KELAN
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Frank Forte    // +   bugfixed by: T.Wild
    // +      input by: Ratheous
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js, meaning the constants are not
    // %          note: real constants, but strings instead. Integers are also supported if someone    // %          note: chooses to create the constants themselves.
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    
    var entities = {}, hash_map = {}, decimal = 0, symbol = '';    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';
     useTable       = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
    useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';
 
    if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
        throw new Error("Table: "+useTable+' not supported');        // return false;
    }
 
    entities['38'] = '&amp;';
    if (useTable === 'HTML_ENTITIES') {        entities['160'] = '&nbsp;';
        entities['161'] = '&iexcl;';
        entities['162'] = '&cent;';
        entities['163'] = '&pound;';
        entities['164'] = '&curren;';        entities['165'] = '&yen;';
        entities['166'] = '&brvbar;';
        entities['167'] = '&sect;';
        entities['168'] = '&uml;';
        entities['169'] = '&copy;';        entities['170'] = '&ordf;';
        entities['171'] = '&laquo;';
        entities['172'] = '&not;';
        entities['173'] = '&shy;';
        entities['174'] = '&reg;';        entities['175'] = '&macr;';
        entities['176'] = '&deg;';
        entities['177'] = '&plusmn;';
        entities['178'] = '&sup2;';
        entities['179'] = '&sup3;';        entities['180'] = '&acute;';
        entities['181'] = '&micro;';
        entities['182'] = '&para;';
        entities['183'] = '&middot;';
        entities['184'] = '&cedil;';        entities['185'] = '&sup1;';
        entities['186'] = '&ordm;';
        entities['187'] = '&raquo;';
        entities['188'] = '&frac14;';
        entities['189'] = '&frac12;';        entities['190'] = '&frac34;';
        entities['191'] = '&iquest;';
        entities['192'] = '&Agrave;';
        entities['193'] = '&Aacute;';
        entities['194'] = '&Acirc;';        entities['195'] = '&Atilde;';
        entities['196'] = '&Auml;';
        entities['197'] = '&Aring;';
        entities['198'] = '&AElig;';
        entities['199'] = '&Ccedil;';        entities['200'] = '&Egrave;';
        entities['201'] = '&Eacute;';
        entities['202'] = '&Ecirc;';
        entities['203'] = '&Euml;';
        entities['204'] = '&Igrave;';        entities['205'] = '&Iacute;';
        entities['206'] = '&Icirc;';
        entities['207'] = '&Iuml;';
        entities['208'] = '&ETH;';
        entities['209'] = '&Ntilde;';        entities['210'] = '&Ograve;';
        entities['211'] = '&Oacute;';
        entities['212'] = '&Ocirc;';
        entities['213'] = '&Otilde;';
        entities['214'] = '&Ouml;';        entities['215'] = '&times;';
        entities['216'] = '&Oslash;';
        entities['217'] = '&Ugrave;';
        entities['218'] = '&Uacute;';
        entities['219'] = '&Ucirc;';        entities['220'] = '&Uuml;';
        entities['221'] = '&Yacute;';
        entities['222'] = '&THORN;';
        entities['223'] = '&szlig;';
        entities['224'] = '&agrave;';        entities['225'] = '&aacute;';
        entities['226'] = '&acirc;';
        entities['227'] = '&atilde;';
        entities['228'] = '&auml;';
        entities['229'] = '&aring;';        entities['230'] = '&aelig;';
        entities['231'] = '&ccedil;';
        entities['232'] = '&egrave;';
        entities['233'] = '&eacute;';
        entities['234'] = '&ecirc;';        entities['235'] = '&euml;';
        entities['236'] = '&igrave;';
        entities['237'] = '&iacute;';
        entities['238'] = '&icirc;';
        entities['239'] = '&iuml;';        entities['240'] = '&eth;';
        entities['241'] = '&ntilde;';
        entities['242'] = '&ograve;';
        entities['243'] = '&oacute;';
        entities['244'] = '&ocirc;';        entities['245'] = '&otilde;';
        entities['246'] = '&ouml;';
        entities['247'] = '&divide;';
        entities['248'] = '&oslash;';
        entities['249'] = '&ugrave;';        entities['250'] = '&uacute;';
        entities['251'] = '&ucirc;';
        entities['252'] = '&uuml;';
        entities['253'] = '&yacute;';
        entities['254'] = '&thorn;';        entities['255'] = '&yuml;';
    }
 
    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';    }
    if (useQuoteStyle === 'ENT_QUOTES') {
        entities['39'] = '&#39;';
    }
    entities['60'] = '&lt;';    entities['62'] = '&gt;';
 
 
    // ascii decimals to real symbols
    for (decimal in entities) {        symbol = String.fromCharCode(decimal);
        hash_map[symbol] = entities[decimal];
    }
    
    return hash_map;
}


var myDecode = function urlencode(str) {
	
	var temp = str.split('-');
	return temp.join(' ');
	
}


var fireOn = (Browser.Engine.trident) ? 'load' : 'domready';
window.addEvent(fireOn,function(){
	
	originalPageTitle = document.title;
	
	search();

});
