// JavaScript Document
var treeData = [];
var treeDataForArray = [];
var openNodeData = [];
var docData = [];
var docPastData = [];
var docFavoriteData = [];
var largeSummary = false;
var largeFavorite = false;
var largeContact = false;

var palettePatern = ['black','red','blue','green','purple'];
var selectFolderRidocId = '';
var searchValid = false;

$(document).ready(function(){
	ajaxLoadingCreate();
	
	window.name = "D290";


	$('#startDate').mask('9999/99/99');
	$('#startDate').datepicker({dateFormat:'yy/mm/dd'});
	$("#startDate").datepicker("option", "showOn", 'button');
	$("#startDate").datepicker("option", "buttonImageOnly", true);
	$("#startDate").datepicker("option", "buttonImage", '../webnais/pilot/scripts/datepicker.png');
	$('#endDate').mask('9999/99/99');
	$('#endDate').datepicker({dateFormat:'yy/mm/dd'});
	$("#endDate").datepicker("option", "showOn", 'button');
	$("#endDate").datepicker("option", "buttonImageOnly", true);
	$("#endDate").datepicker("option", "buttonImage", '../webnais/pilot/scripts/datepicker.png');
	$("img[class='ui-datepicker-trigger']").each(function(){ 
		$(this).attr('style', 'position:relative; top:3px; left:3px;');
	});

	$('.chbFileType').prop('checked',false);
	$('#rdoKikanKbn_4').prop('checked',true);
	$('#startDate').prop('disabled',true);
	$('#endDate').prop('disabled',true);
	$("img[class='ui-datepicker-trigger']").hide();
	
	$('#dialogSearchOption').dialog({
		autoOpen: false,
		title: "検索オプション",
		closeOnEscape: false,
		width: 500,
		modal: true,
		open: function() {
			$('#searchTextDialog1').val($('#searchText1').val());
			$('#searchTextDialog2').val($('#searchText2').val());
			$('#searchTextDialog3').val($('#searchText3').val());
			$('#searchTextDialog4').val($('#searchText4').val());
		},
		buttons: [
			{
		        text:'全ﾌｫﾙﾀﾞﾁｪｯｸ',
				class:'left',
				click: function(event){
					$('.chbFileType').each(function(){
						$(this).prop('checked',true);
					});
				}
    		},
			{
		        text:'全ﾌｫﾙﾀﾞ解除',
				class:'left',
				click: function(event){
					$('.chbFileType').each(function(){
						$(this).prop('checked',false);
					});
				}
    		},
			{
		        text:'この条件で検索',
				class:'SearchButton',
				click: function(event){
					$('#searchText1').val($('#searchTextDialog1').val());
					$('#searchText2').val($('#searchTextDialog2').val());
					$('#searchText3').val($('#searchTextDialog3').val());
					$('#searchText4').val($('#searchTextDialog4').val());
					createDocTable('zenbun','','','','');
					if( searchValid ){
						$(this).dialog("close");
					}
				}
    		}
		]
	});

	$('input[name="rdokikanKbn"]').change(function(){
		if($(this).val() === ""){
			$('#startDate').prop('disabled',false);
			$('#endDate').prop('disabled',false);
			$("img[class='ui-datepicker-trigger']").show();
		}else {
			$('#startDate').val("");
			$('#endDate').val("");
			$('#startDate').prop('disabled',true);
			$('#endDate').prop('disabled',true);
			$("img[class='ui-datepicker-trigger']").hide();
		}
	});

    if( $('#newArrivalKbn').val() == '1'){
		createDocTable('shinchaku',0,0,0);
	}else{
		createTreeTable();
	}

	$('#dialogDocDetail').dialog({
		autoOpen: false,
		title: "発刊文書の詳細",
		closeOnEscape: false,
		width: $('body').width() * 0.78,
		height: $('body').height() * 0.5,
		modal: true,
		open: function() {
			setTimeout(function(){
				$('.ui-dialog-buttonset button:eq(2)').focus();
			},0);
		},
		buttons: {
	        '閉じる': function(){
				$(this).dialog("close");
			}
    	}
	});

	$('.searchText').blur(function(){
		if( $(this).val() == '' ){
			$(this).addClass('defaultKeyWord')
		}
	});

	$('.searchText').focus(function(){
		if( $(this).hasClass('defaultKeyWord') ){
			$(this).val('');
			$(this).removeClass('defaultKeyWord')
		}
	});

	$('#btnSearchDoc').click(function(){
		createDocTable('zenbun','','','','');
	});

	if( $('#infoLibraryKbn').val() == '1' ){
		$('#btnCategorySearch').hide();
	}

	$('#searchText2').hide();
	$('#searchText3').hide();
	$('#searchText4').hide();

	$('#spanAnd1').hide();
	$('#spanAnd2').hide();
	$('#spanAnd3').hide();

	$('#searchText1').css('width','420px');

	$('#searchTextDialog1').change(function(){
		$('#searchText1').val($(this).val())
		setSearchTextWidth()
	});

	$('#searchTextDialog2').change(function(){
		if( $(this).val() == '' ){
			$('#spanAnd1').hide();
			$('#searchText2').hide();
		}else{
			$('#spanAnd1').show();
			$('#searchText2').show();
		}
		$('#searchText2').val($(this).val())
		setSearchTextWidth()
	});

	$('#searchTextDialog3').change(function(){
		if( $(this).val() == '' ){
			$('#spanAnd2').hide();
			$('#searchText3').hide();
		}else{
			$('#spanAnd2').show();
			$('#searchText3').show();
		}
		$('#searchText3').val($(this).val())
		setSearchTextWidth()
	});

	$('#searchTextDialog4').change(function(){
		if( $(this).val() == '' ){
			$('#spanAnd3').hide();
			$('#searchText4').hide();
		}else{
			$('#spanAnd3').show();
			$('#searchText4').show();
		}
		$('#searchText4').val($(this).val())
		setSearchTextWidth()
	});

	ajaxLoadingDelete();

});

