/************************************************************************************/
/* 旧 focusHilight.js の内容を移植 5.2.1.0 (2010/10/01)                             */
/*                                                                                  */
/* フォーカスが当っているアクティブフィールドの色を変更します                       */
/* 色はfocusFieldクラスで指定しています                                             */
/*                                                                                  */
/* @og.rev 4.3.5.0 (2009/02/01) JavaScript分離・イベントにJQuery利用                */
/* @og.rev 5.2.0.0 (2010/09/01) Javaスクリプトで登録したイベントを発動させる        */
/* @og.rev 5.5.9.0 (2010/12/03) IE9対応。selectはstyleを直接変更する                */
/* @og.rev 5.6.4.2 (2013/05/17) エラー表示の alertメッセージ修正                    */
/* Revision: $Id$                                                                   */
/************************************************************************************/

var orgFldCls = null;

$(function(){
	// 5.2.0.0 (2010/09/01) Javaスクリプトで登録したイベントを発動させる
//	$('textarea,select,input[type="text"]').focusin( function(){ doFocus2( this ); } );
//	$('textarea,select,input[type="text"]').focusout( function(){ doBlur2( this ); } );
	if(USE_FOCUS_HILIGHT){ //5.4.5.0 flag add
		setEvent( "textarea,select,input[type=\"text\"]", "focusin", function(){ doFocus2( this ); } );
		setEvent( "textarea,select,input[type=\"text\"]", "focusout", function(){ doBlur2( this ); } );
	}
});

function doFocus2( obj ) {
	// 入力中のフォームの色
	if( obj != null  ) { 
		if( obj.className == null || obj.className.indexOf( "must" ) < 0 ) {
			// 4.3.2.2 (2008/09/16) 入力中のフォームの色をcustom.cssに指定するように変更
			// 5.5.9.0 (2012/12/03) selectタグの場合は直接背景色変更 
			if( obj.tagName == "SELECT" ){ // 5.5.9.1(2012/12/07) 小文字を大文字に
				obj.orgBgColor    = obj.style.backgroundColor;
				obj.style.backgroundColor = '#ffcccc';
			}
			else{
				orgFldCls    = obj.className;
				obj.className = 'focusField ' + orgFldCls;
			}
		}
	}
}

function doBlur2( obj ) {
	if( obj != null ) {
		if( obj.className == null || obj.className.indexOf( "must" ) < 0 ) {
			// 元のフォームの色
			// 5.5.9.0 (2012/12/03) selectタグの場合は直接背景色変更
			if( obj.tagName == "SELECT" ){
				obj.style.backgroundColor = obj.orgBgColor;
			}
			else{
				if( orgFldCls != null ) {
					obj.className = orgFldCls;
				}
				else {
					obj.className = 'notFocusField';
				}
			}
		}
	}
}

/* 旧関数を呼び出した場合はアラートを出す（旧の*_inof.jsp対策） */
oldDoFocusFlag = true;
function doFocus( obj ) {
	if(oldDoFocusFlag){
		oldDoFocusFlag = false;
//		setTimeout(alert("custom/query_info.jsp及びcustom/result_info.jspで次の部分を削除して下さい。\n<script>タグ（ヘッダ固定とフォーカス）、BODYのonLoadとoncontextmenu属性"),100);
		setTimeout(alert("Old Script Error!!\ncustom/query_info.jsp,custom/result_info.jsp Please delete the following part.\n<script>Tag(Header fix and Focus) , BODY onLoad and oncontextmenu Attribute"),100);
	}
}
/*エラー対策の空関数 */
function doBlur( obj ) {}

/************************************************************************************/
/* 旧 autoConvert.js の内容を移植 5.2.1.0 (2010/10/01)                              */
/*                                                                                  */
/* 入力値自動変換機能 4.3.0.0 (2008/07/25) 追加                                     */
/* dbType XL及びXUについて、大文字・小文字の自動変換を行います                      */
/*                                                                                  */
/* @og.rev 4.3.5.0 (2009/02/01) JavaScript分離(inputFocusより)                      */
/* @og.rev 5.2.0.0 (2010/09/01) Javaスクリプトで登録したイベントを発動させる        */
/* @og.rev 5.9.5.0 (2016/02/05) PN2も大文字化の対象とする					        */
/* Revision: $Id$                                                                   */
/************************************************************************************/
$(function(){
	// 5.2.0.0 (2010/09/01) Javaスクリプトで登録したイベントを発動させる
//	$('textarea,select,input[type="text"]').focusout( function(){ convert( this ); } );
	setEvent( "textarea,select,input[type=\"text\"]", "focusout", function(){ convert( this ); } );
});

function convert( obj ) {
	var val , cls ;

	val = obj.value;
	cls = obj.className;
	if( val != null && cls != null ) {
		if( cls.match( /XL/ ) && !(cls.match( /XLU/ )) ) {
			obj.value = val.toLowerCase();
		}
//		else if( cls.match( /XU/ ) && !(cls.match( /XUL/ )) ) {
		else if( (cls.match( /XU/ ) && !(cls.match( /XUL/ ))) || cls.match( /PN2/ ) ) { // 5.9.5.0
			obj.value = val.toUpperCase();
		}
	}
	return true;
}

/************************************************************************************/
/* 旧 eventColumn.js の内容を移植 5.2.1.0 (2010/10/01)                              */
/*                                                                                  */
/* 動的プルダウンを実行するためのJavaScriptです。                                   */
/*                                                                                  */
/* @og.rev 5.2.0.0 (2010/09/01) Javaスクリプトで登録したイベントを発動させる        */
/* Revision: $Id$                                                                   */
/************************************************************************************/
var colMap;
var notFireCols;
var jH_evElm;

$(function(){
	if( ! ( typeof( EC_NAME ) == "undefined" ) ) {
		// 初期化処理だけは、予め要素オブジェクトを取得しておき、ここから子カラムを取得する。
		jH_evElm = $( ".h_evElm" );

		makeColMapping();

		setEvent( "textarea,select,input[type=\"text\"]", "change", function(){ makeColumn( this ); }, ".h_evCol", true, addEvColCls );
		setEvent( "input[type=checkbox],input[type=radio]", "click", function(){ makeColumn( this ); }, ".h_evCol", true );
	}
});

/**
 * 親カラムをキーにしたイベントカラムの一覧を作成します。
 *
 * 親カラムを連想配列のキーとして、子カラムの一覧を配列として保持します。
 *
 * @og.rev 5.2.0.0 (2010/09/01) 新規作成
 *
**/
function makeColMapping() {
	var i , j , evCols , evc , cCols ;

	if( colMap ){ return; }

	colMap = new Object();
	for(  i=0; i<EC_EVCOL.length; i++ ) {
		evCols = EC_EVCOL[i].split(",");
		for( j=0; j<evCols.length; j++ ) {
			evc = evCols[j];
			if( evc.charAt(0) == "_" ) {
				evc = evc.substring(1);
				if( notFireCols ) { notFireCols += ","; }
				notFireCols += evc;
			}
			cCols = colMap[evc];
			if( !cCols ) { cCols = new Array(); }
			cCols[cCols.length] = EC_NAME[i];
			colMap[evc] = cCols;
		}
	}
}

/**
 * 親カラムに対してクラスを付加します。
 *
 * @og.rev 5.2.0.0 (2010/09/01) 新規作成
 *
**/
function addEvColCls() {
	for( var evCol in colMap ) {
		$("#"+evCol+",[id^="+evCol+"__]").addClass("h_evCol");
	}
}

/**
 * イベントカラムが設定されたタグ(spanタグ)を検索し、親カラムにイベントを登録します。
 *
 * @og.rev 5.1.7.0 (2010/06/01) 新規作成(動的プルダウン実装見直し)
 *
 * @param evCol	イベントが発生した親カラムのオブジェクト
**/
function makeColumn( evCol ) {
	var jEvCol , evColId , evColName , cColNameArr , i , suffix , cid , cname , jTag , writable ;

	if( jH_evElm && isEndInitEvent() ) { jH_evElm = null; }

	jEvCol = $( evCol );
	evColId = jEvCol.attr("id");
	evColName = evColId.split("__")[0];

	cColNameArr = colMap[evColName];
	if( !cColNameArr ) { return; }

	// イベントカラムでカラム名の頭文字が'_'で始まっている場合、初回イベント発行を行わない。
	if( !isEndInitEvent() && notFireCols && notFireCols.indexOf( evColName ) >= 0 ) { return; }

	for( i=0; i<cColNameArr.length; i++ ) {
		suffix = ( evColId == evColName ? "" : "__" + evColId.split("__")[1] );
		cid = cColNameArr[i]+suffix;
		cname = cid.split("__")[0];
		jTag = isEndInitEvent() ? $( ".h_evElm[h_evCid="+cid+"]" ) : jH_evElm.filter( "[h_evCid="+cid+"]" );
		writable = jTag.attr("h_evWrtbl");
		eventColumn( jEvCol, jTag, cid, cname, suffix, writable );
	}
}

