/**
 * 標準JavaScript
 * last = 2009/03/04
 */

// 静的ファイルへのパス
var static_path = "http://static.aifuku.net/";
var system_unread_count = [];

var imgPreLoader1 = new Image();
imgPreLoader1.src = static_path + 'images/ajax-loader3.gif';
var imgPreLoader2 = new Image();
imgPreLoader2.src = static_path + 'images/ajax-loader4.gif';

// 初期化する
$(function() { init(); } );


/**
 * フッターの位置初期化
 */
function footerReset()
{
	document.getElementById('footer').style.bottom = "0px";
	document.getElementById('footer').style.bottom = "-1px";

	//$("#footer").css( "bottom", "0px" );
	//$("#footer").css( "bottom", "-1px" );
	return false;
}



/**
 * 初期化処理
 */
function init()
{
	// input type=textをエンター不可にする
	$("input").keydown( function(event)
	{
		return !(event.keyCode == 13);
	});
	
	//$("#toggleSlideMenuArea").click( function(){ toggleSlideMenu() } );

	// ツールチップにイベントを割り当てる
	$("img.tooltip").tooltip( {
		track: false,
   	 	delay: 0,
    	showURL: false,
		showBody: " - ",
		fade: 120,
		positionLeft: true
	});

	// 印刷アイコンにイベント
	//$("#printer-icon").hover( function() { $("#header_print_message").show() }, function() { $("#header_print_message").hide() } );

	// 印刷モード
	if ( location.href.match(/print=true/) ) printerMode();

	// 未読アイコン付加
	var menu_def_height = 26 + 46;
	if ( system_unread_count.length ) {
		$("#system-menu li").each( function(i) {
			menu_def_height += 46;

			var id = $(this).attr("id");
			var sid = id.replace(/system-menu/, "");

			if ( sid ) {
				var cnt = system_unread_count[sid];
				if (typeof cnt !== "undefined") {
					$("#system-unread"+sid).html( cnt ).css( {"top": menu_def_height + "px", "display": "block" } );
				}
			}
		});
	}

	// フォームの入力チェック
	p3_form_check();

	// 自分宛にも送信チェックボックス
	if ( getCookie("my_send_check_flag") == "true" ) $("#my-send-check").attr("checked", true);
	
	// IE6でpngを透過する
	$(document).pngFix();
	
	// サブメニューを角丸にする
	$("#content_pankuzu").corner();
	//$("div.body_area").corner();
	
	footerReset();
}
/*** End of function 'init' ***/



/**
 * フォームの入力チェック
 */
function p3_form_check()
{
	if (typeof feid == "undefined") return false;

	// 全てのformタグをチェック
	if ( feid.length > 0 ) { //フォームタグとset配列が存在する場合
		for ( var f = 0; f < feid.length ; f++ )
		{
			//form_se[feid[f]] = new Array();
			//errorMsg[feid[f]] = new Array();

			// type=submitのイベント
			$("#" + feid[f] + " input[type=submit]")
				.click( function()
				{
					var e = '';
					var error_mes = '';
					var z = $(this).parents("form").attr("id");

					var form_obj = $("#"+z+" input[type=text],#"+z+" input[type=hidden],#"+z+" input[type=password],#"+z+" input[type=file],#"+z+" textarea");

					// エラーメッセージがあった場合でも改めて確認
					for ( var i = 0; i < form_obj.length ; i++ )
					{
						var n = form_obj[i].name;
						var v = form_obj[i].value;

						if ( n in set ) {}
						else continue;

						if ( typeof v === "undefined" ) v = "";

						if ( ! v.match( set[n]["r"] ) || getByte( v ) > set[n]["m"] ) {
							error_mes = true;
							alert(set[n]["e"]);
							//$.jGrowl( set[n]["e"], { "header": "入力エラー", "theme": "error", "life": 10000 } );
						}
					}
					if ( error_mes ) {
						location.href = "#" + z;
						return false;
					}
				}
			);

		}
	}
}



/**
 * 文字の大きさ変更
 */
function fontSizeChange( size )
{
	if ( !size ) size = "90%";
	document.getElementsByTagName("body")[0].style.fontSize = size;

	createCookie("font_size",size,100);

	var left_height = $("#dummy-height-area" ).height();
	var right_height = $("#top_side_area" ).height();
	if ( left_height < right_height ) $("#dummy-height-area").css( "height", right_height + "px" );
	else $("#dummy-height-area").css( "height", left_height + "px" );

	footerReset();

	return false;
}

/**
 * メニューの開け閉め
 */
function toggleSlideMenu( no_cookie )
{
	// 閉じる
	if ( document.getElementById('menu_area').style.left == '0px' ) {
		document.getElementById('menu_area').style.left = '-125px';
		document.getElementById('content').style.marginLeft = '65px';

		$("#menu_area li a").css( { "background-position": "126px center" } );
		if ( !no_cookie ) createCookie("menu_open","close",100);
	}
	// 開ける
	else {
		document.getElementById('menu_area').style.left = '0px';
		document.getElementById('content').style.marginLeft = '190px';
		$("#menu_area li a").css( { "background-position": "0px center" } );
		if ( !no_cookie ) createCookie("menu_open","open",100);
	}
	footerReset();

	return false;
}


// 自分宛にも送信するチェックボックス
function checkMySend()
{
	var flag = document.getElementById("my-send-check").checked;
	createCookie("my_send_check_flag", flag, 100);
}


// お役立ちサイト表示
function viewSlide( id )
{
	$( id ).css("z-index","10000").toggle( "fast" );

	if ( !$("#body").is("#unbind-overray") ) {
		$("#body").prepend('<div id="unbind-overray"></div>').css({height:'100%', width:'100%', 'z-index': 19000})
			.click(function()
			{
				$( id ).hide();
			}
		);
	}
	return false;
}


