var jInputObjs = null;
var jOtherObjs = null;
var jVdCdtnObjs = null;
var jRsObjs = null;
var jMustObjs = null;

$(function(){
	jInputObjs = $("input[type=text],input[type=radio],input[type=checkbox],textarea,select");

	jOtherObjs = jInputObjs.filter(".other")
					.parent().parent().find("input[type=radio],input[type=checkbox],select,input[type=text]"); // その他自由入力項目を含む選択項目
	jOtherObjs.click( function(){
		checkOther( $(this) );
	});
	$.each( jOtherObjs, function( idx ) {
		checkOther( $(this) );
	});

	jVdCdtnObjs = jInputObjs.filter( ".vdcdtn" ); // 条件により有効/無効が切り替わる項目
	jRsObjs = jInputObjs.filter( "[class*=rscode_]" ); // 条件を発動する項目
	jMustObjs = $("input[type=hidden][name=h_must_must]");
	jRsObjs.filter("input[type=radio],input[type=checkbox]").click( function(){
		checkVdcdtn( $(this), 0 );
	});
	$.each( jRsObjs.filter("input[type=radio],input[type=checkbox]"), function( idx ) {
		checkVdcdtn( $(this), 0 );
	});

	jRsObjs.filter("select").change( function(){
		checkVdcdtn( $(this), 1 );
	});
	$.each( jRsObjs.filter("select"), function( idx ) {
		checkVdcdtn( $(this), 1 );
	});

});

function checkOther( jThis ) {
	var nm = jThis.attr("name");

	var jIns = jOtherObjs.filter("input[name="+nm+"]")
	var jOther = jIns.filter(".other");
	var jOtherText = jIns.filter(".otherText");

	if( !jOther || jOther.length == 0 || !jOtherText || jOtherText.length == 0 ) {
		return;
	}

	if( jOther.attr("checked") ) {
		jOtherText.removeAttr("disabled");
		jOtherText.css("background-color","");
	}
	else {
//		jOtherText.val("");
		jOtherText.attr("disabled","true");
		jOtherText.css("background-color","lightgrey");
	}
}

function checkVdcdtn( jThis, type ) {
	$.each( jVdCdtnObjs, function( idx ) {
		var cdtns = $(this).attr( "vdcdtn" );
		if( cdtns ) {
			var keyValArr = cdtns.split("=");
			if( keyValArr.length > 1 ) {
				var key = keyValArr[0];
				var valArr = keyValArr[1].split(",");
				if( valArr ) {
					var isValid = false;
					for( var i=0; i<valArr.length; i++ ) {
						var jEle = jRsObjs.filter("[class*=rscode_"+key+"]");
						if( jEle.length > 0 ) {
							if( ( type == 0
								&& jEle.filter("[class*=rkcode_"+valArr[i]+"]").attr("checked") )
							||  ( type == 1
								&& jEle.find("[class*=rkcode_"+valArr[i]+"]").filter("option:selected").length > 0 )
							) {
								isValid = true;
								break;
							}
						}
					}

					if( isValid ) {
						if( !$(this).hasClass("otherText") ) {
							$(this).removeAttr("disabled");
							$(this).css("background-color","");
							jMustObjs.filter("[value="+$(this).attr("name")+"]").attr("name","h_must_must");
						}
					}
					else {
						$(this).attr("disabled","true");
						$(this).css("background-color","lightgrey");
						jMustObjs.filter("[value="+$(this).attr("name")+"]").attr("name","h_must_must_");
					}
				}
			}
		}
	});
}
