function loadTowns(selectDetector, countySelector){
	
	countyValue = $(countySelector).children('option:selected').val();
	
	$(selectDetector + ' > option').not(':first').remove();
	
	url = '/meditation/town';
	$.get(url, {'county_id':countyValue}, function(data){
		$(selectDetector).children('option:first').after(data);
	});
	
}
	
function filterTowns(cloned_select, county_id){

	if(county_id > 0){
		
		$('#filter-town').children('option').not(':first').each(function(){
			
			$(this).remove();
			
		});

		cloned_select.children('option[rel="' + county_id + '"]').each(function(){

			current_option = $(this).clone();
			$('#filter-town').append(current_option);
	
		});	
		
		$('#filter-town').attr('selectedIndex', '0');
		
	}

}

$(document).ready(function(){

	$('#filter-max-price').click(function(){
		$(this).val('');	
	});
	
	$('#filter-max-price').keypress(function(e){
		
		var characterCode;
		
		if(e && e.which){ //if which property of event object is supported (NN4)
			//e = e;
			characterCode = e.which; //character code is contained in NN4's which property
		}
		else {
			//e = event;
			characterCode = e.keyCode //character code is contained in IE's keyCode property
		}
		
		/*
		 * If character is not 0-9 or BACKSPACE
		 */
		if(characterCode != 8 && (characterCode < 48 || characterCode > 59)){
			/* Old version
			 //If "." or "," don't exist yet
			existingText = $(this).val();
			if(existingText.search(/\,|\./) == -1){
				//If pressed key is not "." or "," 
				if(!(characterCode == 44 || characterCode == 46)){
					return false;
				}
				
			}
			else{
				return false;
			}
			*/
			
			/*
			 * New version : Allow only digits
			 */
			return false;
		}
		
	});
	/*
	 * Filter towns action according to selected county
	 */
	var cloned_select = $('#filter-town').clone();
		
	selected_county_index = parseInt($('#filter-county').children('option:selected').val());	
	
	if(selected_county_index > 0){
		$('#filter-town').children('option[rel!="' + selected_county_index + '"]').not(':first').remove();
	}
	else{
		$('#filter-town').children('option').not(':first').remove();
	}	
	
	$('#filter-county').change(function(){
		
		selected_county_id = parseInt($(this).children('option:selected').val());
		
		if(selected_county_id > 0){
		
			filterTowns(cloned_select, selected_county_id);
		
		}
		
	});
	/*
	 * If lesson filter is selected than show it's name above the announces
	 */
	text = $('#filter-lesson-name strong').html();;
	selected = $('#filter-lesson ').val() > 0 ? 1 : 0;
	$('#filter-lesson-name strong').html(text + (selected ? ' la ' + $('#filter-lesson').children('option:selected').text().toLowerCase() : ''));
	
});
