$(document).ready(function () {
    createDropDown();

    $(".dropdown dt a").live("click", function (event) {
        event.preventDefault();
        var dropID = $(this).closest("dl").attr("id");
        $("#" + dropID).find("ul").toggle();
    });

    $(document).bind('click', function (e) {
        var $clicked = $(e.target);
        if (!$clicked.parents().hasClass("dropdown"))
            $(".dropdown dd ul").hide();
    });


    $(".dropdown li a").live("click", function () {

        var dl = $(this).closest("dl");
        var dropID = dl.attr("id");
        var text = $(this).html();
        var source = dl.prev();
        var selectedLi = $(this)
        $("#" + dropID + " dt a").html(text);
        $("#" + dropID + " dd ul").hide();

        var newVal = $(this).find("span.value").html();

        $("#" + dropID + " dd ul li span.value").each(function () {
            if ($(this).html() == newVal)
                $(this).closest('li').addClass('selected');
            else
                $(this).closest('li').removeClass('selected');
        });

        source.val(newVal);
        // trigger change event because of neighbourhood automatic filtering
        source.change();
        $(dl.attr("data-selector")).val(newVal);
    });
}); 

function createDropDown() { 
  var selects = $("select.dropdown_value"); 
  
  var idCounter = 1; 
  selects.each(function() { 
    var selectName = $(this).attr("name");
    var dropID = "dropdown_" + idCounter; 
    var source = $(this); 
    var selected = source.find("option[selected]"); 
      var selectedText = selected.html();
      //alert(selected.text());
    var options = $("option", source); 
    source.after('<dl id="' + dropID + '" class="dropdown ' + selectName + '" data-selector="#' + selectName + '"></dl>'); 
    $("#" + dropID).append('<dt><a href="#">' + selected.text() + '<span class="value">' + selected.val() + '</span></a></dt>'); 
    $("#" + dropID).append('<dd><ul></ul></dd>'); 
      var text = selectedText;
    options.each(function() { 
          text = text + ' ' + $(this).html();
          var textEqual = $(this).html() == selectedText;
          //if ($(this).html() == 'Any')
              //alert('<li' + (textEqual ? ' class="selected"' : '') + '><a href="#">' + $(this).text() + '<span class="value">' + $(this).val() + '</span></a></li>');
          $("#" + dropID + " dd ul").append('<li' + (textEqual ? ' class="selected"' : '') + '><a href="#">' + $(this).text() + '<span class="value">' + $(this).val() + '</span></a></li>');
    }); 
    idCounter++; 
  }); 
}