// [rescue.php]要請ボックス表示
function viewRescueBox( id )
{
	$("#rescue-receive-box-"+id).toggle("fast", function()
		{
			$("#rescue-receive-box-"+id+" textarea").focus();	
		}
	);
	$("div.rescue_receive_box").hide();
	
	return false;
}
function  hideRescueBox( id )
{
	$("#rescue-receive-box-"+id).hide();
	return false;
}
// [rescue.php]要請決定
function sendRescueReceive( rescue_id, rescue_receive_id, user )
{
	var msg = user + "さんに要請を依頼します。\n尚、この処理は訂正できません。ご確認ください。";

	if ( !confirm( msg )  ) return false;
	
	var obj = {};
	var id = rescue_receive_id;
	obj.rescue_body = $("#rescue-receive-box-"+id+" textarea").val();
	obj.rescue_receive_id = rescue_receive_id;
	obj.rescue_id = rescue_id;

	$.post( "./rescue?action=ajax_update_rescue_receive", obj, function(res)
	{
		$("#rescue-loading-image-"+id).remove();
		eval( "var xml = " + res );
		
		if ( xml.error ) {
			g_alert( xml.error, false );
			return false;
		}
		$('#rescue-receive-parent-box-'+id).html( '<span class="bg_green" id="tooltip-'+id+'" title="' + obj.rescue_body.replace(/\n/, '<br />') + '">要請済み</span>' );
		setTooltip( "#tooltip-"+id );
	});
	hideRescueBox( id );
	$('#rescue-receive-parent-box-'+id).html( '<img src="' + static_path + 'images/ajax-loader4.gif" id="rescue-loading-image-'+id+'" />' );

	
	return false;
}


// [rescue.php]依頼完了ボックス表示
function viewRescueDoneBox( id )
{
	$("#rescue-done-box-"+id).toggle("fast", function()
		{
			$("#rescue-done-box-"+id+" textarea").focus();	
		}
	);
	$("div.rescue_done_box").hide();
	
	return false;
}
function  hideRescueDoneBox( id )
{
	$("#rescue-done-box-"+id).hide();
	return false;
}
// [rescue.php]依頼完了決定
function sendRescueDoneReceive( rescue_id )
{
	var msg = "この依頼を完了します。\n尚、この処理は訂正できません。ご確認ください。";

	if ( !confirm( msg )  ) return false;
	
	var obj = {};
	var id = rescue_id;
	obj.end_body = $("#rescue-done-box-"+id+" textarea").val();
	obj.rescue_id = rescue_id;

	$.post( "./rescue?action=ajax_done_rescue", obj, function(res)
	{
		$("#rescue-loading-image-"+id).remove();
		eval( "var xml = " + res );
		
		if ( xml.error ) {
			g_alert( xml.error, false );
			return false;
		}
		location.reload();
	});
	hideRescueDoneBox( id );
	$('#rescue-done-parent-box-'+id).html( '<img src="' + static_path + 'images/ajax-loader4.gif" id="rescue-loading-image-'+id+'" />' );

	
	return false;
}



// tooltipイベント割り当て
function setTooltip( sl )
{
	$(sl).tooltip( {
		track: true,
   	 	delay: 0,
    	showURL: false,
		showBody: " - ",
		fade: 120
	});
}


// クッキー書き込み
function createCookie(name,value,days)
{
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name)
{
	var arg  = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;

	while (i < clen)
	{
		var j = i + alen;
		if ( document.cookie.substring(i, j) == arg ) return getCookieVal(j);
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) break;
	}
	return "";
}
function getCookieVal(offset)
{
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1) endstr = document.cookie.length;
	return unescape(document.cookie.substring(offset,endstr));
}




// Growlアラート
function g_alert( msg )
{
	var title = arguments[1];
	var header = "";
	var theme = "default";

	alert(msg);return false;

	if ( typeof( title ) == "undefined" ) { header = ""; theme = "default"; }
	else if ( title ) { header = title; }
	else { header = "エラー";  theme = "error"; }

	return $.jGrowl( msg, { "header": header, "theme": theme, "closerTemplate": "<div>[ 全て閉じる ]</div>" });
}


/**
 * 全てのチェックボックスをトグル
 */
function allCheckboxToggle( t )
{
	if ( $(t).attr("checked") == true ) {
		$('input[type=checkbox]').attr('checked', true);
	}
	else {
		$('input[type=checkbox]').attr('checked', false);
	}
}


// INPUTエリアをコピー(汎用)
function copyInputArea( t, max_num )
{
	var copy_area;
	var b_name = "";
	var clone;

	copy_area = $(t).prev();
	clone = copy_area.clone();

	// コピー元のエリアのname属性を分解
	copy_area.attr("name").match( /^(.+)([\d]+)(.*)$/ );

	var copy_name_front = RegExp.$1;
	var next_id = RegExp.$2;
	var copy_name_back = RegExp.$3;

	next_id = parseInt( next_id ) + 1;

	// 上限
	if ( next_id > max_num ) {
		g_alert( "追加は" + max_num + "までです", false );
		return false;
	}

	clone.attr( "name", copy_name_front + next_id + copy_name_back ).val( "" );
	copy_area.after( clone ).after( "<br />" );

	//g_alert( clone.attr("name") );
	footerReset();

	return false;
}


// INPUTエリアをコピー(会議研修案内edit_meeting)
function copyInputAreaMeeting( t, max_num )
{
	var copy_area;
	var b_name = "";
	var clone;

	copy_area = $(t).prev();
	clone = copy_area.clone();

	// コピー元のエリアのname属性を分解
	copy_area.attr("name").match( /^(.+)([\d]+)(\[.*\])$/ );

	var copy_name_front = RegExp.$1;
	var next_id = RegExp.$2;
	var copy_name_back = RegExp.$3;

	next_id = parseInt( next_id ) + 1;

	// 上限
	if ( next_id > max_num ) {
		g_alert( "追加は" + max_num + "までです", false );
		return false;
	}

	clone.attr( "name", copy_name_front + next_id + copy_name_back ).val( "" );
	copy_area.after( clone ).after( "<br />" );

	//g_alert( clone.attr("name") );
	footerReset();

	return false;
}


