String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}


function updatePlaceSel(placestring) {
	$('#sted_sel')[0].disabled = false;
	$('#sted_sel option').each(function() {
		if (this.innerHTML.toLowerCase().indexOf(placestring.toLowerCase().trim()) == -1 && this.index>0 && placestring.length >0) {
			$(this).hide();
		}
		else if (this.index == 0 && (this.parentNode.options.length == 1 || placestring.length == 0)) {
			this.selected = true;
		}
		else {
			$(this).show();
			if (placestring.length) this.selected = true;
		}
		
	});
	$('#sted_sel').hide().show();
}

function onUpdatePlaceSel() {
	$('#new_place')[0].value = '';
}

var createNewLocation = false

function validateNewPlace(place) {
	var matches = new Array()
	var keywords = place.split(' ');
	for (key in keywords) {
		$('#sted_sel option').each(function() {
			if (this.innerHTML.toLowerCase().indexOf(keywords[key].toLowerCase().trim()) > -1 && this.index>0 && keywords[key].length >1) {
				matches.push(Array(this.index,this.innerHTML));
			}
		});
	}
	
	if (matches.length && !createNewLocation) {
		html = '<div id="dialog">';
		html += '<h3>OBS!</h3>';		
		html += '<p>Vælg et af nedenstående steder til dit arrangement, eller bekræft at der skal oprettes en ny lokation</p>';
		html += '<ul>';
		for (var i=0; i<matches.length; i++)
			html+='<li><a href="javascript: selectPlaceByIndex('+matches[i][0]+')">'+matches[i][1]+'</a></li>';
		html += '</ul>';		
		html += '<p>Det er vigtigt at der ikke opstår flere lokationer i databasen, som henviser til det samme sted</p>';
		//html += '<p>Der er allerede en eller flere lokationer, der minder om den lokation du har indtastet som et nyt sted. Er du sikker på at et af disse ikke er det korrekte sted for dit arrangement?</p>';
		html += '<p><a href="javascript: void(0);" onclick="selectPlaceByIndex(0);createNewLocation=true;">Ja tak, jeg vil gerne oprette en ny lokation</a></p>'
		html += '</div>';
		
		$('.container').append(html)
		return false;
	}
	else {
		return true;
	}
	
}

function selectPlaceByIndex(index) {
	$('#sted_sel')[0].selectedIndex = index;
	if (index>0)
		$('#new_place')[0].value='';
	else	
		$('#sted_sel')[0].disabled = true;
	$('#dialog').remove();
}