/**
 * Ajax動的カラム変更用の共通JavaScript
 * 
 * カラムにeventColumnをセットした時に親側にID指定でChangeイベントとして登録されます。
 * ※イベント処理用のJSP用に送られるパラメーターに関しては、jsp/common/eventColumnMaker.jspの
 *   コメントを参照して下さい。
 *
 * @og.rev 5.1.7.0 (2010/06/01) 動的プルダウン実装見直し
 * @og.rev 5.5.4.0 (2012/07/02) suffixが存在すればSLABEL利用を標準にする。eventCallbackの動作追加
 * @og.rev 5.6.2.0 (2013/03/01) jQueryのval()がリセット後のプルダウンから取得できないのでvlaueで取る
 * @og.rev 5.6.4.2 (2013/05/17) エラー表示の alertメッセージに、発生元が分かるように、 cname を追加します。
 * @og.rev 5.9.4.6 (2016/01/29) multiple対応
 *
 * @param jEvCol	イベントが発生した親カラムのjQueryオブジェクト
 * @param jTag		置き換え要素をラップしたspanタグのjQueryオブジェクト
 * @param cid		変更対象の子要素(inputタグなど)のID
 * @param cname		子のカラム名
 * @param suffix	__ + 行番号(一覧表示の場合のみ)
 * @param writable	書き込み可能かどうか
**/
function eventColumn( jEvCol, jTag, cid, cname, suffix, writable ){
	var evVal , url , param , _pos1 , _pos2 , _repClm, _rep, _clm , noVal , columnFocus , jCol , val , renderer , editor , ATTRS , optAttrs , i , optAtt , vtype , isAdd ;
	var callback; // 5.5.4.0 (2012/07/02)
	
	if( !jTag || jTag.length == 0 ) {
//		alert( "[SYSTEM_ERROR] : イベントカラムで置き換え対象の要素が存在しません" );
		alert( "[SYSTEM_ERROR] : jTag is null. The element of the replacement object doesn't exist. [" + cname + "]" );		// 5.6.4.2 (2013/05/17) cname 追加
		return;
	}

//	if( cid == null || cid == "" || cname == null || cname == "" ) {
//		alert( "[SYSTEM_ERROR] : 子要素のIDまたはNAMEがセットされていません" );
//		return;
//	}

	if( !isEndInitEvent() ) {
//		evVal = jEvCol.val();
		evVal = jEvCol.get(0).value; //2013/03/01
		if( !evVal || evVal == null || evVal == "" ) { return; }
	}

	try {
		url = eval( "EC_" + cname + "_URL" );
	}
	catch( e ) {
//		alert( "[SYSTEM_ERROR] : イベントを処理するURLが指定されていません。(変数未定義)" );
		alert( "[SYSTEM_ERROR] : URL that processes the event is not specified. (variable undefinition). [" + cname + "]" );		// 5.6.4.2 (2013/05/17) cname 追加
		return;
	}
	if( !url || url == "" ) {
//		alert( "[SYSTEM_ERROR] : イベントを処理するURLが指定されていません。" );
		alert( "[SYSTEM_ERROR] : URL that processes the event is not specified. [" + cname + "]" );		// 5.6.4.2 (2013/05/17) cname 追加
		return;
	}

	// SQL文をパースして{@xxx}をxxxのvalue値に変更する。一覧での利用では同一行のカラムになる。
	//（リクエスト変数はテキストボックスで一度受ける必要がある）
	// 又、パースして得られたvalue値をJSPのリクエスト変数としてURLの後ろに付ける
	param = "";
	try { param = ( writable ? eval( "EC_" + cname + "_EDITPARAM" ) : eval( "EC_" + cname + "_RENDPARAM" ) ); } catch( e ) {}
	if( param != null && param != "" ) {
		url += "?";
		_pos1 = 0;
		_pos2 = 0;
		while( (_pos1 = param.indexOf("{@",_pos2)) != -1){
			_pos2 = param.indexOf("}",_pos1);
			_clm = param.substring(_pos1+2,_pos2);
			if( _clm.indexOf(".") < 0 ) {
				_repClm = "{@"+_clm+"}";
//				_rep = suffix == "" ? $('#'+_clm).val() : $('#'+_clm+suffix).val();
				_rep = suffix == "" ? $('#'+_clm).get(0).value : $('#'+_clm+suffix).get(0).value;  // 2013/03/01
				_rep = ( _rep == null ? "" : _rep );
				param = param.replace(_repClm,_rep);
				url += _clm + "=" +  encodeURIComponent(_rep) +"&";
			}
			_pos2 = _pos1+1; // 4.3.6.2 (2009/04/15)
		}
	}

	// 子がSelectタグの場合、最上部に空のoptionが存在すればEC_NOVALUEをtrueで送る
	noVal = function(){
		_firstOption = jCol.children('option').get(0);
		if( _firstOption == null || _firstOption.value != "" ){ return false; }
		return true;
	};

	// 4.3.6.5 (2009/05/08) must,mustAnyを引数でJSPに送る。
//	var mustOrMustAny = function(){
//		var _haveClasses = jCol.attr("class");
//		if( _haveClasses && _haveClasses.indexOf("must") >= 0 ){
//			if( _haveClasses.indexOf("mustAny") >= 0 )	{ return "mustAny"; }
//			else										{ return "must"; }
//			return "";
//		}
//	}

	columnFocus = function() {
		jCol.attr("isfocus","true");
	};

//	var jCol;
	if( cid != null && cid != "" ) {
		jCol = jTag.find( "#"+cid );
	}
	else {
		jCol = new Array(0);
	}

	if( jCol.length > 0 && isEndInitEvent() ) {
		jCol.bind("focus",columnFocus);
	}

	val = "";
	if( jCol.length > 0 ) {
		if( isEndInitEvent() )	{ val = ( jCol.val() == null ? "" : jCol.val() ); }
		else					{ val = ( jTag.attr( "h_evVal" ) == null ? "" : jTag.attr( "h_evVal" ) ); }
	}

	renderer = "";
	try { renderer = eval( "EC_" + cname + "_RENDERER" ); } catch( e ) {}

	editor = "";
	try { editor = eval( "EC_" + cname + "_EDITOR" ); } catch( e ) {}

	// 5.2.0.0 (2010/09/01) 属性値が正しく引き継がれないバグを修正
	ATTRS = [ "title", "style", "tabindex", "readonly", "disabled"
				, "onClick", "onChange", "onBlur", "onFocus", "ondblClick", "onMouseDown", "onMouseUp"
				, "onMouseMove", "onMouseOut", "onMouseOver", "onSelect", "onKeydown", "onKeypress", "onKeyup"
				, "eventCallBack" // 5.5.4.0 (2012/07/02)
				, "multiple" // 5.9.4.5 (2016/01/29)
			 ];
	optAttrs = "";
	if( jCol.length > 0 ) {
		for( i=0; i<ATTRS.length; i++ ) {
			optAtt = jCol.attr(ATTRS[i]);
			if( optAtt != null ) {
				vtype = typeof( optAtt );
				isAdd = false;
				if( vtype == "function" ) {
					optAtt = optAtt.toString();
					isAdd = optAtt.length > 0 ? true : false;
					// 関数の場合は、文字列表現として"function anonymous(){...}"という関数定義が返るため、
					// ( FUNCTION )(); 形式で関数を実行するように変更
					optAtt = "(" + optAtt + ")()";
				}
				else if( vtype == "boolean" ) {
					isAdd = optAtt;
				}
				else {
					isAdd = optAtt.length > 0 ? true : false;
				}

				if( isAdd ) {
					optAttrs += ATTRS[i] + "='" + optAtt + "' ";
				}
			}
		}
	}

	// JSPを呼び出して処理する
	$.ajax({
		url: url,
		data: {
			"EC_CID"		: ( cid == null ? "" : cid ),
			"EC_CNAME"		: ( cname == null ? "" : cname ),
			"EC_RENDERER"	:renderer,
			"EC_EDITOR"		: editor,
			"EC_PARAM"		: param,
			"EC_SQL"		: param,
			"EC_WRITABLE"	: ( writable == null ? "" : writable ),
			"EC_CVALUE"		: val,
			"EC_NOVALUE"	: ( jCol.length == 0 ? "" : noVal() ),
//			"EC_MUST"		: ( jCol.length == 0 ? "" : mustOrMustAny() ),
			"EC_CLASS"		: ( jCol.length == 0 ? "" : jCol.attr("class") ),
			"EC_SIZE"		: ( jCol.length == 0 ? "" : jCol.attr("size") ),
			"EC_MAXLENGTH"	: ( jCol.length == 0 ? "" : jCol.attr("maxlength") ),
			"EC_OPTATTRS"	: optAttrs,
			"EC_PNAME"		: jEvCol.attr("id") == null ? "" : jEvCol.attr("id").split("__")[0],
//			"EC_PVALUE"		: jEvCol.val() == null ? "" : jEvCol.val(),
			"EC_PVALUE"		: jEvCol.get(0).value == null ? "" : jEvCol.get(0).value, // 5.6.2.0 (2013/03/01)
			"EC_USESLBL"	: (suffix == null || suffix == "") ? "false" : "true" // 5.5.4.0 (2012/07/02)
		},
		type: 'POST',
		dataType: 'html',
		async : isEndInitEvent(),
		error: function(r,s,e){
			// 5.6.4.2 (2013/05/17) 紙芝居作成時は、url が存在しないエラーが発生するので、無視する。(htm呼び出し時は無視)
			if( url.indexOf( ".htm" ) < 0 ) {
				alert('EventColumnError:'+r+':'+s+':'+e+':'+cname);
			}
		},
		success: function(data,status){
			var jNewCol = $(data);

			if( jCol.length > 0 ) {
				if( isEndInitEvent() ) {
					jCol.unbind("focus",columnFocus);
				}
				bindOldEvents( jNewCol.get(0), jQuery.data( jCol.clone(true).get(0),"events" ) );
			}

			jTag.empty().append( jNewCol );

			if( jCol.length > 0 ) {
				jTag.find("input,select,textarea").attr( "name", cid ).attr( "id", cid );

				if( isEndInitEvent() ) {
					// 置き換え先の要素にフォーカスが当たっていた場合は、フォーカスを復活
					if( jCol.attr("isfocus") ) {
//						jNewCol.focus();
						jNewCol.get(0).focus();
						// IEの場合、置き換え先の要素がテキストボックスの場合は、もう１度フォーカスする必要がある。
						if( $.browser.msie ) {
							jNewCol.get(0).focus();
						}
					}
				}
				// 初回読み込み時に置き換えられた要素はchangeイベントを発行
				if( !isEndInitEvent() ) {
					jNewCol.change();
				}
				// 5.5.4.0 (2012/07/02) callBack処理
				// 置き換え先にeventCallback属性が存在した場合にevalして関数評価した上で、子idと値を引数に渡す。
				if( jCol.attr("eventCallback") ){
					callback = function(){ eval(jCol.attr("eventCallback") + "(arguments);") };
//					callback(cid,jNewCol.val(),jCol.val());
					callback(cid,jNewCol.val(),jCol.get(0).value); // 2013/03/01
				}
			}

			// ヘッダー固定再計算
			if( suffix != null && suffix != "" ) {
				if( isEndInitEvent() ) {
					$('table#viewTable').resizeView();
				}
			}
		}
	});
}

function bindOldEvents( newCol, oldEvents ) {
	var type , handler ;
	for ( type in oldEvents ) {
		for ( handler in oldEvents[type] ) {
			jQuery.event.add( newCol, type, oldEvents[type][handler], oldEvents[type][handler].data );
		}
	}
}

/********************************************************************************************/
/* 旧 TimeCheck.js の内容を移植 5.2.1.0 (2010/10/01)                                    */
/*                                                                                          */
/* 入力欄の簡易チェック(リアルタイム)                                                       */
/* DBTYPE に応じた簡易チェックを行います。あくまで簡易的なチェックです。                    */
/* 大文字小文字などは、JavaScriptで変換できる為、チェックは行いません。                     */
/*                                                                                          */
/* @og.rev 4.3.3.0 (2008/10/01) サーバーサイドのリアルタイムチェック対応                    */
/* @og.rev 4.3.5.0 (2009/02/01) JavaScript分離(inputFocusより)								*/
/* @og.rev 4.3.6.6 (2009/05/15) bodyに追加し、いつも上に表示                                */
/* @og.rev 5.2.0.0 (2010/09/01) ヘッダー固定でスクロールした場合は、エラーメッセージを消す。*/
/* @og.rev 5.2.0.0 (2010/09/01) Javaスクリプトで登録したイベントを発動させる                */
/* @og.rev 5.2.1.0 (2010/10/01) h_ で始まる内部設定フィールドはチェックしない。             */
/* @og.rev 5.3.7.0 (2011/07/01) 入力項目が上方にある場合は、下にチェックチップを表示する。  */
/* @og.rev 5.4.4.0 (2012/02/01) rtOption対応												*/
/* @og.rev 5.9.0.0 (2015/09/04)  ../common/*** の相対パスを絶対パスに変更(6.3.6.1)			*/
/* Revision: $Id$                                                                           */
/********************************************************************************************/
var isShowTip = false;

