$(function() {
	$("#add_filter").click(function() {
		var clone = $("#dropdown_prototype").children().clone();
		$("#competence_filters").append(clone);
		bindDelete();
	});
	
	$("#filters").submit(function(){
		var zip_from = getZip("#zip_from");
		var zip_to = getZip("#zip_to");
		var zip_url = "0";
		var max = Math.max(zip_from, zip_to);
		if (Math.min(zip_from, zip_to) == -1 && max > -1) {
			zip_from = max;
			zip_to = max;
		}
		if (zip_from != -1 && zip_to != -1) {
			zip_url = zip_from + "-" + zip_to;
		}
		var competencies = "";
		$(".competence-dropdown").each(function() {
			var competence = $(this).val();
			if (competence != "empty") {
				competencies += "/" + competence;
			}
		});
		location.href="/freelancers/0/" + zip_url + competencies;
		return false;
	});
	bindDelete();
});

function bindDelete() {
	$(".delete-row").unbind("click").click(function(){
		$(this).parent().remove();
	});
}

function getZip(selector) {
	var zip = getInt(selector, -1);
	zip = Math.min(Math.max(zip, -1), 9999);
	return zip;
}

function getInt(selector, default_value) {
	var int_value = parseInt($(selector).val());
	if (isNaN(int_value)) {
		return default_value;
	} else {
		return int_value;
	}
}

