jQuery.fn.extend({
	flex : function (callback) {
		var flexObject = this;
	
		$(flexObject).addClass("flex-context");
	
		$(".flex-default").hide();
	
		$(this).each(function () {
			if ($(this).hasClass("sortable")) {
				var flexer = this;
				$(".sortable .flex-row", flexer).live("mouseover", function () {
					// If we're in input mode...
					if ($(".input:visible", flexer).size() > 0) {
						function indexUpdater(event, ui) {
							$(ui.item).parents(".sortable").find(".flex-row").each(function (i) {
								$("input:hidden[name*='index']", this).val(i);
							});
						}
	
						$(this).addClass("sortable-active");
						var handler = $(".sortable-display-handle", this);
						var position = $(handler).parent(":first").position();
						handler.css({position: 'absolute', top : position.top + 8, left : position.left - 15}).show();
						$(flexer).sortable({axis: "y", items : ".flex-row", cursor : "move", stop : indexUpdater});
					}
				});
	
				$(".sortable .flex-row", flexer).live("mouseout", function () {
					$(this).removeClass("sortable-active");
					$(".sortable-display-handle", this).hide();
					$(flexObject).sortable("destroy");
				});
			}
		});
	
		$(".flex-minus", flexObject).live("click", function () {
			$(this).parents(".flex-row").hide().find("input:hidden[name*='operation']").val("DELETE");
	
			if (callback) {
				callback(flexObject);
			}
		});
	
		$(".flex-plus", flexObject).live("click", function () {
			var flexContext = $(this).parents(".flex-context");
			var index = $(".flex-row", flexContext).size();
			var defaultRow = $(".flex-default", flexContext);
			var newRow = $(defaultRow).clone(true).removeClass("flex-default hidden").addClass("flex-row").show();
				
			$("select, input", newRow).each(function () {
				var name = $(this).attr("name");
				var id = $(this).attr("id");
				$(this).attr({name : name.replace(".defaultRow", "[" + index + "]"), id : id.replace("defaultRow", index)});
			});
			
			newRow.insertBefore(defaultRow);
	
			if (callback) {
				callback(flexObject);
			}		
		});
	}
	
});


$(function() {
	$(".flex").flex();
});