// INPUTフィールドをコピー(会議研修案内edit_meeting)
function copyInputFieldMeeting1( t, max_num )
{
	var copy_area;
	var clone;

	copy_area = $(t).prev();
	clone = copy_area.clone();

	// コピー元のtooltipや回答の1問目以降を削除
	clone.find( "img.tooltip, input:gt(1), br" ).remove();
	clone.find( "input" ).val( "" );

	// 次のナンバーを取得
	var next_id = copyInputFieldMeeting1_count;
	// 現在のボックス数を取得
	var box_count = $( "div.question_field" ).size();

	// 上限チェック
	if ( box_count >= max_num ) {
		g_alert( "追加は" + max_num + "までです", false );
		return false;
	}

	// inputのnameを修正
	$.each( clone.find( "input" ),
		function ( i ) {
			var new_name = $(this).attr( "name" ).replace( /^(.+\[)[0-9]+(\])$/, "$1"+ next_id +"$2" );
			$(this).attr( "name", new_name );
		}
	);

	//clone.find( "span" ).text( next_id );
	clone.css( "margin-top", "12px" );
	copy_area.after( clone );

	copyInputFieldMeeting1_count = next_id + 1;

	footerReset();

	return false;
}

// INPUTフィールドをコピー(会議研修案内view_meeting)
function copyInputFieldMeeting2( t, max_num )
{
	var copy_area;
	var clone;

	copy_area = $(t).prev();
	clone = copy_area.clone().not("script");

	// オブジェクトが送られてきたら展開
	//if ( !obj ) obj = {};
	//if ( obj.name ) clone.find( "input[name=names[]]" ).val( obj.name );
	//if ( obj.job ) clone.find( "input[name=jobs[]]" ).val( obj.job );


	// 次のナンバーを取得
	var next_id = copyInputFieldMeeting2_count;
	// 現在のボックス数を取得
	var box_count = $( "div.question_field" ).size();

	// 編集モードだったら
	if ( next_id == 1 && box_count > 1) next_id = box_count + copyInputFieldMeeting2_delete_count;

	// 上限チェック
	if ( box_count >= max_num ) {
		g_alert( "追加は" + max_num + "までです", false );
		return false;
	}

	// コピー元のtooltipや回答の1問目以降を削除、name属性を変更
	//clone.find( "input" ).not( "input:radio" ).val( "" )
	//	.filter(":eq(0)").attr("name", "names["+next_id+"]")
	//		.end()
	//	.filter(":eq(1)").attr("name", "jobs["+next_id+"]");
	clone.find( "input" ).not( "input:radio" ).val( "" )
		.filter(":eq(0)").after('<input type="text" name="names['+next_id+']" value="" style="width: 90%;" />').remove()
			.end()
		.filter(":eq(1)").after('<input type="text" name="jobs['+next_id+']" value="" style="width: 90%;" />').remove();


	//g_alert( clone.find( "input" ).not( "input:radio" ).filter(":eq(0)").attr("name") );


	// チェックボックスを外す
	clone.find( "input:radio" ).removeAttr("checked");

	// ラジオボックスのnameとidを修正
	$.each( clone.find( "input:radio" ),
		function ( i ) {
			var new_name = $(this).attr( "name" ).replace( /\[[0-9]+\]$/, "["+ next_id +"]" );
			var new_val = $(this).val();
			var new_id = $(this).attr( "id" ).replace( /[\d]+$/, next_id );
			$(this).after('<input type="radio" name="'+new_name+'" id="'+new_id+'" value="'+new_val+'" />').remove();
		}
	);

	// labelのforを修正
	$.each( clone.find( "label" ),
		function ( i ) {
			$(this).attr( "for", $(this).attr( "for" ).replace( /[\d]+$/, next_id ) );
		}
	);

	clone.css( "margin-top", "12px" );
	copy_area.after( clone );

	copyInputFieldMeeting2_count = next_id + 1;

	footerReset();

//alert( $("#content_body").html()  );
//clone.find("p").html(1);
//$("#content_body").html( "<xmp>" + clone.html());


	return false;
}

// 長い文章を表示する(thisより前のエレメントを削除)
function openToggleDetail( t )
{
	var area = {};
	area = $( t ).next();

	area.toggle("fast", 
		function() {
			footerReset();
		}
	);
	//alert( $(t).parent().children().size() )
	$( t ).prev().remove();

	return false;
}


// INPUTフィールドを削除(会議研修案内view_meeting)
function deleteInputFieldMeeting2( t )
{
	//	alert( $(t).parent().parent().html() );

	if ( $( "div.question_field" ).size() == 1 ) {
		$(t).parent().parent().find("script").remove()
			.end()
		.find( "input" ).not( ":radio" ).val( "" )
			.end()
		.filter(":radio").removeAttr("checked");
		return false;
	}
	$(t).parent().parent().remove();
	copyInputFieldMeeting2_delete_count++;
	footerReset();
}



// INPUTフィールドをコピー(支援物資内edit_rescue)
function copyInputFieldRescue( t, max_num )
{
	var copy_area;
	var clone;

	copy_area = $("tr.rescue_item_field:last");
	clone = copy_area.clone();
	

	// 現在のボックス数を取得
	var box_count = $( "tr.rescue_item_field" ).size() + copyInputFieldRescue_rcount;

	// 上限チェック
	if ( box_count >= max_num ) {
		g_alert( "追加は" + max_num + "までです", false );
		return false;
	}

	// コピー元のテキストフィールドの値を消す
	clone.find( "input" ).val( "" );

	copy_area.after( clone );

	footerReset();

//alert( $("#content_body").html()  );
//clone.find("p").html(1);
//$("#content_body").html( "<xmp>" + clone.html());


	return false;
}