$(function(){
	// 5.2.0.0 (2010/09/01) Javaスクリプトで登録したイベントを発動させる
//	$('textarea,select,input[type="text"]').focusout( function(){ check( this, '../common/realtimecheck.jsp' ); } );
	if(USE_REAL_TIME_CHECK){ //5.4.5.0 flag add
//		setEvent( "textarea,select,input[type=\"text\"]", "focusout", function(){ check( this, '../common/realtimecheck.jsp' ); } );
		setEvent( "textarea,select,input[type=\"text\"]" , "focusout" ,
					// 6.3.6.1 (2015/08/28) ../common/*** の相対パスを絶対パスに変更
//					function(){ check( this, '../common/realtimecheck.jsp' ); } );
					function(){
						var obj=RegExp( /jsp/ );
						var tmp = location.pathname.match( obj );
						// RegExp.leftContext : 最期に一致した文字列より前の文字列を取得(/gf/)
						check( this, RegExp.leftContext + 'jsp/common/realtimecheck.jsp' );
					} );

		// 5.2.0.0 (2010/09/01) ヘッダー固定でスクロールした場合は、エラーメッセージを消す。
		$('table#viewTable').parent().parent().scroll( function () {
			if( isShowTip ) { isShowTip = false; $(".tipErr").remove(); }
		});
	}
});

function check( obj, sUrl ) {
	var sFullFN , val , arrFName , bTMCheck , sParam , ajaxSettings , tipId, rtoption ;

	sFullFN = obj.name;
//	var cls = obj.className;
//	var msg = null;

	if (typeof jQuery != "undefined" && sFullFN.indexOf( "h_" ) != 0 ) {
		val = obj.value;
		if( obj.rtOption != "null" && obj.rtOption != "undefined"){
			rtoption = obj.rtOption; // 5.4.4.0
		}
		arrFName = sFullFN.split('__');
		bTMCheck = (2 == arrFName.length);
//		var sParam = "command=RTCHECK&checkType=" + ( bTMCheck ? "ENTRY" : "NEW" );
		sParam = "command=RENEW&checkType=" + ( bTMCheck ? "ENTRY" : "NEW" ) // 4.3.4.0 (2008/12/01)
				   + ( bTMCheck ? "&h_rowSel=" + arrFName[1] : "" )
//				   + "&column=" + arrFName[0] + "&" + sFullFN + "=" + val;
//				   + "&column=" + arrFName[0] + "&" + sFullFN + "=" + encodeURI( val ); // 4.3.4.0 (2008/12/01)
				   + "&column=" + arrFName[0] + "&" + sFullFN + "=" + encodeURIComponent( val ) // 5.2.0.0 (2010/09/01)
				   + (rtoption ? "&" + rtoption : ""); // 5.4.4.0 (2012/02/01)
		ajaxSettings = {   
				dataType : 'html',
				type	 : 'POST',
				url		 : sUrl,
				data	 : sParam
		};

		ajaxSettings.error = function() {};
		ajaxSettings.success = function(data) {
			//Remove old msg
//			var sOutId = getTipId(obj);
//			$("#" + sOutId).remove();
			tipId = $(obj).data( "tipId" );
			$("#" + tipId).remove();

			if( $.trim(data).indexOf("row_error") >= 0 ) {
				showCheckTip( obj, data );
				isShowTip = true;
			}
		};
		$.ajax(ajaxSettings);
	}

	return true;
}

/* Revised From jTip Plug-in of jQuery */
function showCheckTip( oEditOut, content ) {
//	var jEditOut , hEditOffset , sJtDiv , jJtDiv , clickElementx , clickElementy , tipId ;
	var jEditOut , hEditOffset , iTipOffset , sArrowId , sJtDiv , jJtDiv , clickElementx , clickElementy , tipId ;

	jEditOut = $(oEditOut);
	hEditOffset = jEditOut.offset();

	// 5.3.7.0 (2011/07/01) 上に表示する場合
	if( hEditOffset.top >= 30 ) {
		sJtDiv = "<div class='tipErr'><div id='tipArrowBottom'></div><div>" + content + "</div></div>";
		jJtDiv = $(sJtDiv).appendTo(document.body);
		//set x position
		clickElementx = hEditOffset.left;
		//set y position
		clickElementy = hEditOffset.top + (-11 - jJtDiv[0].offsetHeight);
	}
	// 5.3.7.0 (2011/07/01) 下に表示する場合
	else {
		sJtDiv = "<div class='tipErr'><div id='tipArrowTop'></div><div>" + content + "</div></div>";
		jJtDiv = $(sJtDiv).appendTo(document.body);
		//set x position
		clickElementx = hEditOffset.left;
		//set y position
		clickElementy = hEditOffset.top + 11 + jJtDiv[0].offsetHeight;
	}

	tipId = (new Date()).getTime();
	$(oEditOut).data( "tipId", tipId );

	jJtDiv.css( { left: clickElementx+"px", top: clickElementy+"px" } )
			.attr( 'id', tipId )
			.click( function() { $(this).remove(); } )
			.show();
}

//function getTipId(oEdit) {
//	return "JT" + $.data(oEdit);
//}

/********************************************************************************************/
/* 旧 bindEvents.js の内容を移植 5.2.1.0 (2010/10/01)                                       */
/*                                                                                          */
/* 各JavaScriptで登録されたイベント(主にカラムに割り当てられたイベント)を                   */
/* 実際のイベントハンドラにバインドします。                                                 */
/*                                                                                          */
/* @og.rev 5.2.0.0 (2010/09/01) 新規作成                                                    */
/* Revision: $Id$                                                                           */
/********************************************************************************************/
$(function(){
	bindEvents();
});


/********************************************************************************************/
/* カラーピッカー 5.5.4.0 (2012/07/02)                                                      */
/*                                                                                          */
/* カラーピッカーです。                                                                     */
/* input.colorPickerに対して実行させます                                                    */
/*                                                                                          */
/* @og.rev 5.5.4.0 (2012/07/02) 新規作成                                                    */
/* @og.rev 5.5.6.1 (2013/01/11) 名称変更(Og付加)                                            */
/* @og.rev 5.9.4.0 (2016/01/08) clear対応                                                   */
/* @og.rev 5.9.8.3 (2016/05/20) bulk対応													*/
/* Revision: $Id$                                                                           */
/********************************************************************************************/
$.fn.simpleColorPickerOg = function(options) {
    var defaults = {
        colorsPerLine: 8,
        colors: ['#000000', '#444444', '#666666', '#999999', '#cccccc', '#eeeeee', '#f3f3f3', '#ffffff'
				, '#ff0000', '#ff9900', '#ffff00', '#00ff00', '#00ffff', '#0000ff', '#9900ff', '#ff00ff'
				, '#f4cccc', '#fce5cd', '#fff2cc', '#d9ead3', '#d0e0e3', '#cfe2f3', '#d9d2e9', '#ead1dc'
				, '#ea9999', '#f9cb9c', '#ffe599', '#b6d7a8', '#a2c4c9', '#9fc5e8', '#b4a7d6', '#d5a6bd'
				, '#e06666', '#f6b26b', '#ffd966', '#93c47d', '#76a5af', '#6fa8dc', '#8e7cc3', '#c27ba0'
				, '#cc0000', '#e69138', '#f1c232', '#6aa84f', '#45818e', '#3d85c6', '#674ea7', '#a64d79'
				, '#990000', '#b45f06', '#bf9000', '#38761d', '#134f5c', '#0b5394', '#351c75', '#741b47'
				, '#660000', '#783f04', '#7f6000', '#274e13', '#0c343d', '#073763', '#20124d', '#4C1130'],
        showEffect: '',
        hideEffect: '',
        onChangeColor: false
    };

    var opts = $.extend(defaults, options);

    return this.each(function() {
        var txt = $(this);

        var colorsMarkup = '';

        var prefix = txt.attr('id').replace(/-/g, '') + '_';

        for(var i = 0; i < opts.colors.length; i++){
            var item = opts.colors[i];

            var breakLine = '';
            if (i % opts.colorsPerLine == 0)
                breakLine = 'clear: both; ';

            if (i > 0 && breakLine && $.browser && $.browser.msie && $.browser.version <= 7) {
                breakLine = '';
                colorsMarkup += '<li style="float: none; clear: both; overflow: hidden; background-color: #fff; display: block; height: 1px; line-height: 1px; font-size: 1px; margin-bottom: -2px;"></li>';
            }

            colorsMarkup += '<li id="' + prefix + 'color-' + i + '" class="color-box" style="' + breakLine + 'background-color: ' + item + '" title="' + item + '"></li>';
        }
        breakLine = 'clear: both; ';
        // 5.9.4.0  clear
        colorsMarkup += '<li id="' + prefix + 'color-default' + '" class="color-box" style="width:80px; text-align:center; ' + breakLine +  'background-color:white;" title="clear">clear</li>';


        var box = $('<div id="' + prefix + 'color-picker" class="color-picker" style="position: absolute; left: 0px; top: 0px;"><ul>' + colorsMarkup + '</ul><div style="clear: both;"></div></div>');
        
        $('body').append(box);
        box.hide();

        box.find('li.color-box').click(function() {
        	var sel_val = isNaN(this.id.substr(this.id.indexOf('-') + 1)) ? "": opts.colors[this.id.substr(this.id.indexOf('-') + 1)]; // 5.9.4.0

            if (!txt.is('input')) {
//            txt.val(opts.colors[this.id.substr(this.id.indexOf('-') + 1)]);
              txt.val(sel_val);
              txt.blur();
            }
            if ($.isFunction(defaults.onChangeColor)) {
//            defaults.onChangeColor.call(txt, opts.colors[this.id.substr(this.id.indexOf('-') + 1)]);
              defaults.onChangeColor.call(txt, sel_val);
            }
            hideBox(box);
        });

        $('body').live('click', function() {
            hideBox(box);
        });

        box.click(function(event) {
            event.stopPropagation();
        });

        var positionAndShowBox = function(box) {
          var pos = txt.offset();
          var left = pos.left + txt.outerWidth() - box.outerWidth();
          if (left < pos.left) left = pos.left;
          box.css({ left: left, top: (pos.top + txt.outerHeight()) });
          showBox(box);
        }

        txt.click(function(event) {
          txt = $(this); // 5.9.8.3 (2016/05/20) クリックした際にthisを再セットする（Bulk対応）
          event.stopPropagation();
          if (!txt.is('input')) {
            // element is not an input so probably a link or div which requires the color box to be shown
            positionAndShowBox(box);
          }
        });

		// 5.9.8.3 (2016/05/20) 外部から変更された場合に、色を変更する。
        txt.change( function(event){
          if( txt.val() != txt.css('background-color')){
	          txt.css('background-color', txt.val()) .css('color',txt.val());
	        }
        });

        txt.focus(function() {
          positionAndShowBox(box);
        });

        function hideBox(box) {
            if (opts.hideEffect == 'fade')
                box.fadeOut();
            else if (opts.hideEffect == 'slide')
                box.slideUp();
            else
                box.hide();
        }

        function showBox(box) {
            if (opts.showEffect == 'fade')
                box.fadeIn();
            else if (opts.showEffect == 'slide')
                box.slideDown();
            else
                box.show();
        }
    });
};

