document.observe('dom:loaded', function() {
	var url = 'http://www.bijvrieling.nl/cardata';
	
	var merkSelect = $('merk-select') ? $('merk-select') : null;
	var modelSelect = $('model-select') ? $('model-select') : null;
	var typeSelect = $('type-select') ? $('type-select') : null;
	
	if(merkSelect){
		merkSelect.observe('change', function() {
			new Ajax.Request(url, {
				method: 'get',
				parameters: {
					brand: this.value
				},
				onComplete: function(response) {
					var r = response.responseText.split(';').clean('');
					emptySelect(modelSelect, 1);
					emptySelect(typeSelect, 1);
					populateSelect(modelSelect, r);
				}
			});
		});
	}
		
	if(modelSelect){
		modelSelect.observe('change', function() {
			new Ajax.Request(url, {
				method: 'get',
				parameters: {
					brand: merkSelect.value,
					model: this.value
				},
				onComplete: function(response) {
					var r = response.responseText.split(';').clean('');
					populateSelect(typeSelect, r);
				}
			});
		});
	}
});

function emptySelect(obj, offset) {
	while(obj.hasChildNodes() && obj.length > offset) {
		obj.remove(obj.length - 1);
	}
}

function populateSelect(obj, arr) {
	// Clear all options except the first
	emptySelect(obj, 1);
	
	// Fill select with new options
	for(var i = 0; i < arr.length; i++) {
		opt = document.createElement('option');
		opt.value = opt.innerHTML = arr[i];
		obj.appendChild(opt);
	}
}


/**
 * Helper functions
 * ----------------
 */

/**
 * Clears array items that matches val.
 * 
 * @param {Object} val The value to match
 */
Array.prototype.clean = function(val) {
	for(var i = 0; i < this.length; i++) {
		if(this[i] == val) {
			this.splice(i, 1);
			i--;
		}
	}
	return this;
}

/**
 * IE's implementation of .split(..) completely ignores the grouping request.
 * 
 * @param {Object} _regEx The regular expression
 * @see http://blog.stchur.com/2007/03/28/split-broken-in-ie/
 */
String.prototype.xSplit = function(_regEx) {
	// Most browsers can do this properly, so let them -- they'll do it faster
	if('a~b'.split(/(~)/).length === 3) {
		return this.split(_regEx);
	}
	
	if(!_regEx.global) {
		_regEx = new RegExp(_regEx.source, 'g' + (_regEx.ignoreCase ? 'i' : ''));
	}
	
	// IE (and any other browser that can't capture the delimiter)
	// will, unfortunately, have to be slowed down
	var m, str = '', arr = [];
	var i, len = this.length;
	for(i = 0; i < len; i++) {
		str += this.charAt(i);
		m = str.match(_regEx);
		if(m) {
			arr.push(str.replace(m[0], ''));
			arr.push(m[0]);
			str = '';
		}
	}
	
	if (str != '') arr.push(str);
	
	return arr;
}