// INPUTフィールドを削除(支援物資内edit_rescue)
function deleteInputFieldRescue( t )
{
	var delete_area = $(t).parent().parent().parent().parent();
	
	if ( $( "tr.rescue_item_field" ).size() == 1 ) {
		delete_area.find("input").val("");
	}
	else {
		delete_area.remove();
	}
	footerReset();
}


/**
 * 送信前チェック(typeはカンマ区切りで複数可能)
 */
function sendBeforeCheck( type )
{
	var error_flag = true;
	var error_msg = "";
	type = "," + type + ",";

	// 会議研修案内
	if ( type.match(/,meeting,/) ) {
		if ( $("#reply_flag-1").attr("checked") == false ) {
			$.each( $("input[type=text]"), function( i ) {
				if ( $(this).attr("name").match(/^names/) && !$(this).val() ) {
					g_alert( "※" + ( i / 2 + 1 ) + "人目の出席者名を入力してください", false );
					error_flag = false;
				}
				if ( $(this).attr("name").match(/^jobs/) && !$(this).val() ) {
					g_alert( "※" + ( ( i + 1 ) / 2 ) + "人目の職種を入力してください", false );
					error_flag = false;
				}
			});
			var last_name = "";
			var check_flag = false;
			var user_no = 0;
			$.each( $("input[type=radio]"), function( i ) {
				if ( $(this).attr("name").match(/^answers\[(\d+)\]\[(\d+)\]/) ) {
					user_no = parseInt(RegExp.$1) + 1;
					if ( ( last_name && last_name != $(this).attr("name") ) || ( i == $("input[type=radio]").size()-1 ) ) {
						if ( i == $("input[type=radio]").size()-1 && $(this).attr("checked") == true ) check_flag = true;
						if ( check_flag == false ) {
							//g_alert( "※" + user_no + "人目の回答に未回答項目があります", false );
							g_alert( "※未回答項目があります", false );
							error_flag = false;
						}
						check_flag = false;
					}
					if ( $(this).attr("checked") == true ) check_flag = true;

					last_name = $(this).attr("name");
				}
			});
		}
	}
	// 支援物資(edit_rescue)
	if ( type.match(/,edit_rescue,/) ) {
		$.each( $("tr.rescue_item_field"), function( i ) {
			var item = $(this).find("input").filter(":eq(0)").val();
			if ( item ) {
				var count = $(this).find("input").filter(":eq(1)").val();
				var unit = $(this).find("input").filter(":eq(2)").val();
				count = toHalfNum( count );
				if ( !count || count.match(/[^0-9]/g) ) {
					error_flag = false;
					g_alert( "※依頼物資『"+item+"』の物資数は数値で入力してください", false ); 
				}
				if ( !unit ) {
					error_flag = false;
					g_alert( "※依頼物資『"+item+"』の単位を入力してください", false ); 
				}
			}
		});
	}
	// 宛先
	if ( type.match(/,to,/) ) {
		if ( !$("select[name=send_groups[]]").val() && !$("select[name=send_users[]]").val() && !$("select[name=to_user_id]").val() && !$("input[name=to_user_id]").val() ) {
			g_alert( "※宛先を選択してください", false );
			error_flag = false;
		}
	}
	// テキストエリア
	if ( type.match(/,body,/) ) {
		var objFCKeditor = FCKeditorAPI.GetInstance('textarea-body');

		if ( !objFCKeditor.GetHTML() ) {
			g_alert( "※内容は必ず入力してください", false );
			error_flag = false;
		}
	}
	return error_flag;
}


// 表示・非表示切り替え
function openToggle( area )
{
	$(area).toggle("fast", function() { footerReset(); } );
	return false;
}

// プルダウン追加
function addSelectItem( form, cname, sname )
{
	var c = form.elements[cname].options;
	var u = form.elements[sname].options;
	for( i = 0 ; i < c.length - 1 ; i ++ )
	{
		var co = c[i];
		if( ! co.selected || ! co.value ) continue;

		var f = false;
		var li = u.length - 1;
		for( j = 0 ; j < li ; j ++ ) { if( u[j].value == co.value ) { f = true; break; } }
		if( f ) continue;
		u[u.length] = new Option( u[li].text, "" );
		u[li] = new Option( co.text, co.value, true, true );
	}
}
// プルダウン削除
function removeSelectItem( form, sname )
{
	var u = form.elements[sname].options;
	li = u.length - 1;
	for( i = 0 ; i < li ; i ++ ) { if( u[i].selected ) { u[i] = null; li -=1; i-=1; } }
}
// プルダウン全て選択
function allSelectItem( form, sname )
{
	var u = form.elements[sname].options;
	li = u.length - 1;
	for( i = 0 ; i < li ; i ++ ) { form.elements[sname].options[i].selected = true; }
	return false;
}

// プルダウン 頭文字で絞込み
function changeInitial( form, initial )
{
	var o;
	var a = document.getElementById("CID").options;
	var len = a.length;
	var li;

	// 初期化
	for( i = 0 ; i < len - 1 ; i ++ ) { a[0] = null; }

	// 全て表示
	if ( initial == 0 ) {
		for ( s in user_initial )
		{
			for ( i in user_initial[s] )
			{
				li = a.length - 1;
				a[a.length] = new Option( a[li].text, "" );
				a[li] = new Option( user_initial[s][i], i );
				a[li].selected = true;
			}
		}
	}
	// 絞込み
	else {
		for ( i in user_initial[initial] )
		{
			li = a.length - 1;
			a[a.length] = new Option( a[li].text, "" );
			a[li] = new Option( user_initial[initial][i], i );
			a[li].selected = true;
		}
	}

	form.CID.focus();
}


// ユーザー検索フォーム初期化
function resetUserSearchForm()
{
	$("#search-area input[name=s_w]").val("");
	$("#search-area select").val( 0 );

	return false;
}