// カラーピッカーの対象はinput.colorPicker
$(function(){
	// 5.5.6.1 (2013/01/11) jQueryの上書き時エラー対策にif文挿入（上書きされると動作しない）
	// 5.9.4.0 (2016/01/08) backgroundではなくbackground-colorにする
	// 5.9.8.3 (2016/05/20) change追加
	if($.fn.simpleColorPickerOg){
//		$('input.colorPicker').simpleColorPickerOg({ onChangeColor: function(color) { $(this).val(color).css('background-color', color) .css('color',color); } });
		$('input.colorPicker').simpleColorPickerOg({ onChangeColor: function(color) { $(this).val(color).css('background-color', color) .css('color',color).change(); } });
	}
});

/********************************************************************************************
時間ピッカー 5.6.5.2 (2013/06/21)  
ClockPick, by Josh Nathanson 
Version 1.2.9 and Masakazu Takahasi Modified
Complete documentation at http://www.jnathanson.com/index.cfm?page=jquery/clockpick/ClockPick

以下を、対象タグの属性値から取得可能なように改造
param	 options[starthour]       int                     starting hour (use military int)
param	 options[endhour]         int                     ending hour (use military int)
param 	 options[minutedivisions] int                     number of divisions, i.e. 4 = :00, :15, :30, :45
param 	 options[military]        string                  use 24hr time if true(true/false)
param	 options[valuefield]      string                  field to insert time value, if not same as click field(name of input field)
param	 options[showminutes]     bool                    show minutes
                                  
又、対象単位に設定値を持てるように対応。
@og.rev 5.9.8.3 (2016/05/20) 標準をAMPMではなく24時間表記に変更、ピッカー選択時にchangeイベント発生させる
********************************************************************************************/