function createTreeTable(){
	var retXML = getTreeData();
	treeData = cmXmlToTreeData(retXML,'line');
	treeDataForArray = cmXmlToArray(retXML,'line');

	$('#treeMenu').tree({
		data:treeData,
		closedIcon:'images/migisankaku.png',
		openedIcon:'images/sitasankaku.png',
		
	});

	$('#treeMenu').on('tree.click',function(event){
		var node = event.node;
		selectFolderRidocId = node.ridocID;

		$('.chbFileType').each(function(){
			if( $(this).attr('data-Cd') == node.typeID ){
				$(this).prop('checked',true)
			}else{
				$(this).prop('checked',false)
			}
		});

		createDocTable('tuujo',node.nodeLevel,node.nodeNo,'')
	});

	getOpenNodeIDs();
	if( openNodeData.length > 0 ){
		openNode();
	}else{
		$('#treeMenu > ul > li > div > a').click();
		createDocTable('tuujo',0,0,'','なし');
	}

}

function getTreeData(){
	var param = {
		'appname':'NAIS3WEB',
		'prgname':'D291',
		'ssid': $('#ssid').val(),
		'infoLibraryKbn': $('#infoLibraryKbn').val(),
		'arguments':'ssid,infoLibraryKbn'
	};
	var xmlData = cmGetXmlData(param);
	if( $(xmlData).find('message').text() !== '' ){
		alert($(xmlData).find('message').text());
	}
	return xmlData;
}