// 添付ファイル参照フォームを表示
function viewAttachFileArea( max_num )
{
	var file_count = document.getElementById('attachments').options.length - 1;
	if ( file_count >= max_num) {
		g_alert( "添付ファイルは" + max_num + "つまでです", false);
	}
	else {
		tb_show( "添付するファイルを選択", "#TB_inline?height=155&width=450&inlineId=ajax-upload-form" );
	}
	return false;
}

// IFRAMEにファイルをアップロード
function ajaxFileUpload( el )
{
	var attach_name = $("#attachment-file").val();
	if ( !attach_name ) { alert( "ファイルを参照してください" ); return false; }
	if ( !attach_name.match( attach_accept_pattern ) ) { alert( "ファイル形式が対応していません" ); return false; }

	$('#ajax_upload_form').submit();
	$('#attach-loading-area').append( '<img src="' + static_path + 'images/ajax-loader3.gif" id="attach-loading-image" />' );

	$("#attachment-file").val("");
	$("#attachment-name").val("");

	tb_remove();
}

// 添付ファイル削除
function removeAttachFile()
{
	var u = document.getElementById('attachments').options;
	var delete_count = 0;
	var li = u.length - 1;
	var attach_ids = "";

	for ( i = 0 ; i < li ; i ++ )
	{
		if( u[i].selected ) {
			attach_ids = attach_ids + u[i].value + ",";
			u[i] = null;
			li -= 1;
			i -= 1;
			delete_count++;
		}
	}
	if ( delete_count ) {
		$.post( "./attachment?action=ajax_delete_file_end", { 'attach_ids': attach_ids }, function(res)
		{
		});
		g_alert( "添付ファイルを" + delete_count + "つ削除しました" );
	}
}


/**
 * バックナンバーを一覧から消す(class=deleteをトグル)
 */
function toggleBNList(t)
{
	if ( $(t).hasClass("on") ) {
		$("tr.delete").hide();
		$(t).removeClass("on");
		$(t).addClass("off");
		$(t).html("バックナンバーを表示");
	}
	else {
		$("tr.delete").show();
		$(t).removeClass("off");
		$(t).addClass("on");
		$(t).html("バックナンバーを非表示");
	}
}


/**
 * 月間スケジュール更新
 */
function editScheduleMonth()
{
	var obj = {};

	obj.schedule_id = $("#schedule_id").val();

	obj.schedule_date_y = $("#schedule_date_y").val();
	obj.schedule_date_m = $("#schedule_date_m").val();
	obj.schedule_date_d = $("#schedule_date_d").val();

	obj.start_time_h = $("#start_time_h").val();
	obj.start_time_m = $("#start_time_m").val();
	obj.end_time_h = $("#end_time_h").val();
	obj.end_time_m = $("#end_time_m").val();

	obj.subject = $("#input-subject").val();
	obj.open_flag = $("#open-flag:checked").val();
	obj.open_flag = ( typeof( obj.open_flag ) === "undefined" ) ? 0 : 1;
	obj.body = $("#textarea-body").val();
	obj.icon = $("#form1 input[@name='icon']:checked").val();

	var update_id = "#d-" + obj.schedule_date_y + "-" + obj.schedule_date_m + "-" + obj.schedule_date_d;

	if ( !obj.subject ) {
		g_alert( "タイトルは必須です", false );
		return false;
	}

	$.post( "./schedule_month?action=ajax_schedule_update", obj, function(res)
	{
		$("#sche_load").remove();

		eval( "var xml = " + res );
		if ( xml.error ) {
			g_alert( xml.error, false );
			return false;
		}
		//$(update_id).html( xml.schedules );

		// トップページからだったら再取得
		if ( location.href.match( /aifuku\.net\/$/ ) ) {
			tb_remove();
			g_alert( xml.message );
			viewScheduleNextWeek("r");
		}
		else {
			window.location = "./schedule_month?month="+obj.schedule_date_y+"-"+obj.schedule_date_m;
		}
	});

	$(update_id).append( "<p style='text-align:center' id='sche_load'><img src='"+static_path+"images/ajax-loader3.gif' /></p>" );

	return false;
}


/**
 * 月間スケジュール削除
 */
function deleteScheduleMonth()
{
	var schedule_id = $("#schedule_id").val();
	var old_schedule_date = $("#old_schedule_date").val();
	//var schedule_date_y = $("#schedule_date_y").val();
	//var schedule_date_m = $("#schedule_date_m").val();
	//var schedule_date_d = $("#schedule_date_d").val();

	if ( !schedule_id ) return false;

	if ( confirm( "この予定を削除します。\nよろしいですか？" ) ) {
		$.post( "./schedule_month?action=ajax_schedule_delete", {"schedule_id": schedule_id, "old_schedule_date": old_schedule_date}, function(res)
		{
			eval( "var xml = " + res );

			if ( xml.error ) {
				g_alert( xml.error, false );
				return false;
			}
			// トップページからだったら再取得
			if ( location.href.match( /aifuku\.net\/$/ ) ) {
				tb_remove();
				g_alert( xml.message );
				viewScheduleNextWeek("r");
			}
			else {
				window.location = "./schedule_month?month=" + old_schedule_date.replace(/\-[0-9]+$/, "");
			}
		});
	}
	return false;
}


/**
 * トップページ週間スケジュール
 */