jQuery.fn.ogClockpicker = function(options, callback) {

	var org_settings = {
		starthour       : 6,
		endhour         : 20,
		showminutes     : "true",
		minutedivisions : 4,
		military        : true,
		event           : 'click',
		layout			: 'vertical',
		valuefield		: null,
		useBgiframe		: false,
		hoursopacity	: 1,
		minutesopacity  : 1
		};
		
	if(options) {
		jQuery.extend(org_settings, options);
	};
	
	var callback = callback || function() { },
	 	v = (org_settings.layout == 'vertical'); // boolean for vertical, shorten footprint
	errorcheck(org_settings);	


	jQuery(this)[org_settings.event](function(e) {
		var self = this,
		$self = jQuery( this ),
		$body = jQuery( "body" );
		var settings = jQuery.extend(true,{},org_settings); // OpenGion deep copy

		// OpenGion 属性対応
		if( $self.attr('valuefield') ){
			settings.valuefield = $self.attr('valuefield');
		}
		if( $self.attr('starthour') ){
			settings.starthour = $self.attr('starthour');
		}
		if( $self.attr('endhour') ){
			settings.endhour = $self.attr('endhour');
		}
		if( $self.attr('minutedivisions') ){
			settings.minutedivisions = $self.attr('minutedivisions');
		}
		if( $self.attr('military') ){
			settings.military = $self.attr('military');
		}
		if( $self.attr('showminutes') ){
			settings.showminutes = $self.attr('showminutes');
		}
		
		errorcheck(settings);


		
		if ( !settings.valuefield ) {
			$self.unbind( "keydown" ).bind( "keydown", keyhandler );
			
		}
		else {
			var inputfield = jQuery("[name=" + settings.valuefield + "]");
			inputfield
				.unbind( "keydown" )
				.bind( "keydown", keyhandler)[0]
				.focus();
			inputfield
				.bind("click", function() { inputfield.unbind("keydown"); } );										
		}
		// clear any malingerers
		jQuery("#CP_hourcont,#CP_minutecont").remove();
		
		// append hourcont to body
		// add class "CP" for mouseout recognition, although there is only
		// one hourcont on the screen at a time
		var $hourcont = jQuery("<div id='CP_hourcont' class='CP' />").appendTo( $body );
		!settings.useBgiframe ? $hourcont.css("opacity",settings.hoursopacity) : null;
		binder( $hourcont );
		
		var $hourcol1 = jQuery("<div class='CP_hourcol' id='hourcol1' />").appendTo( $body );
		var $hourcol2 = jQuery("<div class='CP_hourcol' id='hourcol2' />").appendTo( $body );

		// if showminutes, append minutes cont to body

		if (settings.showminutes == "true") {
			var $mc = jQuery("<div id='CP_minutecont' class='CP' />").appendTo( $body );
			!settings.useBgiframe ? $mc.css("opacity",settings.minutesopacity) : null;
			binder($mc);
		}
		if ( !v ) {
			$hourcont.css("width","auto");
			if (settings.showminutes == "true") {
				$mc.css("width","auto");
			}
		}
		else {
			$hourcol1.addClass('floatleft');
			$hourcol2.addClass('floatleft');
		}
				
		// all the action right here
		// fill in the hours container (minutes rendered in hour mouseover)
		// then make hour container visible
		renderhours();
		putcontainer();
		
		/*----------------------helper functions below-------------------------*/
				
		function renderhours() {
			// fill in the $hourcont div
			var c = 1; 
			// counter as index 2 of hr id, gives us index 
			// in group of hourdivs for calculating where to put minutecont on keydown
			for (var h=settings.starthour; h<=settings.endhour; h++) {
				
				if(h==12) { c = 1; } // reset counter for col 2
				
				var displayhours = ((!settings.military && h > 12) ? h - 12 : h);
				var valuehouers = h; // opengion
				// rectify zero hour
				if (!settings.military && h == 0) {
					//displayhours = '12'; // 日本向けに0時で表示
				}
				else if (!settings.military && h == 12) {
					displayhours = '0'; // 日本向けに0時で表示
				}
				if ( settings.military && h < 10 ) {
					displayhours = '0' + displayhours;
				}
				if ( h < 10 ){
					valuehouers = '0'+valuehouers;
				}
			
				var $hd = jQuery("<div class='CP_hour' id='hr_" + h + "_" + c + "' " + "value='" +valuehouers+ "' >" + displayhours + set_tt(h) + "</div>");
				// shrink width a bit if military
				if (settings.military) { $hd.width(20); }
				binder($hd);
				if (!v) {
					$hd.css("float","left");
				}
				(h<12) ? $hourcol1.append($hd) : $hourcol2.append($hd);
				c++;
			}
			$hourcont.append($hourcol1);
			!v ? $hourcont.append("<div style='clear:left' />") : '';
			$hourcont.append($hourcol2);
		}
		
		function renderminutes( h ) {
			var realhours = h;
			var displayhours = (!settings.military && h > 12) ? h - 12 : h;
			var valuehouers = h; // opengion
			if (!settings.military && h == 0) {
				//displayhours = '12'; // 日本向けに0時で表示
			}
			else if (!settings.military && h == 12) {
				displayhours = '0'; // 日本向けに0時で表示
			}
			if ( settings.military && h < 10 ) {
				displayhours = '0' + displayhours;
			}
			if ( h < 10 ){
				valuehouers = '0'+valuehouers;
			}

			$mc.empty();
			var n = 60 / settings.minutedivisions,
				tt = set_tt(realhours),
				counter = 1;
		
			for(var m=0;m<60;m=m+n) {
				$md = jQuery("<div class='CP_minute' id='" + realhours + "_" + m + "' value='" + valuehouers + ((m<10) ? "0" : "") + m +"'>" 
							 + displayhours + ":" + ((m<10) ? "0" : "") + m + tt 
							 + "</div>");
				if ( !v ) {
					$md.css("float","left");
					if (settings.minutedivisions > 6 
						&& counter == settings.minutedivisions / 2 + 1) {
						// long horizontal, kick in extra row after half
						$mc.append("<div style='clear:left' />");
					}
				}
				$mc.append($md);
				binder($md);
				counter++;
			}
		}
		
		function set_tt(realhours) {
			if (!settings.military) { 
				return (realhours >= 12) ? ' PM' : ' AM'; 
				}
			else { 
				return '';
			}
		}
		
		function putcontainer() {
			if ( e.type != 'focus') {
				$hourcont[0].style.left = e.pageX - 5 + 'px';
				$hourcont[0].style.top = e.pageY - (Math.floor($hourcont.height() / 2)) + 'px';
				rectify($hourcont);
			}
			else {
				$self.after($hourcont);
			}
			$hourcont.slideDown('fast');
			
			if ( settings.useBgiframe )
				bgi( $hourcont );			
		}
		
		function rectify($obj) { 
			// if a div is off the screen, move it accordingly
			var ph = document.documentElement.clientHeight 
						? document.documentElement.clientHeight 
						: document.body.clientHeight;
			var pw = document.documentElement.clientWidth
						? document.documentElement.clientWidth
						: document.body.clientWidth;
			var t = parseInt( $obj[0].style.top );
			var l = parseInt( $obj[0].style.left );
			var st = document.documentElement.scrollTop 
						? document.documentElement.scrollTop 
						: document.body.scrollTop;
			// run off top
			if ( t <= st && !$obj.is("#CP_minutecont") ) {
				$obj.css("top",st+10+'px');
			}
			else if (t + $obj.height() - st > ph) {
				$obj.css("top",st + ph - $obj.height() - 10 + 'px');
			}
			if ( l <= 0 ) {
				$obj.css("left", '10px');
			}
		}
		
		function bgi( ob ) {
			if ( typeof jQuery.fn.bgIframe == 'function' )
				ob.bgIframe();
			else
				alert('bgIframe plugin not loaded.');
		}
		
		function binder($obj) {
		// all the binding is done here
		// event handlers have been abstracted out,
		// so they can handle mouse or key events
		
			// bindings for hc (hours container)
			if($obj.attr("id") == 'CP_hourcont') {
				$obj.mouseout(function(e) { hourcont_out(e) });
			}
			
			// bindings for mc (minute container)
			else if ($obj.attr("id") == 'CP_minutecont') {
				$obj.mouseout(function(e) { minutecont_out(e) });
			}
			
			// bindings for $hd (hour divs)
			else if ($obj.attr("class") == 'CP_hour') {
				$obj.mouseover(function(e) { hourdiv_over($obj, e) });
				$obj.mouseout(function() { hourdiv_out($obj) });					
				$obj.click(function() {	hourdiv_click($obj) });
			}
			
			// bindings for $md (minute divs)
			else if ($obj.attr("class") == 'CP_minute') {
				$obj.mouseover(function() { minutediv_over($obj) });
				$obj.mouseout(function() { minutediv_out($obj) });					
				$obj.click(function() {	minutediv_click($obj) });
			}
		};
		
		function hourcont_out(e) {
			/*
			this tells divs to clear only if rolling all the way 
			out of hourcont.
			relatedTarget "looks ahead" to see where the mouse
			has moved to on mouseOut.
			IE uses the more sensible "toElement".
			try/catch for Mozilla bug on relatedTarget-input field.
			*/
			try {
				var t = (e.toElement) ? e.toElement : e.relatedTarget;
				if (!(jQuery(t).is("div[class^=CP], iframe"))) {
					// Safari incorrect mouseover/mouseout
					//if (!jQuery.browser.safari) {
						cleardivs();
					//}
				}	
			}
			catch(e) {
				cleardivs();
			}
		}
		
		function minutecont_out(e) {
			try {
				var t = (e.toElement) ? e.toElement : e.relatedTarget;
				if (!(jQuery(t).is("div[class^=CP], iframe"))) {
					cleardivs();
				}		
			}
			catch(e) {
				cleardivs();
			}
		}
		
		function hourdiv_over($obj, e) {
			var h = $obj.attr("id").split('_')[1],
				i = $obj.attr("id").split('_')[2],
				l,
				t;
			$obj.addClass("CP_over");
			
			if ( settings.showminutes == "true") {
				$mc.hide();
				renderminutes(h);
				
				// set position & show minutes container
				if (v) {
					t = e.type == 'mouseover'
						? e.pageY - 15
						: $hourcont.offset().top + 2 + ($obj.height() * i);
					if ( h < 12 )
						l = $hourcont.offset().left - $mc.width() - 2;
					else
						l = $hourcont.offset().left + $hourcont.width() + 2;
				}
				else {
					l = (e.type == 'mouseover') 
						? e.pageX - 10 
						: $hourcont.offset().left + ($obj.width()-5) * i;
					if(h<12) {
						t = $hourcont.offset().top - $mc.height() - 2;
					}
					else {
						t = $hourcont.offset().top + $hourcont.height();
					}
				}
				$mc.css("left",l+'px').css("top",t+'px');
				rectify( $mc );
				$mc.show();
				
				if ( settings.useBgiframe )
					bgi( $mc );
			}
			return false;
		}
		
		
		
		function hourdiv_out($obj) {
			$obj.removeClass("CP_over");
			return false;
		}
		
		function hourdiv_click($obj) {
			var h = $obj.attr("id").split('_')[1],
				tt = set_tt(h),
				str = $obj.attr('value');
			if(str.indexOf(' ') != -1) {
				var cleanstr = str.substring(0,str.indexOf(' '));
			}
			else {
				var cleanstr = str;
			}


			//$obj.text(cleanstr + ':00' + tt);
			$obj.text(cleanstr + '00');
			setval($obj);
			cleardivs();
		}
		
		function minutediv_over($obj) {
			$obj.addClass("CP_over");
			return false;
		}
		
		function minutediv_out($obj) {
			$obj.removeClass("CP_over");	
			return false;
		}
		
		function minutediv_click($obj) {
			$obj.text( $obj.attr('value'));
			setval($obj);
			cleardivs();
		}
		
		function setval($obj) { // takes either hour or minute obj
			if(!settings.valuefield) {
				self.value = $obj.text();
			}
			else {
				//jQuery("input[name=" + settings.valuefield + "]").val($obj.text());
				jQuery("input[name=" + settings.valuefield + "]").val($obj.text()).change(); // 5.9.8.3 (2016/05/17)
			}
			callback.apply( $self, [ $obj.text() ]);
			// unbind keydown handler, otherwise it will double-bind if 
			// field is activated more than once
			$self.unbind( "keydown", keyhandler );
		}
		
		function cleardivs() {
			if ( settings.showminutes == "true") {
				$mc.hide();
			}
			$hourcont.slideUp('fast');
			$self.unbind( "keydown", keyhandler );
		}
		
		// keyboard handling
		
		function keyhandler( e ) {
			
			// $obj is current active div
			var $obj = $("div.CP_over").size() ? $("div.CP_over") : $("div.CP_hour:first"),
				divtype = $obj.is(".CP_hour") ? 'hour' : 'minute',
				hi = (divtype == 'hour') ? $obj[0].id.split('_')[2] : 0, // hour index
				h = (divtype == 'minute') ? $obj[0].id.split('_')[0] : $obj[0].id.split('_')[1]; // real hour 
			if (divtype == 'minute') 
				{ var curloc = h<12 ? 'm1' : 'm2' }
			else 
				{ var curloc = h<12 ? 'h1' : 'h2' }
			
			function divprev($obj) {
				if ($obj.prev().size()) {
					eval(divtype + 'div_out($obj)');
					eval(divtype + 'div_over($obj.prev(), e)');
				}
				else { return false; }
			}
			
			function divnext($obj) {
				if ($obj.next().size()) {
					eval(divtype + 'div_out($obj)');
					eval(divtype + 'div_over($obj.next(), e)');
				}
				else { return false; }
			}
			
			function hourtohour($obj) {
				var ctx = h>=12 ? '#hourcol1' : '#hourcol2';
				$newobj = jQuery(".CP_hour[id$=_" + hi + "]", ctx );
				if ($newobj.size()) {
					hourdiv_out($obj);
					hourdiv_over($newobj, e);
				}
				else { return false; }
			}
			
			function hourtominute($obj) {
				hourdiv_out($obj);
				minutediv_over($(".CP_minute:first"));
			}
			
			function minutetohour($obj) {
				minutediv_out($obj);
				var ctx = h>=12 ? '#hourcol2' : '#hourcol1';
				// extract hour from minutediv, then find hourdiv with that hour
				var $newobj = jQuery(".CP_hour[id^=hr_" + h + "]", ctx);
				hourdiv_over($newobj, e);
			}

			switch (e.keyCode) {
				case 37: // left arrow
					if (v) {
						switch (curloc) {
							case 'm1':
								return false;
								break;
							case 'm2':
								minutetohour($obj);
								break;
							case 'h1':
								hourtominute($obj);
								break;
							case 'h2':
								hourtohour($obj);
								break;
						}
					}
					else {
						divprev($obj);
					}
					break;
					
				case 38: // up arrow
					if(v) {
						divprev($obj);
					}
					else {
						switch (curloc) {
							case 'm1':
								return false;
								break;
							case 'm2':
								minutetohour($obj);
								break;
							case 'h1':
								hourtominute($obj);
								break;
							case 'h2':
								hourtohour($obj);
								break;
						}
					}
					break;
				case 39: // right arrow
					if (v) {
						switch (curloc) {
							case 'm1':
								minutetohour($obj);
								break;
							case 'm2':
								return false;
								break;
							case 'h1':
								hourtohour($obj);
								break;
							case 'h2':
								hourtominute($obj);
								break;
						}
					}
					else {
						divnext($obj);
					}
					break;
				
				case 40: // down arrow
					if(v) {
						divnext($obj);
					}
					else {
						switch (curloc) {
							case 'm1':
								minutetohour($obj);
								break;
							case 'm2':
								return false;
								break;
							case 'h1':
								hourtohour($obj);
								break;
							case 'h2':
								hourtominute($obj);
								break;
						}
					}
					break;
					
				case 13: // return
					eval(divtype + 'div_click($obj)');
					break;
					
				default:
					return true;
			}
					
		return false;
			
		}

	return false;
	});
	
	function errorcheck(settings) {
		if (settings.starthour >= settings.endhour) {
			alert('Error - start hour must be less than end hour.');
			return false;
		}
		else if (60 % settings.minutedivisions != 0) {
			alert('Error - param minutedivisions must divide evenly into 60.');
			return false;
		}
	}
	
	return this;

}

$(function(){
	if($.fn.ogClockpicker){
		$(document).ready(function(){ $(".clockpick").ogClockpicker(); });
	}
});



/********************************************************************************************/
/* 曖昧ピッカー																				*/
/*																							*/
/*	AIMAI_xxxのid属性を持つタグを見つけて、xxxのvalue値の％付加を行います。					*/
/*	openGion的には、カラムタグに、aimai属性を設定することで、関連するタグを出力します。		*/
/*		0/null : 何もなし(処理的には1,2,3以外とする)										*/
/*		1 : 前方一致％																		*/
/*		2 : ％後方一致																		*/
/*		3 : ％前後曖昧％																	*/
/*																							*/
/*	@og.rev 5.8.4.1 (2015/02/21) 新規作成(6.2.0.0)											*/
/********************************************************************************************/
function likeComp( _tgtName ){
	var _orgTagName  = _tgtName.substring(6);						// 'AIMAI_' の文字数
	var _likePtn     = $("#" + _tgtName ).attr('aimaiType');
	var _orgTagValue = $("#" + _orgTagName ).val();
	_orgTagValue     = _orgTagValue.replace(/^%+|%+$/g, "");

	if( _orgTagValue != "" ){
		switch( _likePtn ){
			case "1": _orgTagValue =       _orgTagValue + "%";	break;
			case "2": _orgTagValue = "%" + _orgTagValue;		break;
			case "3": _orgTagValue = "%" + _orgTagValue + "%";	break;
		}
	}

	$("#" + _orgTagName ).val( _orgTagValue );
}

/* onSubmit時に自動実行 */
$(function(){
	$("form").submit(function() {
		$("[id^='AIMAI_']").each( function(){likeComp(this.id);} );
	});
});

