$.initPlaceDropDowns = function(options) {
    var opts = $.extend({
        url: ''
    }, options);

    function remove_extra_selects(maxLevel){
        $(".place-dropdown").each(function(){
            var level = parseInt($(this).attr("id").replace("places-level-", ""));
            if (!isNaN(level) && level > maxLevel) {
                $(this).remove();
            }
        });
    }

	function clickHandler(self) {
		if (self.parent().parent().hasClass("final")) {
            return true;
        }

        var place = self.attr("rel"),
        level = parseInt(self.parents('.place-dropdown').attr("id").replace("places-level-", ""));
        
		if (isNaN(level)) level = 0;
        remove_extra_selects(level);

        $.get(opts.url, {'place': place}, function(data){
            if (data.search('place-dropdown') != -1){
                $("#places-selects").append($(data).attr('id', 'places-level-' + (level + 1)));
				$('#places-level-' + (level + 1) + ' a').click(function(){
					var self = $(this);
					return clickHandler(self);
				})
            } else {
				location.href = self.attr('href')
			}
        });
		return false
	}
	
    $(".place-dropdown li a").bind('click', function(){
		var self = $(this);
		return clickHandler(self);
    });

    $('#places-selects > span').click(function(){
        if ($(this).parent().children('.dropdown:first').is(':visible')){
            $(this).parent().children('.dropdown').fadeOut();
        } else {
            $(this).parent().children('.dropdown').fadeIn()
        }

        $(this).parent().children('.arrow').toggleClass('up');
        return false
    })
	
	$('#places-selects').click(function(event){
		event.stopPropagation();
	})
	
	$('body').bind('click', function(){
		if ($('#places-selects').children('.dropdown:first').is(':visible')){
			$('#places-selects > span:first').click();
		}
	});
	
}
