var Data = {
	initialized: null,
	plaatsen: null,
	pollInterval: null,

	/**
	 * Loads initial data and binds keyup event to refine data.
	 */
	initialize: function() {
		// Data.load();
		// $('#input-plaats').bind('keyup', Data.refine);

		$('#input-plaats').bind('keyup', function() {
			Data.loadAsp();
		});

		Data.initialized = true;
	},

	/**
	 * Starts loading ASP every 0.2 seconds.
	 */
	startPolling: function() {
		Data.pollInterval = window.setInterval(Data.loadAsp, 200);
	},

	/**
	 * Stops polling after 0.4 seconds of inactivity.
	 */
	stopPolling: function() {
	},

	/**
	 * Receives data from server.
	 */
	receive: function(text) {
		var plaatsen = text.split("\r");

		var html = new String();
		for (var i = 0; i < plaatsen.length; i++) {
			html += '<option value="' + plaatsen[i] + '">' + plaatsen[i] + '</li>';
		}

		$('#select-plaatsen').empty().html(html).show();
	},

	/**
	 * Adapter for initializing and loading data.
	 */
	load: function() {
		if (Data.initialized == null) {
			Data.initialize();
		}

		var method = $('#method').val();

		switch (method) {
			case 'firstLetter':
				Data.loadFirstLetter();
				break;
			case 'asp':
				Data.loadAsp();
				break;
			default: Data.loadAll();
		}
	},

	/**
	 * Loads data from server.
	 */
	loadAll: function() {
		$.get('data/plaatsen.txt', Data.receive);
	},

	/**
	 * Loads data file based on first letter.
	 */
	loadFirstLetter: function() {
		var plaats = $('#input-plaats').val();
		var firstLetter = plaats[0].toLowerCase();
		$.get('data/alfabetisch/' + firstLetter + '.txt', Data.receive);
	},

	/**
	 * Loads data from Active Server Page.
	 */
	loadAsp: function() {
		var plaats = $('#input-plaats').attr('value');

		$.get('/gezochtmaatjes/test.asp?l=' + plaats, function(html) {
			$('#select-plaatsen').empty().html(html).show();
		});
	},

	/**
	 * Removes places that don't start with the typed letters.
	 */
	refine: function() {
		var plaats = $('#input-plaats').val();
		$('#select-plaatsen option:not([value^=' + plaats + '])').remove();
	},

	/**
	 * Clears list from object and empties select box.
	 */
	clear: function() {
		Data.plaatsen = null;
		$('#select-plaatsen').empty().hide();
	}
};