/********************************************************************************************/
/* 曖昧ピッカー																				*/
/* jQueryのプラグイン																		*/
/*																							*/
/*	@og.rev 5.8.4.1 (2015/02/21) 新規作成(6.2.0.0)											*/
/********************************************************************************************/
$.fn.aimaiPickerOg = function(options) {
	// この文字列が順に0,1,2,3という扱いにいなる。
	var defaults = {
		texts: [' V '     , ' V*'     , '*V '     , '*V*'],				// 桁数を合わせる。
		titls: ['完全一致', '前方一致', '後方一致', '前後曖昧']		// 日本語はリソース化しなければ…
	};

	var opts = $.extend(defaults, options);

	return this.each(function() {
		var txt = $(this);
		var prefix = 'PIC_' + txt.attr('id').replace(/-/g, '') + '_';

		var textsMarkUp = '';
		// ここでピッカーの中身のタグを作成
		for(var i = 0; i < opts.texts.length; i++){
			var item = opts.texts[i];
			var titl = opts.titls[i];
			textsMarkUp += '<span id="'
								+ prefix + 'text-' + i
								+ '" class="text-box"'
								+ '" title="' + titl + '">'
								+ '(' + item + ') </span>';
		}

		// ピッカーそのものを作成
		var box = $('<div id="'
						+ prefix
						+ 'aimai-picker" class="aimai-picker" style="position: absolute; left: 0px; top: 0px;">'
						+ textsMarkUp
						+ '<div style="clear: both;"></div></div>');

		$('body').append(box);
		box.hide();

		// ピッカークリック時の挙動
		box.find('span.text-box').click(function() {
			var indx = this.id.substr(this.id.indexOf('-') + 1);
			txt.attr( 'aimaiType',indx );
			txt.attr( 'title',opts.titls[indx] );
			txt.text( opts.texts[indx] );
			txt.blur();
			hideBox(box);
		});

		// 以下、ボックス制御。気にしなくて良い
		$('body').live('click', function() {
			hideBox(box);
		});

		box.click(function(event) {
			event.stopPropagation();
		});

		var positionAndShowBox = function(box) {
			var pos = txt.offset();
			var left = pos.left + txt.outerWidth() - box.outerWidth();
			if (left < pos.left) left = pos.left;
			box.css({ left: left, top: (pos.top + txt.outerHeight()) });
			showBox(box);
		}

		txt.click(function(event) {
			event.stopPropagation();
			if (!txt.is('input')) {
				positionAndShowBox(box);
			}
		});

		txt.focus(function() {
			positionAndShowBox(box);
		});

		function hideBox(box) {
			if (opts.hideEffect == 'fade')
				box.fadeOut();
			else if (opts.hideEffect == 'slide')
				box.slideUp();
			else
				box.hide();
		}

		function showBox(box) {
			if (opts.showEffect == 'fade')
				box.fadeIn();
			else if (opts.showEffect == 'slide')
				box.slideDown();
			else
				box.show();
		}
	});
};

/* aimaiPicker自動セット */
$(function(){
	if($.fn.aimaiPickerOg){
		$('.aimaiClm').aimaiPickerOg();
	}
});