function createDocTable(tableKbn,nodeLevel,nodeNo,folderRidocId){
	$('#divAjax').show();
	setTimeout(function(){

		var docXml
		if( tableKbn == 'zenbun' ){
			$('#spnSearchStr').text(createSearchStr(tableKbn));
			docXml = searchZenbun();
		}else if( tableKbn == 'shinchaku' ){
			docXml = getNewArrivalDoc();
		}else{
			$('#spnSearchStr').text(createSearchStr(tableKbn));
			docXml = getPublishDoc(nodeLevel,nodeNo);
		}

		var tableID = "";
		switch( $(docXml).find('ret').text() ){
			case 'I001':
				var lineTag = [];
				lineTag[0] = 'line';
				
				var subLineTag = [];
				subLineTag[0] = 'detailLine';

				var createData = cmXmlToArray(docXml,'line');

				docData = createData;
				tableID = 'tblReportList';
				break;
			case 'S001':
			case 'E002':
				tableID = 'tblReportList';
				createData = [];
				break;
			case 'E001':
				ExecPgm('W040');
				break;
		}

		if(tableID !== ""){
			$('#' + tableID ).empty();
			var html = '';
			if( createData.length <= 0 ){
				html = html + '<tr style="height: 24px;">';
				html = html + '<td align="center" width="50px" nowrap>&nbsp</td>';
				html = html + '<td align="left" width="120px" nowrap>&nbsp</td>';
				html = html + '<td align="left" nowrap>' + $(docXml).find('message').text() + '</td>';
				html = html + '<td align="left" width="120px" nowrap>&nbsp</td>';
				html = html + '</tr>';
			}else{
				for( var i = 0; i < createData.length; i++ ){
					var lineData = createData[i];
					html = html + '<tr style="height: 24px;">';
					html = html + '<td align="center" width="50px" nowrap>&nbsp</td>';
					html = html + '<td align="left" width="120px" nowrap>';
					html = html + '<img src="../webnais/images/downloadfile.png" style="position:relative;top:2px"><a href="#" style="color:' + lineData.titleColor +'" class="hrefFile" id="href' + String(i) + '" data-ridocID="' + lineData.ridocID + '" data-i="' + String(i) + '">' + lineData.fileNo +'</a>';
					html = html + '</td>';
					html = html + '<td id="titleTd' + String(i) +'" style="color:' + lineData.titleColor +'" align="left">' + lineData.fileTitle + '</td>';
					html = html + '<td id="hassinTd' + String(i) +'" align="left" style="color:' + lineData.titleColor +'" width="120px" nowrap>' + lineData.hassinDate + '</td>';
					html = html + '</tr>';
				}
			}
			$('#' + tableID ).append(html);

			$('.hrefFile').on(
				'click',
				function(){
					var docKind = $(this).attr('data-kind');
					var docNo = $(this).attr('data-no');
					var ridcoID = $(this).attr('data-ridocID');
					var dataNum = $(this).attr('data-i');

					$(this).css('color','#000000');
					$('#titleTd' + dataNum).css('color','#000000');
					$('#hassinTd' + dataNum).css('color','#000000');

					/*
					window.open("/Magic33Scripts/MGrqispi.dll?APPNAME=NAIS3WEB&PRGNAME=D220&ARGUMENTS=-ANAIS3WEB,-A" + $('#ssid').val() + ",-A" + docKind + ",-A" + docNo,
								   "",'toolbar=0,directories=0,status=1,resizable=1,scrollbars=1,menubar=0,left=100,top=60,width=800,height=500,');
								   */
					window.open("","ファイル",'toolbar=0,directories=0,status=1,resizable=1,scrollbars=1,menubar=0,left=100,top=60,width=800,height=500');
					$('#windowForm').attr('target','ファイル');
					$('#Wprgname').val('D293');
					$('#w_param1').val('ANAIS3WEB');
					$('#w_param2').val($('#ssid').val());
					$('#w_param3').val(ridcoID);
					$('#w_param4').val('');
					$('#w_param5').val('');
					$('#w_param6').val('');
					$('#w_param7').val('');
					$('#w_param8').val('');
					$('#w_param9').val('');
					$('#w_param10').val('');
					$('#windowForm').submit();
					$('#windowForm').attr('target','_self');

				}
			);

		}
		$('#divAjax').hide();
	},0);
}