function viewScheduleNextWeek( range )
{
	var current_date = $("#cal-th-top").attr("title");
	//g_alert(current_date);

	$.get( "./schedule_month?action=ajax_get_schedule_week&date=" + current_date + "&range=" + range, function(res)
	{
		$("#schedule-loading-image").remove();

		eval( "var xml = " + res );

		if ( xml.error ) {
			g_alert( xml.error, false );
			return false;
		}
		$("#cal-th-top").attr("title", xml.current_date);

		var th = $("#top-calendar tr:eq(0) th");
		var td = $("#top-calendar tr:eq(1) td");
		var i = 0;
		var date_msg = "";
		var href = "";

		for ( key in xml.schedules ) {
			if ( key == "error" ) continue;

			date_msg = xml.schedules[key].day + "(" + xml.schedules[key].week + ")";

			// 月も表示
			if ( i == 0 || xml.schedules[key].day == "1" ) {
				date_msg = xml.schedules[key].month + "/" + date_msg;
			}
			th.eq(i).children(":eq(0)").html( date_msg );
			href = th.eq(i).children(":eq(1)").attr( "href" );
			th.eq(i).children(":eq(1)").attr( "href", href.replace( /date=.+?&/, "date=" + xml.schedules[key].datetime + "&" ) );

//alert(xml.schedules[key].schedule);break;
//g_alert(xml.schedules[key].datetime + "<br />" + xml.schedules[key].addClass);
			td.eq(i).html( "<div>" + xml.schedules[key].schedule + "</div>" );

			// クラス名変更
			//th.eq(i).attr( "class", xml.schedules[key].addClass );
			if ( xml.schedules[key].today ) td.eq(i).addClass( "today" );
			else td.eq(i).removeClass( "today" );

			i++;
		}
		footerReset();

		// スケジュール範囲更新
		$("#start-date-str").html( xml.start_date_str );
		$("#end-date-str").html( xml.end_date_str );

		// tooltipイベント
		$("#top-calendar a.tooltip").tooltip( {
			track: true,
   	 		delay: 0,
    		showURL: false,
			showBody: " - ",
			fade: 120
		});
		// thickboxイベント
		tb_init( "#top-calendar tr:eq(1) a.thickbox" );
	});

	$('#a-schedule').after( '<img src="' + static_path + 'images/ajax-loader4.gif" id="schedule-loading-image" />' );

	return false;
}


/**
 * 印刷ボタン
 */
function printContentPage()
{
	var url = location.href;
	var size = getPageSize();

	if ( !url.match(/\?/) ) url += "?";
	url += "&print=true&width=770&height=" + (size.height - 40) + "&TB_iframe=true&modal=1";

	tb_show("", url, "");
	return false;
}
// 印刷モード
function printerMode()
{
	$("#content").css( {"margin": "0px"} );
	$("#container").css( {"background": "#ffffff", "margin": "0px 5px 0px 5px"} );
	$("a").css({ "color": "#0000ff", "text-decoration": "underline" }).removeAttr("href");

	$("div.menu_unread").remove();
	$("#content_body_footer").remove();
	$("input[type=submit]").remove();
	$("input[type=reset]").remove();
	$("#dummy-height-area").remove();

	$("#dummy-main-area").css( {"width": "100%"} );

	$("a.smarty_wordcut").click();
	$("*").unbind();

	//$("#content_body_header div:eq(1)").remove();
}


/**
 * 文章の省略部分を全て展開
 */
function openSmartyWordcut( t, class_name )
{
	$("a."+class_name).click();
	$(t).remove();
	return false;
}



/**
 * 文字列のバイト数計算
 */
function getByte(text)
{
	count = 0;
	code = 0;
	unicode = ("｡".charCodeAt(0) == 0xFF61);
	
	for (i = 0; i < text.length; i++)
	{
		code = text.charCodeAt(i);
		//var n = escape(text.charAt(i));

		if (code < 0) { code += 0x0100; }

		if (code <= 0x7E) {
			count += 1;
		}
		else if ((!unicode && code >= 0xA1 && code <= 0xDF) || (unicode && code >= 0xFF61 && code <= 0xFF9F)) {
			count += 1;
		}
		else {
			count += 2;
		}
	}
	return count;
}
/*** End of function 'getByte' ***/






jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

//URL Encode (UTF-8)
function encodeURL(str) {
  var character = '';
  var unicode   = '';
  var string    = '';
  var i         = 0;

  for (i = 0; i < str.length; i++) {
    character = str.charAt(i);
    unicode   = str.charCodeAt(i);

    if (character == ' ') {
      string += '+';
    } else {
      if (unicode == 0x2a || unicode == 0x2d || unicode == 0x2e || unicode == 0x5f || ((unicode >= 0x30) && (unicode <= 0x39)) || ((unicode >= 0x41) && (unicode <= 0x5a)) || ((unicode >= 0x61) && (unicode <= 0x7a))) {
        string = string + character;
      } else {
        if ((unicode >= 0x0) && (unicode <= 0x7f)) {
          character   = '0' + unicode.toString(16);
          string += '%' + character.substr(character.length - 2);
        } else if (unicode > 0x1fffff) {
          string += '%' + (oxf0 + ((unicode & 0x1c0000) >> 18)).toString(16);
          string += '%' + (0x80 + ((unicode & 0x3f000) >> 12)).toString(16);
          string += '%' + (0x80 + ((unicode & 0xfc0) >> 6)).toString(16);
          string += '%' + (0x80 + (unicode & 0x3f)).toString(16);
        } else if (unicode > 0x7ff) {
          string += '%' + (0xe0 + ((unicode & 0xf000) >> 12)).toString(16);
          string += '%' + (0x80 + ((unicode & 0xfc0) >> 6)).toString(16);
          string += '%' + (0x80 + (unicode & 0x3f)).toString(16);
        } else {
          string += '%' + (0xc0 + ((unicode & 0x7c0) >> 6)).toString(16);
          string += '%' + (0x80 + (unicode & 0x3f)).toString(16);
        }
      }
    }
  }

  return string;
}


function getPageSize()
{  
    return {
        width: window.innerWidth || (document.documentElement && document.documentElement.clientWidth) || document.body.clientWidth,  
        height: window.innerHeight || (document.documentElement && document.documentElement.clientHeight) || document.body.clientHeight
    };
}