/*
 * glDatePicker v2.0
 * http://glad.github.com/glDatePicker/
 * カレンダーピッカー
 *
 * Copyright (c) 2013 Gautam Lad.  All rights reserved.
 * Released under the MIT license.
 *
 * OpenGion Modified
 * 横幅、高さはwindowの高さに依存(option指定可)で、表示位置調整
 * アイコンクリック起動対応
 * 返り値をyyyymmdd形式に変更
 * 月曜開始の条件追加
 *
 * 利用方法
 * $(".calPic").glDatePicker(); のようにプラグインを適用するとclass="calPic"がピッカー起動対象です。
 * @og.rev 5.8.9.0 (2015/08/07)
 * @og.rev 5.9.4.3 (2016/01/15) IE7対応
 * @og.rev 5.9.5.0 (2016/02/05) マウスホイール対応
 * @og.rev 5.9.6.1 (2016/03/02) サイズをウインドウの高さによって135-180で可変とする
 * @og.rev 5.9.10.1 (2016/07/02) draggableはエラーが出るのでやめる
 * @og.rev 5.9.11.0 (2016/08/05) カレンダーの事前作成をやめる
 */
 ;(function() {
	$.fn.glDatePicker = function(options) {
		var pluginName = 'glDatePicker';

		// Find the plugin attached to the element
		var instance = this.data(pluginName);

		// If the instance wasn't found, create it...
		if(!instance) {
			// Return the element being bound to
			return this.each(function() {
				return $(this).data(pluginName, new glDatePicker(this, options));
			});
		}

		// ...otherwise if the user passes true to the plugin (on the second call),
		// then return the instance of the plugin itself
		return (options === true) ? instance : this;
	};

	// Default options
	$.fn.glDatePicker.defaults =
	{
		// Style to use for the calendar.  This name must match the name used in
		// the stylesheet, using the class naming convention "gldp-cssName".
		cssName: 'default',

		// The z-index for the calendar control.
		zIndex: 1000,

		// Thickness of border (in pixels)
		borderSize: 1,

		// The number of pixels to offset the calendar's position on the page.
		calendarOffset: { x: 0, y: 1 },

		// Set to true if you want the calendar to be visible at all times.
		// NOTE: If your target element is hidden, the calendar will be hidden as well.
		showAlways: false,

		// Hide the calendar when a date is selected (only if showAlways is set to false).
		hideOnClick: true,

		// Allow selection of months by clicking on the month in the title.
		allowMonthSelect: true,

		// Allow selection of years by clicking on the year in the title.
		allowYearSelect: true,

		// The date that will be treated as 'today'.
		todayDate: new Date(),

		// The date that will appear selected when the calendar renders.
		// By default it will be set to todayDate.
		selectedDate: null,

		// Arrows used for the Previous and Next month buttons on the title.
		// Set these to blank to hide the arrows completely.
		prevArrow: '\u25c4',
		nextArrow: '\u25ba',

		// A collection of dates that can be selectable by the user.
		// The dates can be a one-time selection or made repeatable by setting
		// the repeatYear or repeatMonth flag to true.
		// By default repeatYear and repeatMonth are false.
		//
		// This example creates 4-individual dates that can be selected;
		// The first date will repeat every year, the second date will repeat every
		// month and year, the third date will repeat every month and the fourth date
		// will only be selectable one-time and not repeat:
		//
		//    selectableDates: [
		//        { date: new Date(0, 8, 5), repeatYear: true },
		//        { date: new Date(0, 0, 14), repeatMonth: true, repeatYear: true },
		//        { date: new Date(2013, 0, 24), repeatMonth: true },
		//        { date: new Date(2013, 11, 25) },
		//    ]
		selectableDates: null,

		// A collection of date ranges that are selectable by the user.
		// The ranges can be made to repeat by setting repeatYear to true
		// (repeatMonth is not supported).
		//
		// This example will create 3-sets of selectable date ranges with
		// specific from and to ranges.  The 4th and 5th ranges don't specify
		// the "to" date in which case the "to" date will be the maximum days for
		// the month specified in "from".  The 4th and 5th ranges also repeat every year:
		//
		//     selectableDateRange: [
		//         { from: new Date(2013, 1, 1), to: newDate (2013, 2, 1) },
		//         { from: new Date(2013, 4, 1), to: newDate (2013, 8, 1) },
		//         { from: new Date(2013, 7, 10), to: newDate (2013, 9, 10) },
		//         { from: new Date(0, 8, 10), repeatYear: true }
		//         { from: new Date(0, 9, 1), repeatYear: true }
		//     ]
		selectableDateRange: null,

		// Mark certain dates as special dates.  Similar to selectableDates, this
		// property supports both repeatYear and repeatMonth flags.
		// Each special date can be styled using custom style names and can have
		// data attached to it that will be returned in the onClick callback.
		// The data field can be any custom (JSON style) object.
		//
		// This example creates two (repeatable by year) dates with special data in them.
		// The first date also assigns a special class (which you will have to define).
		//    specialDates: [
		//        {
		//            date: new Date(0, 8, 5),
		//            data: { message: 'Happy Birthday!' },
		//            repeatYear: true,
		//            cssClass: 'special-bday'
		//        },
		//        {
		//            date: new Date(2013, 0, 8),
		//            data: { message: 'Meeting every day 8 of the month' },
		//            repeatMonth: true
		//        }
		//    ]
		specialDates: null,

		// List of months that can be selectable, including when the user clicks
		// on the title to select from the dropdown.
		// This example only makes two months visible; September and December:
		//    selectableMonths: [8, 11]
		selectableMonths : null,

		// List of selectable years.  If not provided, will default to 5-years
		// back and forward.
		// This example only allows selection of dates that have year 2012, 2013, 2015
		//    selectableYears: [2012, 2013, 2015]
		selectableYears: null,

		// List of selectable days of the week.  0 is Sunday, 1 is Monday, and so on.
		// This example allows only Sunday, Tuesday, Thursday:
		//    selectableDOW: [0, 2, 4]
		selectableDOW : null,

		// Names of the month that will be shown in the title.
		// Will default to long-form names:
		//     January, February, March, April, May, June, July,
		//     August, September, October, November, December
		monthNames: null,

		// Names of the days of the Week that will be shown below the title.
		// Will default to short-form names:
		//     Sun, Mon, Tue, Wed, Thu, Fri, Sat
		dowNames: null,

		// The day of the week to start the calendar on.  0 is Sunday, 1 is Monday and so on.
		// HYBS_CALSTART_MON次第とする
		//dowOffset: 0,
		dowOffset: (HYBS_CAL_START_MON==true ? 1 : 0),

		// Callback that will trigger when the user clicks a selectable date.
		// Parameters that are passed to the callback:
		//     el : The input element the date picker is bound to
		//   cell : The cell on the calendar that triggered this event
		//   date : The date associated with the cell
		//   data : Special data associated with the cell (if available, otherwise, null)
		onClick: (function(el, cell, date, data) {
			//el.val(date.toLocaleDateString());
			
			// openGion アイコン起動が出来るようにしておく
			var tgt = el;
			if ( el[0].tagName.toUpperCase() != 'INPUT' ){
				var _targetId = el.attr('targetId');
				if( _targetId != null ){
					tgt = $('#'+_targetId);
				}
			}
			
			var year = date.getFullYear();  
			var month = date.getMonth() + 1;
			var day = date.getDate();
			if ( month < 10 ) {
				month = '0' + month;
			}
			if ( day < 10 ) {
				day = '0' + day;
			}
			// var str = year + month + day;
			var str = year + "" +  month + "" + day;  // 5.9.1.2 (2015/10/23)
			tgt.val(str); // opneGion:yyyymmdd形式
		}),

		// Callback that will trigger when the user hovers over a selectable date.
		// This callback receives the same set of parameters as onClick.
		onHover: function(el, cell, date, data) {},

		// Callback that will trigger when the calendar needs to show.
		// You can use this callback to animate the opening of the calendar.
		onShow: function(calendar) { 
			calendar.show(); 
		},

		// Callback that will trigger when the calendar needs to hide.
		// You can use this callback to animate the hiding of the calendar.
		onHide: function(calendar) { calendar.hide(); },

		// First date of the month.
		firstDate: null
	};

	// Our plugin object
	var glDatePicker = (function() {
		// Main entry point.  Initialize the plugin
		function glDatePicker(element, userOptions) {
			// Grab handle to this
			var self = this;

			// Save bound element to el
			self.el = $(element);
			var el = self.el;

			// Merge user options into default options
			self.options = $.extend(true, {}, $.fn.glDatePicker.defaults, userOptions);
			var options = self.options;

			// Find the calendar element if the user provided one
			self.calendar = $($.find('[gldp-el=' + el.attr('gldp-id') + ' ]'));

			// Default first date to selected
			options.selectedDate = options.selectedDate || options.todayDate;
			options.firstDate = (new Date((options.firstDate || options.selectedDate)))._first();

			if(!(el.attr('gldp-id') || '').length) {
				el.attr('gldp-id', 'gldp-' + Math.round(Math.random() * 1e10))
			}

			// Show the plugin on focus
			el
				.addClass('gldp-el')
				.bind('click', function(e) { self.show(e); });
				//.bind('focus', function(e) { self.show(e); }); // opneGion:focusでは起動させない

			// If the user is defining the container and it exists, hide it on initial creation.
			// The update function will handle showing if it's showAlways = true
			if(self.calendar.length && !options.showAlways) {
				self.calendar.hide();
			}

			// Hide the plugin on mouse up outside of the plugin
			$(document).bind('mouseup', function(e) {
				var target = e.target;
				var calendar = self.calendar;

				if(!el.is(target) && !calendar.is(target) && calendar.has(target).length === 0 && calendar.is(':visible')) {
					self.hide();
				}
			});
			
// 5.9.10.1 (2016/07/02) Del 
//			if(typeof $(self).draggable == "function"){
//			$(self).draggable({
//				 opacity  : 0.5
//			    ,cursor   : 'move'
//			    });
//			}

			// Render calendar
			//self.render(); // 5.9.11.0 一覧で遅いのでここで予め作る事はしない
		};

		// Public methods
		glDatePicker.prototype =
		{
			show: function() {
				this.render();// 5.9.6.1 (2016/03/04)
				// Hide others and show this calendar
				$.each($('.gldp-el').not(this.el), function(i, o) {
					if(o.length) { o.options.onHide(o.calendar) ; }
				});

				// Show this calendar
				this.options.onShow(this.calendar);
			},

			hide: function() {
				if(this.options && !this.options.showAlways) {
					this.options.onHide(this.calendar);
				}
			},

			// Render the calendar
			render: function(renderCalback) {
				var self = this;
				var el = self.el;
				var options = self.options;
				var calendar = self.calendar;

				// Build a core class (with border) that every element would have
				var coreClass = ' core border ';
				var cssName = 'gldp-' + options.cssName;

				// Get today
				var todayVal = options.todayDate._val();
				var todayTime = todayVal.time;

				// Constants
				var maxRow = 6;
				var maxCol = 7;
				var borderSize = options.borderSize + 'px';

				// Helper function to build selectable list
				var getSelectableList = function(min, max, userList) {
					// Build a default list using min/max
					var resultList = [];
					for(var i = min; i <= max; i++) { resultList.push(i); }

					// If user provided a collection, sanitize list by ensuring it's within range and unique
					if(userList) {
						var newList = [];
						$.each(userList, function(i, v) {
							if(v >= min && v <= max && newList._indexOf(v) < 0) {
								newList.push(v);
							}
						});

						resultList = newList.length ? newList : resultList;
					};

					// Sort the values before returning it
					resultList.sort();

					return resultList;
				};

				// Selectable (constants)
				var selectableMonths = getSelectableList(0, 11, options.selectableMonths);
				var selectableYears = getSelectableList(todayVal.year - 5, todayVal.year + 5, options.selectableYears);
				var selectableDOW = getSelectableList(0, 6, options.selectableDOW);
				var dowNames = options.dowNames || ['日','月','火','水','木','金','土'];
				var monthNames = options.monthNames || ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'];
				
				// Create cell width based on el size
				//var containerWidth = el.outerWidth();
				// 5.9.6.1 (2016/03/04) 可変
				var containerSize = window.innerHeight ? window.innerHeight : 180;
				if( containerSize < 180 ){ containerSize = (containerSize > 135 ? containerSize : 135); }
				else{ containerSize = 180; }
				
				var containerWidth = options.conainerWidth || containerSize; // opneGion:180を基準として、130までは可変
				var containerHeight = containerWidth;

				// Create cell size based on container size
				var getCellSize = function(_size, _count) {
//					return (_size / _count) + ((options.borderSize / _count) * (_count - 1));
					return (_size / _count) + ((options.borderSize / _count) * (_count - 1)) - 1; // 5.9.4.3
				};
				var cellWidth = getCellSize(containerWidth, maxCol);
				var cellHeight = getCellSize(containerHeight, maxRow + 2);

				// If calendar doesn't exist, create it and re-assign it to self
				if(!calendar.length) {
					self.calendar = calendar = $('<div/>')
						.attr('gldp-el', el.attr('gldp-id'))
						.data('is', true)
						.css(
						{
							display: (options.showAlways ? undefined : 'none'),
							zIndex: options.zIndex,
							//width: (cellWidth * maxCol) + 'px'
							width: ((cellWidth+1) * maxCol) + 'px' // 5.9.4.3
						});

					$('body').append(calendar);
				}
				else {
					if(!eval(calendar.data('is'))) {
						containerWidth = calendar.outerWidth();
						containerHeight = calendar.outerHeight();

						cellWidth = getCellSize(containerWidth, maxCol);
						cellHeight = getCellSize(containerHeight, maxRow + 2);
					}
					// 5.9.6.1 (2016/03/04)
					self.calendar.css(
						{
							width: ((cellWidth+1) * maxCol) + 'px'
						}
					)
				}

				// Hide calendar if the target element isn't visible
				if(!el.is(':visible')) { calendar.hide(); }

				// Add core classes and remove calendar's children
				calendar
					.removeClass()
					.addClass(cssName)
					.children().remove();

				// Bind to resize event to position calendar
				var onResize = function() {
					var elPos = el.offset();
					
					// ポジションは上、右にスペースが無い場合は修正する
					calPosTop = (elPos.top + el.outerHeight() + options.calendarOffset.y) -20;
					calPosLeft = (elPos.left + options.calendarOffset.x);
					
					if( calPosTop > $(window).height() - 150 ){ calPosTop -= 130; }
					if( calPosLeft > $(window).width() -150 ) { calPosLeft -= 150; }
					
					if( calPosTop < 0 ){ calPosTop = 0; }
					if( calPosLeft < 0 ){ calPosLeft = 0; }
					
					calendar.css(
					{
						top: calPosTop + 'px',
						left: calPosLeft + 'px'
					});
				};
				$(window).resize(onResize);
				onResize();

				// Create variables for cells
				var cellCSS =
				{
					width: cellWidth + 'px',
					height: cellHeight + 'px',
					lineHeight: cellHeight + 'px'
				};

				// Helper function to setDate
				var setFirstDate = function(_date) {
					if(_date) {
						// Get first date
						options.firstDate = _date;

						// Update the calendar
						self.render();
					}
				};

				var getFirstDate = function(_offset) {
					// Create start date as the first date of the month
					var _date = new Date(options.firstDate);

					// Default to no offset
					_offset = _offset || 0;

					// Find out which months are selectable
					while(true) {
						// Adjust date for month offset
						_date.setMonth(_date.getMonth() + _offset);
						_date.setDate(Math.min(1, _date._max()));

						// If not an offset, break out of the loop
						if(_offset == 0) { break; }

						// Get _date's value
						var dateVal = _date._val();

						// Get local vars
						var dateMonth = dateVal.month;
						var dateYear = dateVal.year;

						// Find the month first
						if(selectableMonths._indexOf(dateMonth) != -1) {
							// If year is in our collection, break...
							if(selectableYears._indexOf(dateYear) != -1) {
								break;
							}
							else {
								// ...otherwise, if it's out of bounds, exit loop
								if(dateYear < selectableYears[0] || dateYear > selectableYears[selectableYears.length - 1]) {
									return null;
								}
							}
						}
					}

					return _date;
				};

				// Get the previous, next first dates
				var prevFirstDate = getFirstDate(-1);
				var nextFirstDate = getFirstDate(1);

				// Get the first date for the current month being rendered
				var firstDate = (options.firstDate = getFirstDate());
				var firstDateVal = firstDate._val();
				var firstDateMonth = firstDateVal.month;
				var firstDateYear = firstDateVal.year;

				// Get the start date in the calendar
				var startDate = new Date(firstDate);

				// Sanitize days of the week offset
				var dowOffset = Math.abs(Math.min(6, Math.max(0, options.dowOffset)));

				// Offset weekdays
				var startOffset = startDate.getDay() - dowOffset;
					startOffset = startOffset < 1 ? -7 - startOffset : -startOffset;
					dowNames = (dowNames.concat(dowNames))
								.slice(dowOffset, dowOffset + 7);

				// Offset the start date
				startDate._add(startOffset);

				// Gather flags for prev/next arrows
				var showPrev = (prevFirstDate);
				var showNext = (nextFirstDate);

				// Create the arrows and title
				var monyearClass = coreClass + 'monyear ';

				var prevCell = $('<div/>')
								.addClass(monyearClass)
								.css(
									$.extend({}, cellCSS,
									{
										borderWidth: borderSize + ' 0 0 ' + borderSize
									})
								)
								.append(
									$('<a/>')
										.addClass('prev-arrow' + (showPrev ? '' : '-off'))
										.html(options.prevArrow)
								)
								.mousedown(function() { return false; })
								.click(function(e) {
									if(options.prevArrow != '' && showPrev) {
										e.stopPropagation();
										setFirstDate(prevFirstDate);
									}
								});

				var titleCellCount = maxCol - 2;
				var titleWidth = (cellWidth * titleCellCount) - (titleCellCount * options.borderSize) + (options.borderSize);
				var titleCell = $('<div/>')
								.addClass(monyearClass + 'title')
								.css(
									$.extend({}, cellCSS,
									{
										width: titleWidth + 'px',
										borderTopWidth: borderSize,
										marginLeft: '-' + (borderSize)
									})
								);

				var nextCell = $('<div/>')
								.addClass(monyearClass)
								.css(
									$.extend({}, cellCSS,
									{
										marginLeft: '-' + (borderSize),
										borderWidth: borderSize + ' ' + borderSize + ' 0 0'
									})
								)
								.append(
									$('<a/>')
										.addClass('next-arrow' + (showNext ? '' : '-off'))
										.html(options.nextArrow)
								)
								.mousedown(function() { return false; })
								.click(function(e) {
									if(options.nextArrow != '' && showNext) {
										e.stopPropagation();
										setFirstDate(nextFirstDate);
									}
								});

				// Add cells for prev/title/next
				calendar
					.append(prevCell)
					.append(titleCell)
					.append(nextCell);

				// Add all the cells to the calendar
				for(var row = 0, cellIndex = 0; row < maxRow + 1; row++) {
					for(var col = 0; col < maxCol; col++, cellIndex++) {
						var cellDate = new Date(startDate);
						var cellClass = 'day';
						var cellZIndex = options.zIndex + (cellIndex);
						var cell = $('<div/>')

						if(!row) {
							cellClass = 'dow';
							cell.html(dowNames[col]);
							cellDate = null;
						}
						else {
							// Get the new date for this cell
							cellDate._add(col + ((row - 1) * maxCol));

							// Get value for this date
							var cellDateVal = cellDate._val();
							var cellDateTime = cellDateVal.time;

							// Variable to hold special data
							var specialData = null;

							// Determine if this date is selectable
							var isSelectable = true;

							// Helper function to get repeat friendly date against current date
							var getRepeatDate = function(v, date) {
								// If repeating, set the date's year and month accordingly
								if(v.repeatYear === true) { date.setYear(cellDateVal.year); }
								if(v.repeatMonth === true) { date.setMonth(cellDateVal.month); }

								return date._val();
							};

							// Assign date for the cell
							cell.html(cellDateVal.date);

							// If we have selectable date ranges
							if(options.selectableDateRange) {
								isSelectable = false;
								$.each(options.selectableDateRange, function(i, v) {
									var dateFrom = v.from;
									var dateTo = (v.to || null);

									// If to is not specified, default to max days in the from month
									dateTo = dateTo || new Date(v.from.getFullYear(), v.from.getMonth(), v.from._max());

									// If repeating year, set the from and two to the current date's year
									dateFrom = getRepeatDate(v, dateFrom);
									dateTo = getRepeatDate(v, dateTo);

									// Test to see if this date is selectable
									if(cellDateTime >= dateFrom.time && cellDateTime <= dateTo.time) {
										isSelectable = true;
										return true;
									}
								});
							}

							// Handle date ranges and collections
							if(options.selectableDates) {
								if((options.selectableDateRange && !isSelectable) || (isSelectable && !options.selectableDateRange)) {
									isSelectable = false;
								}
								$.each(options.selectableDates, function(i, v) {
									var vDate = getRepeatDate(v, v.date);

									if(vDate.time == cellDateTime) {
										return (isSelectable = true);
									}
								});
							}

							// If not active or if not within selectableMonths, set to noday otherwise evaluate accordingly
							if(!isSelectable ||
								selectableYears._indexOf(cellDateVal.year) < 0 ||
								selectableMonths._indexOf(cellDateVal.month) < 0 ||
								selectableDOW._indexOf(cellDateVal.day) < 0) {
								cellClass = 'noday';
							}
							else {
								// Handle active dates and weekends
								cellClass = ([ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ])[cellDateVal.day];

								// Handle today or selected dates
								if(firstDateMonth != cellDateVal.month) { cellClass += ' outday'; }
								if(todayTime == cellDateTime) { cellClass = 'today'; cellZIndex += 50; }
								if(options.selectedDate._time() == cellDateTime) { cellClass = 'selected'; cellZIndex += 51; }

								// Handle special dates
								if(options.specialDates) {
									$.each(options.specialDates, function(i, v) {
										var vDate = getRepeatDate(v, v.date);

										if(vDate.time == cellDateTime) {
											cellClass = (v.cssClass || 'special');
											cellZIndex += 52;
											specialData = v.data;
										}
									});
								}

								cell
									.mousedown(function() { return false; })
									.hover(function(e) {
										e.stopPropagation();

										// Get the data from this cell
										var hoverData = $(this).data('data');

										// Call callback
										options.onHover(el, cell, hoverData.date, hoverData.data);
									})
									.click(function(e) {
										e.stopPropagation();

										// Get the data from this cell
										var clickedData = $(this).data('data');

										// Save date to selected and first
										options.selectedDate = options.firstDate = clickedData.date;

										// Update calendar (and auto-hide if necessary)
										self.render(function() {
											if(!options.showAlways && options.hideOnClick) {
												self.hide();
											}
										});

										// Call callback
										options.onClick(el, $(this), clickedData.date, clickedData.data);
									});
							}
						}

						// Update the css for the cell
						$.extend(cellCSS,
						{
							borderTopWidth: borderSize,
							borderBottomWidth: borderSize,
							borderLeftWidth: (row > 0 || (!row && !col)) ? borderSize : 0,
							borderRightWidth: (row > 0 || (!row && col == 6)) ? borderSize : 0,
							marginLeft: (col > 0) ? '-' + (borderSize) : 0,
							marginTop: (row > 0) ? '-' + (borderSize) : 0,
							zIndex: cellZIndex
						});

						// Assign other properties to the cell
						cell
							.data('data', { date: cellDate, data: specialData})
							.addClass(coreClass + cellClass)
							.css(cellCSS);

						// Add cell to calendar
						calendar.append(cell);
					}
				}

				// Render the month / year title

				// Helper function for toggling select and text
				var toggleYearMonthSelect = function(showYear) {
					var show = 'inline-block';
					var hide = 'none';

					if(options.allowMonthSelect) {
						monthText.css({ display: !showYear ? hide : show });
						monthSelect.css({ display: !showYear ? show : hide });
					}

					if(options.allowYearSelect) {
						yearText.css({ display: showYear ? hide : show });
						yearSelect.css({ display: showYear ? show : hide });
					}
				};

				// Helper function when select is updated
				var onYearMonthSelect = function() {
					options.firstDate = new Date(yearSelect.val(), monthSelect.val(), 1);
					self.render();
				};

				// Build month selector
				var monthSelect = $('<select/>')
									.hide()
									.change(onYearMonthSelect);

				// Build year selector
				var yearSelect = $('<select/>')
									.hide()
									.change(onYearMonthSelect);

				// Build month label
				var monthText = $('<span/>')
									.html(monthNames[firstDateMonth])
									.mousedown(function() { return false; })
									.click(function(e) {
										e.stopPropagation();
										toggleYearMonthSelect(false);
									});

				// Build year label
				var yearText = $('<span/>')
									.html(firstDateYear)
									.mousedown(function() { return false; })
									.click(function(e) {
										e.stopPropagation();
										toggleYearMonthSelect(true);
									});

				// Populate month select
				$.each(monthNames, function(i, v) {
					if(options.allowMonthSelect && selectableMonths._indexOf(i) != -1) {
						var o = $('<option/>').html(v).attr('value', i);
						if(i == firstDateMonth) { o.attr('selected', 'selected');}
						monthSelect.append(o);
					}
				});

				// Populate year select
				$.each(selectableYears, function(i, v) {
					if(options.allowYearSelect) {
						var o = $('<option/>').html(v).attr('value', v);
						if(v == firstDateYear) { o.attr('selected', 'selected'); }
						yearSelect.append(o);
					}
				});

				var titleYearMonth = $('<div/>')
										.append(monthText)
										.append(monthSelect)
										.append(yearText)
										.append(yearSelect);

				// Add to title
				titleCell.children().remove();
				titleCell.append(titleYearMonth);

				// Run the callback signaling end of the render
				renderCalback = renderCalback || (function() {});
				renderCalback();
				
				// マウスホイールの回転 5.9.5.0
				var mousewheelevent = 'onwheel' in document ? 'wheel' : 'onmousewheel' in document ? 'mousewheel' : 'DOMMouseScroll';
			    calendar.bind(mousewheelevent,function(e){
			        e.preventDefault();
			        var delta = e.originalEvent.deltaY ? -(e.originalEvent.deltaY) : e.originalEvent.wheelDelta ? e.originalEvent.wheelDelta : -(e.originalEvent.detail);
			        if (delta < 0){
			            // マウスホイールを下に
			            nextCell.click();
			        } else {
			            // マウスホイールを上に
			            prevCell.click();
			        }
			    });

			}
		
		};
		
		
		// Return the plugin
		return glDatePicker;
	})();

	// One time initialization of useful prototypes
	(function() {
		Date.prototype._clear = function() {
			this.setHours(0);
			this.setMinutes(0);
			this.setSeconds(0);
			this.setMilliseconds(0);

			return this;
		};

		Date.prototype._time = function() {
			return this._clear().getTime();
		};

		Date.prototype._max = function() {
			var isLeapYear = (new Date(this.getYear(), 1, 29).getMonth() == 1) ? 1 : 0;
			var days = [31, 28 + isLeapYear, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

			return days[this.getMonth()];
		};

		Date.prototype._add = function(days) {
			this.setDate(this.getDate() + days);
		};

		Date.prototype._first = function() {
			var date = new Date(this);
				date.setDate(1);

			return date;
		};

		Date.prototype._val = function() {
			this._clear();

			return {
				year: this.getFullYear(),
				month: this.getMonth(),
				date: this.getDate(),
				time: this.getTime(),
				day: this.getDay()
			};
		};

		Array.prototype._indexOf = function(value) {
			return $.inArray(value, this);
		}
	})();
})();

/* 日付ピッカー自動セット */
$(function(){
	if($.fn.glDatePicker){
		$(".calPic").glDatePicker(); 
	}
});


/*
 * multipleのリストボックスで、初期選択されていた場合にその位置にスクロールします。
 * optionの高さが取れなかったので、sizeから割り出しています。
 *
 * @og.rev 5.9.4.5 (2016/01/29) 新規作成
 */
function selectScroll(_tgt){
		var size = 4;
		if( _tgt.getAttribute('size') ){ size= _tgt.getAttribute('size');}
		var _child = _tgt.options;
		for(var i=0; i<_child.length; i++){
			if(_child[i].selected){
				// 親がグループの場合のみ
				if( _child[i].parentNode.tagName.toUpperCase() == 'OPTGROUP'){
					 i += $(_child[i].parentNode).prev().length;
					
				}
				var firstSelected = i * ($(_tgt).height()/size);
				break;
			}
		}
		$(_tgt).scrollTop(firstSelected);
	}
	
// マルチのセレクトに対して画面ロード時に実行する
$(function(){
	$('select[multiple]').each(function(){ selectScroll(this); });
});