function getNewArrivalDoc(){
	var param = {
		'appname':'NAIS3WEB',
		'prgname':'D299',
		'ssid': $('#ssid').val(),
		'arguments':'ssid'
	};
	var xmlData;
	$.ajax({
		async : false,
		url: ajaxURL,
		data : param,
		dataType:'xml',
		scriptCharset: 'utf-8',
		success : function(xml){
			$('#ssid').val($(xml).find('ssid').text());	
			xmlData = xml;
		},
		error : function(XMLHttpRequest, textStatus, errorThrown){
				cmAjaxError(XMLHttpRequest, textStatus, errorThrown);
		}
	});
	//var xmlData = cmGetXmlData(param);
	return xmlData;
}

function getPublishDoc(nodeLevel,nodeNo){
	var param = {
		'appname':'NAIS3WEB',
		'prgname':'D292',
		'ssid': $('#ssid').val(),
		'nodeNo': nodeNo,
		'nodeLevel': nodeLevel,
		'arguments':'ssid,nodeNo,nodeLevel'
	};
	var xmlData;
	$.ajax({
		async : false,
		url: ajaxURL,
		data : param,
		dataType:'xml',
		scriptCharset: 'utf-8',
		success : function(xml){
			$('#ssid').val($(xml).find('ssid').text());	
			xmlData = xml;
		},
		error : function(XMLHttpRequest, textStatus, errorThrown){
				cmAjaxError(XMLHttpRequest, textStatus, errorThrown);
		}
	});
	//var xmlData = cmGetXmlData(param);
	return xmlData;
}

function searchZenbun(){

	searchValid = true;

	var paraFileTypeFlag = '0';
	var paraDateFlag = '0';

	var paraFileType = '';
	var paraSearchWord = '';
	var paraStartDate = '';
	var paraEndDate = '';

	if( !$('#searchText1').val() == '' ){
		paraSearchWord = paraSearchWord + '@' + $('#searchText1').val();
	}

	if( !$('#searchText2').val() == '' ){
		paraSearchWord = paraSearchWord + '@' + $('#searchText2').val();
	}

	if( !$('#searchText3').val() == '' ){
		paraSearchWord = paraSearchWord + '@' + $('#searchText3').val();
	}

	if( !$('#searchText4').val() == '' ){
		paraSearchWord = paraSearchWord + '@' + $('#searchText4').val();
	}

	if( paraSearchWord !== '' ){
		paraSearchWord = paraSearchWord.substring(1);
	}

	$('.chbFileType').each(function(){
		if( $(this).prop('checked') ){
			paraFileType = paraFileType + '@' + $(this).attr('data-Cd');
		}
	});
	if( paraFileType !== '' ){
		paraFileType = paraFileType.substring(1);
		paraFileTypeFlag = 1;
	}

	if($('input[name="rdokikanKbn"]:checked').val() === ""){
		paraStartDate = $('#startDate').val();
		paraEndDate = $('#endDate').val();
	}else {
		paraStartDate = $('input[name="rdokikanKbn"]:checked').val();
		paraEndDate = '9999/12/31';
	}
	
	var validMsg = '';

	if( paraSearchWord === "" ){
		validMsg = validMsg + 'キーワードを1つ以上指定してください。' + '<br>';
	}

	if(paraFileType === ""){
		validMsg = validMsg + '全文検索するフォルダを選択してください。' + '<br>';
	}
/*
	if(paraFileType.indexOf('@') !== -1){
		validMsg = validMsg + 'フォルダは１つのみの選択としてください。' + '<br>';
	}
	if(paraFileType.length > 49){
		validMsg = validMsg + 'フォルダの選択は１０フォルダまでとしてください。' + '<br>';
	}
*/
	if(paraStartDate === "" && paraEndDate === ""){
		validMsg = validMsg + '期間が指定されていません。' + '<br>';
	}
	if(paraStartDate > paraEndDate){
		validMsg = validMsg + '期間の指定は開始日＜終了日となるように入力してください。' + '<br>';
	}

	var xmlData = '';
	if(validMsg === ""){
		var param = {
			'appname':'NAIS3WEB',
			'prgname':'D296',
			'ssid': $('#ssid').val(),
			'searchText': paraSearchWord,
			'folderRidocID': paraFileType,
			'paraFileType': paraFileType,
			'paraStartDate': paraStartDate,
			'paraEndDate': paraEndDate,
			'arguments':'ssid,searchText,folderRidocID,paraFileType,paraStartDate,paraEndDate'
		};
		xmlData = cmGetXmlData(param);
	}else {
		searchValid = false;
		cmAlert('エラー',validMsg);
	}
	//var xmlData = cmGetXmlData(param);
	return xmlData;
}
function gotoCategorySearch(){
	$('#prgname').val('D260');
	$('#menuForm').submit();
}

