jQuery.fn.ccMenu = function(menu, mostUsefullCC, recentNumbers) {

	var menu = $(menu);

	return this.each(function() {
		var current = this;

		function hide() {
			menu.hide();
			$(document).unbind("click.cc");
			$(current).unbind("keydown");
		}

		function show() {

			var recent = menu.find(".cc-recent").empty();
			var usefull = menu.find(".cc-most-usefull").empty();

			menu.find(".cc-all").unbind("change");

			jQuery.each(mostUsefullCC(), function() {
			    usefull.append('<li class="cc-selectable" val="' + this[1] + '">' + 
						 this[0] + " " + this[1] + 
						 "</li>");
			});

			var recentList = recentNumbers();

			if(recentList && recentList.length > 0) {
				$.each(recentList, function() {
					recent.append('<li class="cc-selectable" val="' + this + '">' + 
							 this + 
								  "</li>");
				});
			} else {
				menu.find(".cc-recent-container").hide();
			}

			//$(current).keydown(handleKeyDown);

			//hide when clicked outside
			$(document).bind("click.cc", function(e){
			   if(e.target != current && 
			       e.target != menu.get(0) && 
			       $(e.target).parents().index(menu.get(0)) < 0)
			    {
				    hide();
			    }
            });		

			menu.find(".cc-selectable").hover(
			  function() { $(this).addClass("cc-selectable-on"); },
			  function() { $(this).removeClass("cc-selectable-on"); });

			//selectable selected
			menu.find(".cc-selectable").bind("click", function() {
			    $(current).focus();
			    $(current).attr("value", $(this).attr("val"));
                $(current).blur();
                $(current).focus();
			    hide();
		    });

			//cc from full list selected
			menu.find(".cc-all").bind("change", function() {
			    $(current).focus();
			    $(current).attr("value", $(this).attr("value"));
			    hide();
		    });

			//that is instead of blur
			$(current).keydown(function(e){
					if(e.keyCode == 9) //tab
						hide();
            });

			var pos = $(current).offset();
            var left;
            if (menu.width()+pos.left-70 > $(window).width() + $(window).scrollLeft())
                left = $(window).width() + $(window).scrollLeft() - menu.width() - 20;
            else
                left = pos.left;

            menu.show().
                css('top', pos.top + jQuery(current).height() + 10 + 'px').
                css('left', left + 'px');

           //if($.browser.msie) menu.bgiframe();
		}

		//show only when field is empty
		$(current).keyup(function(e){
			if($(current).val() == ''){
			    show();
            } else {
			    hide();
			}
		});

		$(current).bind('focus', function(){
			if($(current).val() == ''){
			    show();
			}
		});
	});
}
