$(function(){
	// show text input fields when necessary
	$("input.type_answer").click(function(){
		if( this.checked ) {
			$("input[@name='" + this.name.replace(/\[\d+\]/,"") + "_other']").fadeIn();
		} else {
			$("input[@name='" + this.name.replace(/\[\d+\]/,"") + "_other']").val("").fadeOut();
		}
	});
	
	// make multiple choice questions max 3 answers
	$("input.multiplechoice").click(function(){
		if( $("input[@name^='" + this.name.replace(/\[\d+\]/,"") + "']:checked").length == 3 ) {
			$("input[@name^='" + this.name.replace(/\[\d+\]/,"") + "'][@type='checkbox']").each(function(){
				if( !this.checked ) {
					this.disabled = true;
				}
			});
		} else {
			$("input[@name^='" + this.name.replace(/\[\d+\]/,"") + "'][@type='checkbox']").each(function(){
				if( !this.checked ) {
					this.disabled = false;
				}
			});
		}
	});
	
	// make rank pull-downs disable items as selected
	$("select.rank").change(function(){
		var active = this;
		var value = this.value;
		if( value != "" ) {
			$("select.rank[@name='" + this.name + "']").each(function(){
				if( this !== active ) {
					$("option[@value='" + value + "']", this).remove();
				}
			});
		}
		$("option", this).each(function(){
			var opt = $(this);
			if( this.value != value ) {
				if( $("option[@value='" + this.value + "']", "select.rank[@name='" + active.name + "']").length == 1 ) {
					$("select.rank[@name='" + active.name + "']").each(function(){
						if( this !== active ) {
							var tmpVal = this.value;
							$(this).append(opt.clone(true));
							var sorted = $("option", this).slice(1).get().sort(function(a,b){
								if( a.value == "" ) {
									return false;
								}
								return parseInt(a.value) - parseInt(b.value);
							});
							$(this).html('<option value=""></option>');
							$(this).append(sorted);
							this.value = tmpVal;
						}
					});
				}
			}
		});
	});
	
	$("label.button input, label.button_sm input, label.smirk input, label.smile input, label.frown input, label.undecided_sm input, label.smile_sm input, label.frown_sm input").click(function(){
		if( this.checked ) {
			$(this).parent().addClass("active");
			$("input[@name='" + this.name + "']").each(function(){
				if( !this.checked ) {
					$(this).parent().removeClass("active");
				}
			});
		}
	});
	if( $.browser.msie ) {
		$("label.button, label.button_sm, label.smirk, label.smile, label.frown, label.undecided_sm, label.smile_sm, label.frown_sm").click(function(){
			field = $("input", this);
			field[0].checked = !field[0].checked
			field.click();
		});
	}
	
});