function createSearchStr(tableKbn){
	var searchStr = 'フォルダ：';

	var fileTypeStr = '';
	var fileTypeCheck = 0;
	$('.chbFileType').each(function(){
		if($(this).prop('checked')){
			fileTypeStr = fileTypeStr + ',' + $('label[for="'+$(this).attr('id')+'"]').text();
		}else {
			fileTypeCheck = 1;
		}
	});
	
	if(fileTypeStr !== ''){
		if(fileTypeCheck === 0){
			fileTypeStr = '全て';
		}else {
			fileTypeStr = fileTypeStr.substring(1);
		}
		searchStr = searchStr + fileTypeStr;
	}else{
		searchStr = searchStr + 'なし';
	}
	
	if( tableKbn == 'zenbun' ){
		var KikanStr = '';
		if($('input[name="rdokikanKbn"]:checked').val() === ""){
			KikanStr = $('#startDate').val() + ' ～ ' + $('#endDate').val();
		}else {
			KikanStr = $('label[for="'+$('input[name="rdokikanKbn"]:checked').attr('id')+'"]').text();
		}
		searchStr = searchStr + '  期間：' + KikanStr;
		
	}
	return searchStr;
}
function openSearchOption(){
	$('#dialogSearchOption').dialog('open');
}

function setSearchTextWidth(){
	var searchTextNum = 1;
	if ($('#searchText2').css('display') != 'none') {
		searchTextNum = searchTextNum + 1;
	}
	if ($('#searchText3').css('display') != 'none') {
		searchTextNum = searchTextNum + 1;
	}
	if ($('#searchText4').css('display') != 'none') {
		searchTextNum = searchTextNum + 1;
	}

	$('#searchText1').css('width',String(420 / searchTextNum) + 'px')
	$('#searchText2').css('width',String(420 / searchTextNum) + 'px')
	$('#searchText3').css('width',String(420 / searchTextNum) + 'px')
	$('#searchText4').css('width',String(420 / searchTextNum) + 'px')

}

function getOpenNodeIDs(){

	var parentNodeNo = '0';
	
	openNodeData = []

	$.each(treeDataForArray,function(index,row){
		if(row.ridocID == $('#hidInitialRidocID').val()){
			openNodeData.push(row.nodeNo);
			parentNodeNo = row.parentNodeNo
			return false;
		}
	});

	while (parentNodeNo != '0'){
		parentNodeNo = '0'
		$.each(treeDataForArray,function(index,row){
			if(row.nodeNo == parentNodeNo){
				openNodeData.push(row.nodeNo);
				parentNodeNo = row.parentNodeNo
				return false;
			}
		});
	}
	
	return true;
}

function openNode(){
	var i = 0;
	var nodeObj
	for(i=openNodeData.length - 1;i==0; i--){
		nodeObj = $('#treeMenu').tree('getNodeById', openNodeData[i]);
		$('#treeMenu').tree('openNode', nodeObj);
	}
	$('#treeMenu').tree('selectNode', nodeObj);
	$('.jqtree-selected > div').click();
}