// 全角数字を半角にする
function toHalfNum(src)
{
	return src.replace(/[．０-９]/g, function (wc){var zen="．。０１２３４５６７８９",han = "..0123456789";return han[zen.indexOf(wc)];});
}





// jquery.pngFix.js
(function($) {

jQuery.fn.pngFix = function(settings) {

	// Settings
	settings = jQuery.extend({
		blankgif: 'blank.gif'
	}, settings);

	var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
	var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);

	if (jQuery.browser.msie && (ie55 || ie6)) {

		//fix images with png-source
		jQuery(this).find("img[src$=.png]").each(function() {

			jQuery(this).attr('width',jQuery(this).width());
			jQuery(this).attr('height',jQuery(this).height());

			var prevStyle = '';
			var strNewHTML = '';
			var imgId = (jQuery(this).attr('id')) ? 'id="' + jQuery(this).attr('id') + '" ' : '';
			var imgClass = (jQuery(this).attr('class')) ? 'class="' + jQuery(this).attr('class') + '" ' : '';
			var imgTitle = (jQuery(this).attr('title')) ? 'title="' + jQuery(this).attr('title') + '" ' : '';
			var imgAlt = (jQuery(this).attr('alt')) ? 'alt="' + jQuery(this).attr('alt') + '" ' : '';
			var imgAlign = (jQuery(this).attr('align')) ? 'float:' + jQuery(this).attr('align') + ';' : '';
			var imgHand = (jQuery(this).parent().attr('href')) ? 'cursor:hand;' : '';
			if (this.style.border) {
				prevStyle += 'border:'+this.style.border+';';
				this.style.border = '';
			}
			if (this.style.padding) {
				prevStyle += 'padding:'+this.style.padding+';';
				this.style.padding = '';
			}
			if (this.style.margin) {
				prevStyle += 'margin:'+this.style.margin+';';
				this.style.margin = '';
			}
			var imgStyle = (this.style.cssText);

			strNewHTML += '<span '+imgId+imgClass+imgTitle+imgAlt;
			strNewHTML += 'style="position:relative;white-space:pre-line;display:inline-block;background:transparent;'+imgAlign+imgHand;
			strNewHTML += 'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;';
			strNewHTML += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + jQuery(this).attr('src') + '\', sizingMethod=\'scale\');';
			strNewHTML += imgStyle+'"></span>';
			if (prevStyle != ''){
				strNewHTML = '<span style="position:relative;display:inline-block;'+prevStyle+imgHand+'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;'+'">' + strNewHTML + '</span>';
			}

			jQuery(this).hide();
			jQuery(this).after(strNewHTML);

		});

		// fix css background pngs
		jQuery(this).find("*").each(function(){
			var bgIMG = jQuery(this).css('background-image');
			if(bgIMG.indexOf(".png")!=-1){
				var iebg = bgIMG.split('url("')[1].split('")')[0];
				jQuery(this).css('background-image', 'none');
				jQuery(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
			}
		});
		
		//fix input with png-source
		jQuery(this).find("input[src$=.png]").each(function() {
			var bgIMG = jQuery(this).attr('src');
			jQuery(this).get(0).runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + bgIMG + '\', sizingMethod=\'scale\');';
   		jQuery(this).attr('src', settings.blankgif)
		});
	
	}
	
	return jQuery;

};

})(jQuery);



// jquery.corner.js
(function($) { 

var expr = (function() {
	if (! $.browser.msie) return false;
    var div = document.createElement('div');
    try { div.style.setExpression('width','0+0'); }
    catch(e) { return false; }
    return true;
})();
    
function sz(el, p) { 
    return parseInt($.css(el,p))||0; 
};
function hex2(s) {
    var s = parseInt(s).toString(16);
    return ( s.length < 2 ) ? '0'+s : s;
};
function gpc(node) {
    for ( ; node && node.nodeName.toLowerCase() != 'html'; node = node.parentNode ) {
        var v = $.css(node,'backgroundColor');
        if (v == 'rgba(0, 0, 0, 0)')
            continue; // webkit
        if (v.indexOf('rgb') >= 0) { 
            var rgb = v.match(/\d+/g); 
            return '#'+ hex2(rgb[0]) + hex2(rgb[1]) + hex2(rgb[2]);
        }
        if ( v && v != 'transparent' )
            return v;
    }
    return '#ffffff';
};

function getWidth(fx, i, width) {
    switch(fx) {
    case 'round':  return Math.round(width*(1-Math.cos(Math.asin(i/width))));
    case 'cool':   return Math.round(width*(1+Math.cos(Math.asin(i/width))));
    case 'sharp':  return Math.round(width*(1-Math.cos(Math.acos(i/width))));
    case 'bite':   return Math.round(width*(Math.cos(Math.asin((width-i-1)/width))));
    case 'slide':  return Math.round(width*(Math.atan2(i,width/i)));
    case 'jut':    return Math.round(width*(Math.atan2(width,(width-i-1))));
    case 'curl':   return Math.round(width*(Math.atan(i)));
    case 'tear':   return Math.round(width*(Math.cos(i)));
    case 'wicked': return Math.round(width*(Math.tan(i)));
    case 'long':   return Math.round(width*(Math.sqrt(i)));
    case 'sculpt': return Math.round(width*(Math.log((width-i-1),width)));
    case 'dog':    return (i&1) ? (i+1) : width;
    case 'dog2':   return (i&2) ? (i+1) : width;
    case 'dog3':   return (i&3) ? (i+1) : width;
    case 'fray':   return (i%2)*width;
    case 'notch':  return width; 
    case 'bevel':  return i+1;
    }
};

$.fn.corner = function(o) {
    // in 1.3+ we can fix mistakes with the ready state
	if (this.length == 0) {
        if (!$.isReady && this.selector) {
            var s = this.selector, c = this.context;
            $(function() {
                $(s,c).corner(o);
            });
        }
        return this;
	}

    o = (o||"").toLowerCase();
    var keep = /keep/.test(o);                       // keep borders?
    var cc = ((o.match(/cc:(#[0-9a-f]+)/)||[])[1]);  // corner color
    var sc = ((o.match(/sc:(#[0-9a-f]+)/)||[])[1]);  // strip color
    var width = parseInt((o.match(/(\d+)px/)||[])[1]) || 10; // corner width
    var re = /round|bevel|notch|bite|cool|sharp|slide|jut|curl|tear|fray|wicked|sculpt|long|dog3|dog2|dog/;
    var fx = ((o.match(re)||['round'])[0]);
    var edges = { T:0, B:1 };
    var opts = {
        TL:  /top|tl/.test(o),       TR:  /top|tr/.test(o),
        BL:  /bottom|bl/.test(o),    BR:  /bottom|br/.test(o)
    };
    if ( !opts.TL && !opts.TR && !opts.BL && !opts.BR )
        opts = { TL:1, TR:1, BL:1, BR:1 };
    var strip = document.createElement('div');
    strip.style.overflow = 'hidden';
    strip.style.height = '1px';
    strip.style.backgroundColor = sc || 'transparent';
    strip.style.borderStyle = 'solid';
    return this.each(function(index){
        var pad = {
            T: parseInt($.css(this,'paddingTop'))||0,     R: parseInt($.css(this,'paddingRight'))||0,
            B: parseInt($.css(this,'paddingBottom'))||0,  L: parseInt($.css(this,'paddingLeft'))||0
        };

        if (typeof this.style.zoom != undefined) this.style.zoom = 1; // force 'hasLayout' in IE
        if (!keep) this.style.border = 'none';
        strip.style.borderColor = cc || gpc(this.parentNode);
        var cssHeight = $.curCSS(this, 'height');

        for (var j in edges) {
            var bot = edges[j];
            // only add stips if needed
            if ((bot && (opts.BL || opts.BR)) || (!bot && (opts.TL || opts.TR))) {
                strip.style.borderStyle = 'none '+(opts[j+'R']?'solid':'none')+' none '+(opts[j+'L']?'solid':'none');
                var d = document.createElement('div');
                $(d).addClass('jquery-corner');
                var ds = d.style;

                bot ? this.appendChild(d) : this.insertBefore(d, this.firstChild);

                if (bot && cssHeight != 'auto') {
                    if ($.css(this,'position') == 'static')
                        this.style.position = 'relative';
                    ds.position = 'absolute';
                    ds.bottom = ds.left = ds.padding = ds.margin = '0';
                    if (expr)
                        ds.setExpression('width', 'this.parentNode.offsetWidth');
                    else
                        ds.width = '100%';
                }
                else if (!bot && $.browser.msie) {
                    if ($.css(this,'position') == 'static')
                        this.style.position = 'relative';
                    ds.position = 'absolute';
                    ds.top = ds.left = ds.right = ds.padding = ds.margin = '0';
                    
                    // fix ie6 problem when blocked element has a border width
                    if (expr) {
                        var bw = sz(this,'borderLeftWidth') + sz(this,'borderRightWidth');
                        ds.setExpression('width', 'this.parentNode.offsetWidth - '+bw+'+ "px"');
                    }
                    else
                        ds.width = '100%';
                }
                else {
                    ds.margin = !bot ? '-'+pad.T+'px -'+pad.R+'px '+(pad.T-width)+'px -'+pad.L+'px' : 
                                        (pad.B-width)+'px -'+pad.R+'px -'+pad.B+'px -'+pad.L+'px';                
                }

                for (var i=0; i < width; i++) {
                    var w = Math.max(0,getWidth(fx,i, width));
                    var e = strip.cloneNode(false);
                    e.style.borderWidth = '0 '+(opts[j+'R']?w:0)+'px 0 '+(opts[j+'L']?w:0)+'px';
                    bot ? d.appendChild(e) : d.insertBefore(e, d.firstChild);
                }
            }
        }
    });
};

$.fn.uncorner = function() { 
	$('div.jquery-corner', this).remove();
	return this;
};
    
})(jQuery);


// ページ内スクロール
(function(){

var interval = 20;
var easing = 0.6;
var comeLink = false;

var d=document,dE=d.documentElement,lH=location.hash,timer,t,p={},a=d.getElementsByTagName("a"),$h=function(hash){return document.getElementById(hash.replace("#",""));}
function cp(){return{x:d.body.scrollLeft||dE.scrollLeft,y:d.body.scrollTop||dE.scrollTop}}
function sp(t){var h=dE.clientHeight,w=dE.clientWidth,mH=dE.scrollHeight,mW=dE.scrollWidth;p.top=(mH-h)<t.offsetTop?mH-h:t.offsetTop;p.left=(mW-w)<t.offsetLeft?mW-w:t.offsetLeft;}
function np(){var x=cp().x,y=cp().y,sx=Math.ceil((x-p.left)/(5*easing)),sy=Math.ceil((y-p.top)/(5*easing));return{x:x-sx,y:y-sy,ax:sx,ay:sy}}
function scroll(){timer=setInterval(function(){np();if(Math.abs(np().ax)<1&&Math.abs(np().ay)<1){clearInterval(timer);window.scroll(p.left,p.top);}
window.scroll(np().x,np().y);},interval);}
function hs(){if(!$h(lH))return false;sp($h(lH));window.scroll(0,0);if(document.all)setTimeout(function(){scroll();},50);else scroll();}
function sus(){for(var i=0;i<a.length;i++){if(a[i].hash&&$h(a[i].hash)&&a[i].href.match(new RegExp(location.href.split("#")[0]))){a[i].onclick=function(){clearInterval(timer);sp($h(this.hash));scroll();return false;}}}}
function ae(t,l,fn){try{t.addEventListener(l,fn,false);}catch(e){t.attachEvent("on"+l,function(){fn.apply(t);});}}
if(comeLink&&lH)ae(window,"load",hs);ae(window,"load",sus);})();

