/**
 * mplus_mobile_clinic
 */
var mplus_mobile_clinic = function(){
	//상속
	mplus_common.call(this);
	var mplusPatient = new mplus_mobile_patient();
	var mplusNursing = new mplus_nursing();
	
	//super
	var self = this;
	
	//변수
	var div = $('<div></div>');
	var tr = $('<tr></tr>');
	var th = $('<th></th>');
	var td = $('<td></td>');
	var table = $('<table></table>');
	var li = $('<li></li>');
	var a = $('<a></a>');
	var span = $('<span></span>');
	var button = $('<button></button>');
	
	var deptList = new Array(); 
	var wardList = new Array();
	
	var requestToServer = true;
	var searchedPatientList = [];
	
	self.hospital.getDeptList('D', function(result) {deptList = result});
	self.hospital.getDeptList('W', function(result) {wardList = result});
	
	/**
	 * 초기화
	 */
	this.init = function(){ //여기서 모든화면 콤보박스데이터를 집어넣자!!! 그래야지 화면이동할때 속도가 오래걸리지않음!!!
		inInitDataSetting();		
		outInitDataSetting();
		searchInitDataSetting();
		inAddEvent();
		inInit();
		inSearchPatientList();
		
		outAddEvent();
		emerAddEvent();
		searchAddEvent();
		$('#clinicTab a[data-toggle="tab"]').unbind();
		$('#clinicTab a[data-toggle="tab"]').on('click', function (e) {
			/*if($('#overlay').css('bottom')=='-49px'){*/
				$('#openToggle').css({bottom:10}); //에니메이션을 넣으니 화면이  이동된후에 에니메이션 동작이 되어서 css만변경
				$('#overlay').stop().animate({bottom:-290},500);
				$('#nursingPopup').stop().animate({bottom:-max},500);
				$('#newPopupFooter').css('display', 'none');
				$('#patientList').css('margin-bottom', '0');
				$('#searchPatientList').css('margin-bottom', '0');
				$('#openToggle').removeClass('on');
				$('#openToggle').find('.fa').removeClass('fa-chevron-down');
				$('#openToggle').find('.fa').addClass('fa-chevron-up');
			/*}*/
		});
		$('#clinicTab a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
			$('.tab-pane').scrollTop(0);
			patientInfoInit();
			if($("ul#clinicTab.nav-tabs li.active a").attr('aria-controls')=='tabIn'){
				inInit();
				inSearchPatientList();
			}else if($("ul#clinicTab.nav-tabs li.active a").attr('aria-controls')=='tabOut'){
				outInit();
				outSearchPatientList();
			}else if($("ul#clinicTab.nav-tabs li.active a").attr('aria-controls')=='tabEmer'){
				emerInit();
				emerInitDataSetting();
				emerSearchPatientList();
			}else if($("ul#clinicTab.nav-tabs li.active a").attr('aria-controls')=='tabSearch'){
				searchInit();
			}else{
				/*slef.aler('에러메시지?');*/
			}
		});
		localStorage.setItem('treatType', treatType);
	};
	
	var patientInfoInit = function(){
		$('#divId').text('');
		$('#divDiagName').text('');
		$('#divOpName').text('');
		$('#divOpDate').text('');
		$('#divTreatDate').text('');
		$('#divDoctorName').text('');
		
		$('#tdNameNum').text('');
		//로컬스토리지 정보는 없애야할지 테스트헤보고 넣기! 
	};
	
	/*----------------------- 입원 resource  ----------------------*/
	var $inTotalNumSpan = $('#inTotalNumSpan'),
	 	$inRoundBtn = $('#inRoundBtn'),
	 	$inInsertBtn = $('#inInsertBtn'),
	 	$rountInsertBtn = $('#rountInsertBtn'),
	 	$inSearchBtn = $('#inSearchBtn'),
	 	$inUlPatientList = $('#inUlPatientList'),
	 	$inSltDept = $('#inSltDept'),
	 	$inChkTotalView = $('#inChkTotalView'), 
	 	$inBtnSortOpen  = $('#inBtnSortOpen'),
	 	$inPidSearch  = $('#inPidSearch');
	
	var inRecentSearchType, //최근 검색했던 전체, 본인 여부(정렬시 필요)
		inPatientList = [];
	
	var inInit = function(){
		treatType = 'I';
		$inPidSearch.val('');
		requestToServer = true;
		searchedPatientList = [];
		// TODO: 전문의 & 강사일 때만 회진 기능 이용할 수 있도록 구현하기
		var jobKindCd = JSON.parse(localStorage.user).jobKindCd;
		$('#inChkTotalView').prop('checked', true);
		
		if(jobKindCd=='S' || jobKindCd=='G'){ //jobKindCd: S(전문의), G(강사)
			$inRoundBtn.css('display', 'initial');
			$('#roundBtnWrap').css('display', 'initial');
			if(jobKindCd=='S'){
				$('#inChkTotalView').prop('checked', false);
			}
		}else{
			$inRoundBtn.css('display', 'none');
			$('#roundBtnWrap').css('display', 'none');
		}
		
		var sortList = [{key: 'wardNm', type: 'string',  value: '병동순'},
		            {key: 'age', type: 'number', value: '연령순'},
		            {key: 'patientNm', type: 'string', value: '이름순'}];
		inRecentSearchType = '';
		inPatientList = [];
		$inSltDept.val(localStorage.selectDeptCode);
		$inTotalNumSpan.text(0);
		$inUlPatientList.empty();
		sortInit(sortList);
		$('#sortConfirmBtn').unbind();
		$('#sortConfirmBtn').on("click", function(e){
			$('#sortModal').modal('hide');
			inSortPatientList($('#sltSort').val(), $('#sltSort option:selected').attr('type'), $('input[type="radio"][name="sortRadio"]:checked').val());
			
			$('.header span').css('display', 'none');
			$('.header.sort_'+$('#sltSort').val()+' .sort-icon-'+$('input[type="radio"][name="sortRadio"]:checked').val()).css('display', 'inline-block');
		});
		
		// 태블릿일 때는 회진 체크박스를 맨 앞으로 배치한다
		if( self.isTablet() ) {
			$('#inPatientHeaderTablet').css('display', 'block');
			$('#inPatientHeaderPhone').css('display', 'none');
		}else{
			$('#inPatientHeaderTablet').css('display', 'none');
			$('#inPatientHeaderPhone').css('display', 'block');
		}
	};
	/**
	 * 이벤트등록
	 */
	var inAddEvent = function(){
		$inRoundBtn.on('click', function(e){
			if( self.isTablet() ) {
				$('#roundAllChkBoxWrapTablet').css('display', 'block');
			}else{
				$('#roundAllChkBoxWrapPhone').css('display', 'block');
							
				$('.in-date-wrap').removeClass('pdr0').addClass('pd0');
				$('.bed-wrap').removeClass('col-xs-5').addClass('col-xs-4');
				$('.patientNm-wrap').removeClass('col-xs-4').addClass('col-xs-5');
				$('.doctor-wrap').removeClass('col-xs-4').removeClass('pd0').addClass('col-xs-3').addClass('pdr0');
			}
			$('.chk-box-wrap').css('display', 'block');
			$('.empty-wrap').css('display', 'none');
			$inRoundBtn.css('display', 'none');
			$inInsertBtn.css('display', 'initial');
			$('#roundAllChkBox').prop('checked', true).trigger('change');
		});
		$inInsertBtn.on('click', function(e){
			if($('[id*=check_]:checked').length==0){
				self.alert('환자를 선택해주세요.');
				return;
			};
			$('#dateRound')[0].value = self.util.toDate(new Date());
			$('#timeRound')[0].value = '--:--';
			$('#roundMemo').text('환자 및 보호자분은 질문사항을 미리 준비해 주시고 병실에서 대기하여 주시기 바랍니다.');
			
			$('#modalRoundInsert').modal('show');
		});
		$rountInsertBtn.on('click', function(e){
			//회진시간입력 로직 호출
			var currentTime = new Date();
			currentTime.setSeconds(00);
			
			if($('#dateRound').val()=='' || $('#timeRound').val()==''){
				self.alert('회진시간을 입력해주세요.');
				return;
			}
			var roundTime = new Date($('#dateRound').val() +' '+ $('#timeRound').val());
			
			if(currentTime.getTime() - roundTime.getTime() > 0){
				self.alert('회진시간은 현재시간 이후로 설정해주세요.');
				return;
			}
			var patientInfo = JSON.parse(localStorage.user);
			
			var selectPatientList = [];
			var executeRoundFailList = [];
			var param = {'round': []};
			
			for(var i=0; i<$('[id*=check_]:checked').length; i++){
				var commentMsg = '';
				if(patientInfo.hospitalCd=='10'){
					commentMsg = '<강남세브란스병원 회진안내>\n';		
				}else{
					commentMsg = '<세브란스병원 회진안내>\n'; 
				}
				
				commentMsg = commentMsg 
							+ moment(currentTime).format('MM월 DD일') +' '+ $('#inSltDept option:selected').text() + ' ' + patientInfo.userNm + '선생님 '
							+ self.util.restoreRoundTime($('#timeRound').val()) + '부터 회진 예정입니다. \n'
							+ '<전달사항>\n'
							+ $('#roundMemo').val().replace( /\r?\n/g, "\n" );

				var roundPatientInfo = {
						 'hospitalCd': localStorage.hospitalCd,
						 //'patientId': $('[id*=check_]:checked')[i].value,	// 20180622 shinsunwoo value 가 "ALL"로 나오는 오류로 수정
						 'patientId': inPatientList[$('[id*=check_]:checked')[i].id.split('_')[1]].patientId,
						 'inputDt': moment(currentTime).format('YYYYMMDD'),
						 'inputTm': moment(currentTime).format('HHmm00'),
						 'roundTreatMemo': commentMsg, 
						 'roundTreatDt': moment($('#dateRound').val()).format('YYYYMMDD'),
						 'roundTreatTm': $('#timeRound').val().replace(':', '')+'00', 
						 'departmentCd': inPatientList[$('[id*=check_]:checked')[i].id.split('_')[1]].departmentCd, 
						 'userId': patientInfo.userId};
				
				selectPatientList.push(inPatientList[$('[id*=check_]:checked')[i].id.split('_')[1]]);
				param.round.push(roundPatientInfo);
			}
			//실패 케이스 처리
			var executeRoundTreatResult = self.treatment.executeRoundTreat(param);
			if( executeRoundTreatResult.result == undefined ){
				$('#modalRoundInsert').modal('hide');
				self.alert(executeRoundTreatResult.msg);
				return;
			} 
			executeRoundTreatResult = executeRoundTreatResult.result;
			
			for(var j=0; j<executeRoundTreatResult.length; j++){
				if(executeRoundTreatResult[j].returnCd=='1'){
					for(var k=0; k<selectPatientList.length; k++){
						if(executeRoundTreatResult[j].patientId == selectPatientList[k].patientId){
							var failData = selectPatientList[k];
							executeRoundFailList.push({'patientId': failData.patientId, 'patientNm': failData.patientNm});
							break;
						}
					}
				}
			}
			
			if(executeRoundFailList.length>0){
				var alertMsg = '';
				
				$('#modalRoundInsert').modal('hide');
				$('[id*=check_]').prop('checked', false);
				for(var j=0; j<executeRoundFailList.length; j++){
					$('[id*=check_][value='+executeRoundFailList[j].patientId+']').prop('checked', true);
					alertMsg = alertMsg + executeRoundFailList[j].patientId + ' / ' + executeRoundFailList[j].patientNm + '<br/>';
				}
				alertMsg = alertMsg + '환자 회진정보 입력 실패하였습니다.';
				self.alert(alertMsg);
			}else{
				$inRoundBtn.css('display', 'initial');
				$inInsertBtn.css('display', 'none');
				$('#modalRoundInsert').modal('hide');
				
				self.alert('환자 회진정보가 입력되었습니다.');
				
				$('#roundAllChkBoxWrapPhone').css('display', 'none');
				$('#roundAllChkBoxWrapTablet').css('display', 'none');
				$('.chk-box-wrap').css('display', 'none');
				$('.empty-wrap').css('display', 'block');
				
				if(!self.isTablet()){
					$('.in-date-wrap').removeClass('pd0').addClass('pdr0');
					$('.bed-wrap').removeClass('col-xs-4').addClass('col-xs-5');
					$('.patientNm-wrap').removeClass('col-xs-5').addClass('col-xs-4');
					$('.doctor-wrap').removeClass('col-xs-3').removeClass('pdr0').addClass('col-xs-4').addClass('pd0');
				}
			}
		});
		$inSearchBtn.on('click', function(e){
			$('.header span').css('display', 'none');
			// 검색조건(진료과, 본인or전체) 변동사항이 없고, 환자번호 검색어가 입력된경우
		    // 서버로 따로 요청하지 않고 이미 받은 데이터에서 환자번호 필터링만 한다.
			if( !requestToServer && $inPidSearch.val().length > 0) {
				inPatientList = searchedPatientList.filter(val => {return val.patientId.indexOf($inPidSearch.val()) >= 0;});
				inBindingPatientList(inRecentSearchType, inPatientList, null);
			} /*else if (!requestToServer && $inPidSearch.val().length == 0) {
				inPatientList = searchedPatientList;
				inBindingPatientList(inRecentSearchType, inPatientList, null);
			} */else {
				inSearchPatientList();
			}
		});
		$inBtnSortOpen.on("click", function(e){
			$('#sortModal').modal('show');
		});
		$inPidSearch.on('click', function(e){
			e.currentTarget.value = '';
		});
		$inSltDept.on('change', function(e){
			requestToServer = true;
		});
	 	$inChkTotalView.on('change', function(e){
	 		requestToServer = true;
	 	});
	};
	
	/**
	 * 기초데이터 셋팅
	 */
	var inInitDataSetting = function(){
/*		var sltList = deptList.concat(wardList); */
		var deptList = JSON.parse(localStorage.user).departmentList;
		var sltList = deptList; 
		$inSltDept.empty();
		for(var i=0; i<sltList.length; i++){
			option = $('<option></option>').clone().attr('value', sltList[i].departmentCd)
													.attr('departmentTyp', sltList[i].departmentTyp)
													.text(sltList[i].departmentNm);
			$inSltDept.append(option);
		}
	};
	
	var inSearchPatientList = function(){
		inRecentSearchType = $inChkTotalView.prop('checked')? 'all': 'mine';
		$inUlPatientList.empty();
		inPatientList = [];
		patientInfoInit();
					
		//과별, 병동별 입원환자 조회
		if($inChkTotalView.prop('checked')){
			var type = $('#inSltDept option[value='+$('#inSltDept').val()+']').attr('departmentTyp');
			var param;
			if(type=='D'){
				param = {
						departmentCd: $inSltDept.val()
						};
			}else{
				param = {
						wardCd: $inSltDept.val()
						};
			}
			self.treatment.getInPatListPerDeptOrWard(param, 'all', 'in');
			/*bindingPatientList('all', patientList);*/
		//과,병동 & 의사별 입원환자 조회
		}else{
			var type = $('#inSltDept option[value='+$('#inSltDept').val()+']').attr('departmentTyp');
			var param;
			if(type=='D'){
				param = {
						departmentCd: $inSltDept.val(), 
						doctorId: loginUserId
						};
			}else{
				param = {
						wardCd: $inSltDept.val(),
						doctorId: loginUserId
						};
			}
			self.treatment.getInPatListPerDDOrWD(param, 'mine');
			/*patientList = self.treatment.getInPatListPerDDOrWD(param);
			bindingPatientList('mine', patientList);*/
		}
	};
	
	var inSortPatientList = function(key, type, method){
		inPatientList = self.util.sortObj(inPatientList, key, type, method);
		inBindingPatientList(inRecentSearchType, inPatientList, null);
	};
	
	inBindingPatientList = function(type, bindPatientList, extraMsg){ //all: 전체, mine: 본인
		if( $inPidSearch.val().length > 0 ) {
			inPatientList = bindPatientList.filter(val => {return val.patientId.indexOf($inPidSearch.val()) >= 0;});
		} else {
			inPatientList = bindPatientList;
		}
		
		if( requestToServer ) {
			searchedPatientList = bindPatientList;
			requestToServer = false;
		}
		
		if(!self.isTablet()){
			$('.in-date-wrap').removeClass('pd0').addClass('pdr0');
			$('.bed-wrap').removeClass('col-xs-4').addClass('col-xs-5');
			$('.patientNm-wrap').removeClass('col-xs-5').addClass('col-xs-4');
			$('.doctor-wrap').removeClass('col-xs-3').removeClass('pdr0').addClass('col-xs-4').addClass('pd0');
		}
		
		$inUlPatientList.empty();
		$inTotalNumSpan.text(inPatientList.length);
		if(inPatientList.length==0){
			$inUlPatientList.append(li.clone().append(div.clone().addClass('text-center no-result').text('―')));
		}
		$inRoundBtn.css('display', 'initial');
		$inInsertBtn.css('display', 'none');
		
		$('#roundAllChkBoxWrapPhone').css('display', 'none');
		$('#roundAllChkBoxWrapTablet').css('display', 'none');
		
		for(var i=0; i<inPatientList.length; i++){
			var divPatientInfo = div.clone().addClass('list-row container');
			if( self.isTablet() ) {
				var div12Row1 = div.clone().addClass('col-xs-12 col-sm-12 pd0');
				var divNum = div.clone().addClass('col-xs-2 col-sm-2 sexage').append(
						span.clone().text( (inPatientList[i].gender=='F'? 'F':'M') + ' / '+ inPatientList[i].age )
				);
				
				var divDay = div.clone().addClass('day col-xs-2 col-sm-2 pdr0 bed-wrap ').text(inPatientList[i].wardNm + '/' + inPatientList[i].roomNm + '/' + inPatientList[i].bedNm);
				var divName = div.clone().addClass('name col-xs-2 col-sm-2 pd0 patientNm-wrap').text(inPatientList[i].patientNm + ' ' + inPatientList[i].patientId);
				
				var checkbox = $('<input type="checkbox" value="ALL" checked=""><label for=""></label>').attr('id', 'check_' + i).attr('for', 'check_' + i);
				var divRound = div.clone().addClass('num_b checkbox3 checkbox-sm checkbox-check checkbox-light col-xs-1 col-sm-1 pdr0 chk-box-wrap').append(checkbox);
				var divDoctor = div.clone().addClass('doctor col-xs-2 col-sm-2 pd0 doctor-wrap').text(inPatientList[i].departmentCd + ' / ' + inPatientList[i].doctorNm);
				var divDate = div.clone().addClass('date col-xs-3 col-sm-3 pdr0 in-date-wrap letter-control').text((inPatientList[i].inDt!=undefined&&inPatientList[i].inDt!=null&&inPatientList[i].inDt!=''? moment(inPatientList[i].inDt).format('YYYY-MM-DD'):'') 
																									+ ' HOD ' 
																									+ inPatientList[i].inDay);
				
				var divFirstRow = div12Row1.clone().append(divRound).append(divDay).append(divDate).append(divName).append(divNum).append(divDoctor);
				
				divPatientInfo.append(divFirstRow);
			} else {
				var div12Row1 = div.clone().addClass('col-xs-12 col-sm-8 pd0');
				var div12Row2 = div.clone().addClass('col-xs-12 col-sm-4 pd0');
				var divNum = div.clone().addClass('col-xs-3 col-sm-2 sexage').append(
						span.clone().text( (inPatientList[i].gender=='F'? 'F':'M') + ' / '+ inPatientList[i].age )
				);
				
				var divDay = div.clone().addClass('day col-xs-5 col-sm-3 pdr0 bed-wrap').text(inPatientList[i].wardNm + '/' + inPatientList[i].roomNm + '/' + inPatientList[i].bedNm);
				var divName = div.clone().addClass('name col-xs-4 col-sm-5 pd0 patientNm-wrap').text(inPatientList[i].patientNm + ' ' + inPatientList[i].patientId);
				var divEmpty = div.clone().addClass('clearfix visible-xs-block').text(' ');
				
				var checkbox = $('<input type="checkbox" value="ALL" checked=""><label for=""></label>').attr('id', 'check_' + i).attr('for', 'check_' + i);
				var divRound = div.clone().addClass('num_b checkbox3 checkbox-sm checkbox-check checkbox-light col-xs-4 col-sm-2 pdr0 chk-box-wrap').append(checkbox);
				var divEmpty1 = div.clone().addClass('doctor col-xs-3 hidden-sm hidden-md hidden-lg empty-wrap').text('');
				var divDoctor = div.clone().addClass('doctor col-xs-4 col-sm-5 pd0 doctor-wrap').text(inPatientList[i].departmentCd + ' / ' + inPatientList[i].doctorNm);
				var divDate = div.clone().addClass('date col-xs-5 col-sm-5 pdr0 in-date-wrap letter-control').text((inPatientList[i].inDt!=undefined&&inPatientList[i].inDt!=null&&inPatientList[i].inDt!=''? moment(inPatientList[i].inDt).format('YYYY-MM-DD'):'') 
																									+ ' HOD ' 
																									+ inPatientList[i].inDay);
				
				var divFirstRow = div12Row1.clone().append(divDay).append(divName).append(divNum);
				var divSecondRow = div12Row2.clone().append(divRound).append(divDate).append(divDoctor).append(divEmpty).append(divEmpty1);
				divPatientInfo.append(divFirstRow).append(divSecondRow);
				$('#inDateWrap').before($('#roundAllChkBoxWrapPhone'));
			}			
			$inUlPatientList.append(li.clone().append(a.clone().addClass('list-group-item').attr('patientNo', i).attr('patientId', inPatientList[i].patientId).append(divPatientInfo)));
			
			$('.chk-box-wrap').css('display', 'none');
			
			$('#roundAllChkBox').unbind();
			$('#roundAllChkBox').on('change', function(e){
				$('[id*=check_]').prop('checked', e.currentTarget.checked);
			});
		};
		
		$('#inUlPatientList .list-group-item').on('click',function(){
			if(event.toElement.id.indexOf('check')>-1){
				return;
			}
			
			$('.list-group-item').removeClass('active');
			$(this).addClass('active');
			
			var patientNo = event.currentTarget.attributes.patientNo.value;
			var patientInfo = inPatientList[patientNo];
			patientInfo.treatDt=patientInfo.inDt;
			patientInfo.treatTyp=treatType;
			localStorage.setItem('patientInfo', JSON.stringify(patientInfo));
							
			$('#nursingPopup  [id*=popContent]').removeClass('in');
			$('#nursingPopup  #popContentNursingRecode').addClass('in');
			if(!$('#openToggle').is('.on')){
				$('#nursingRecodeTab.nav-tabs a[href="#tabInfo"]').tab('show');
			}else{
				mplusNursing.reInit($("ul#nursingRecodeTab.nav-tabs li.active a").attr('aria-controls'));
			}
			$('#newPopupFooter').css('display', 'block');
			/*$('#nursingPopup').css('display', 'block');*/
			
			$('.list-group-item').removeClass('active');
			$(this).addClass('active');

			// 선택한 환자의 스크롤 위치 구하기
			var pos = $('#tabIn').scrollTop() + $('#inUlPatientList li a.list-group-item[patientno='+patientNo+']').offset().top;
			
			$('#patientList').css('margin-bottom', '100vh');
			
			if( self.isTablet() ) {
				// 적절한 위치로 이동
				$('#tabIn').animate({scrollTop: pos - 150}, 500); 
				$('#nursingPopup').height(max2-245);
				$('#nursingPopup .tab-content .tab-pane').height(max2-317);
				$('#openToggle').stop().animate({bottom: wh-280 },500);
			}else{
				// 적절한 위치로 이동
				$('#tabIn').animate({scrollTop: pos - 77}, 500);
				$('#nursingPopup').height(max2-105);
				$('#nursingPopup .tab-content .tab-pane').height(max2-177);
				$('#openToggle').stop().animate({bottom: wh-140 },500);
			}
			$('#openToggle').addClass('on');
			$('#openToggle').find('.fa').removeClass('fa-chevron-up');
			$('#openToggle').find('.fa').addClass('fa-chevron-down');
			$('#nursingPopup').stop().animate({bottom:0},500);
			$('#nursingPopup').css({'display': 'block'});
			mplusNursing.init();
			
			var patientInfo = inPatientList[event.currentTarget.attributes.patientNo.value];
			patientInfo.treatTyp=treatType;
			localStorage.setItem('patientInfo', JSON.stringify(patientInfo));
			
			var param = {
						hospitalCd: localStorage.hospitalCd,
						patientId: patientInfo.patientId
						};
			var patientInfoData = self.nursing.getPatientInfo(param);
			bindingPatientDetail(patientInfo, patientInfoData);
			// 다음이벤트 (환자리스트가 아닌 화면영역을 클릭했을 때 토글 내려가게 하는 기능) 동작을 막기 위함
			return false;
		});
	};
	
	/*----------------------- 입원 resource 종료 ----------------------*/
	
	/*----------------------- 외래 resource ----------------------*/
	var $outTotalNumSpan = $('#outTotalNumSpan'), 
		$outSearchDate = $('#outSearchDate'), 
		$outSearchBtn = $('#outSearchBtn'), 
		$outUlPatientList = $('#outUlPatientList'), 
		$outBtnSortOpen = $('#outBtnSortOpen'),
		$outSltDept = $('#outSltDept'),
		$outSltDoctor = $('#outSltDoctor'),
		$outPidSearch = $('#outPidSearch');
	
	var outRecentSearchType, //최근 검색했던 전체, 본인 여부(정렬시 필요)
		outPatientList = [];
	
	var treatType = '';
	var outInit = function(){
		treatType = 'O';
		$outPidSearch.val('');
		requestToServer = true;
		searchedPatientList = [];
		$outSearchDate.val(moment(new Date()).format('YYYY-MM-DD'));
		var sortList = [{key: 'age', type: 'number', value: '연령순'},
		            {key: 'patientNm', type: 'string', value: '이름순'}, 
		            {key: 'treatTm', type: 'number', value: '진료시간순'}];
		outRecentSearchType = '';
		outPatientList = [];
		$outSltDept.val(localStorage.selectDeptCode).trigger('change');
		if($outSltDept.val()==null){
			$outSltDept[0].selectedIndex = 0;
		}
		$outTotalNumSpan.text(0);
		$outUlPatientList.empty();
		sortInit(sortList);
		$('#sortConfirmBtn').unbind();
		$('#sortConfirmBtn').on("click", function(e){
			$('#sortModal').modal('hide');
			outSortPatientList($('#sltSort').val(), $('#sltSort option:selected').attr('type'), $('input[type="radio"][name="sortRadio"]:checked').val());
			
			$('.header span').css('display', 'none');
			$('.header.sort_'+$('#sltSort').val()+' .sort-icon-'+$('input[type="radio"][name="sortRadio"]:checked').val()).css('display', 'inline-block');
		});

		$('#outChkTotalView').prop('checked', true);
		
		if(jobKindCd=='S'){
			$('#outChkTotalView').prop('checked', false);
			$('#outSltDoctor').val(JSON.parse(localStorage.user).userId);
			if($('#outSltDoctor').val()==null) $('#outSltDoctor').val(' '); 
		}
	};
	
	var outAddEvent = function() {
		$outSearchBtn.on("click", function(e) {
			$('.header span').css('display', 'none');			
			// 검색조건(진료과, 진료의, 진료일) 변동사항이 없고, 환자번호 검색어가 입력된경우
		    // 서버로 따로 요청하지 않고 이미 받은 데이터에서 환자번호 필터링만 한다.
			if( !requestToServer && $outPidSearch.val().length > 0) {
				outPatientList = searchedPatientList.filter(val => {return val.patientId.indexOf($outPidSearch.val()) >= 0;});
				outBindingPatientList(outPatientList, null);
			} else {
				outSearchPatientList();
			}
		});
		$outBtnSortOpen.on("click", function(e){
			$('#sortModal').modal('show');
		});
		$outSltDept.on("change", function(e){
			if( e.currentTarget.value == '' ) return;
			var doctorList = self.hospital.getDoctorList({
				departmentCd: e.currentTarget.value
			});
			$outSltDoctor.empty();
			var totalOption = $('<option></option>').clone().attr('value', ' ').text('전체');
			$outSltDoctor.append(totalOption);
			
			for(var i=0; i<doctorList.length; i++){
				var option = $('<option></option>').clone().attr('value', doctorList[i].doctorId).text(doctorList[i].doctorNm);
				$outSltDoctor.append(option);
			}
		});
		$outPidSearch.on('click', function(e){
			e.currentTarget.value = '';
		});
		$outSearchDate.on('change', function(e){
			requestToServer = true;
		}); 
		$outSltDept.on('change', function(e){
			requestToServer = true;
		});
		$outSltDoctor.on('change', function(e){
			requestToServer = true;
		});
	};
	
	var outInitDataSetting = function(){
		var deptList = JSON.parse(localStorage.user).departmentList;
		var userJobKindCd  = JSON.parse(localStorage.user).jobKindCd;
		var sltList = deptList;
		
		$outSltDept.empty();
		for(var i=0; i<sltList.length; i++){
			if(!(userJobKindCd=='N' && sltList[i].departmentTyp=='W')){
				option = $('<option></option>').clone().attr('value', sltList[i].departmentCd)
				.text(sltList[i].departmentNm);
				$outSltDept.append(option);
			}
		}
	};

	var outSearchPatientList = function() {
		if($outSearchDate.val()==''){
			self.alert('조회 일자를 입력해주세요.');
			return;
		}
		$outUlPatientList.empty();
		outPatientList = [];
		
		patientInfoInit();
		
		//과별 외래환자 조회
		if($outSltDoctor.val().trim() == ''){
			var param;
				param = {
						treatDt: moment($outSearchDate.val()).format('YYYYMMDD'), 
						departmentCd: $outSltDept.val()
						};
			self.treatment.getOutPatList(param, 'out');
		}else{
			//전체해제, 진료과&병동선택
			var param;
			param = {
					treatDt: moment($outSearchDate.val()).format('YYYYMMDD'), 
					departmentCd: $outSltDept.val(), 
					doctorId: $outSltDoctor.val()
					};
			self.treatment.getOutPatList(param, 'out');
		}
	};
	
	var outSortPatientList = function(key, type, method){
		var sortPatientList = self.util.sortObj(outPatientList, key, type, method);
		outBindingPatientList(sortPatientList, null);
	};
	
	outBindingPatientList = function(bindPatientList, extraMsg){ //all: 전체, mine: 본인
		if( $outPidSearch.val().length > 0 ) {
			outPatientList = bindPatientList.filter(val => {return val.patientId.indexOf($outPidSearch.val()) >= 0;});
		} else {
			outPatientList = bindPatientList;
		}
		if( requestToServer ) {
			searchedPatientList = bindPatientList;
			requestToServer = false;
		}
		
		$outUlPatientList.empty();

		$outTotalNumSpan.text(outPatientList.length);
		if(outPatientList.length==0){
			$outUlPatientList.append(li.clone().append(div.clone().addClass('text-center no-result').text('―')));
		}
	
		for(var i=0; i<outPatientList.length; i++){
			var divTime = div.clone().addClass('day col-xs-3 col-sm-3').text(outPatientList[i].treatTm!=''?(outPatientList[i].treatTm.substr(0,2)+':'+outPatientList[i].treatTm.substr(2,2)+':'+outPatientList[i].treatTm.substr(4,2)):'');
			var divName = div.clone().addClass('name col-xs-6 col-sm-6').text(outPatientList[i].patientNm + ' ' + outPatientList[i].patientId);
			var divNum = div.clone().addClass('num_3 col-xs-3 col-sm-3').text(outPatientList[i].gender + ' / ' + outPatientList[i].age);
			
			var divReserveTime = div.clone().addClass('day col-xs-3 hidden-sm').text('');
			var divDoctor = div.clone().addClass('doctor col-xs-6 col-sm-6').text(outPatientList[i].departmentCd + ' / '+ outPatientList[i].doctorNm);
			var divStatus = div.clone().addClass('col-xs-3 col-sm-3').text(outPatientList[i].treatStat);
							
			var divRow1 = div.clone().addClass('list-row container').append(div.clone().addClass('col-xs-12 col-sm-6 pd0').append(divTime).append(divName).append(divNum));
			var divRow2 = div.clone().addClass('col-xs-12 col-sm-6 pd0').append(divReserveTime).append(divDoctor).append(divStatus);
			
			var divRow = a.clone().addClass('list-group-item').attr('patientNo', i).attr('patientId', outPatientList[i].patientId).append(divRow1.append(divRow2));
			// 퇴실사유가 있는경우 아래에 출력한다.
			if(outPatientList[i].outRsn != undefined && outPatientList[i].outRsn != '' && outPatientList[i].outRsn != '') {
				var divOutReasonWrap = div.clone().addClass('list-row container');
				var divOutReason = div.clone().addClass('col-xs-9 col-sm-10').append($("<strong></strong>").text("퇴실사유: ")).append(span.clone().text(outPatientList[i].outRsn));
				divOutReasonWrap.append(div.clone().addClass('col-xs-3 col-sm-2')).append(divOutReason);
				divRow.append(divOutReasonWrap);
			}
			
			$outUlPatientList.append(li.clone().append(divRow));
		}
		
		$('#outPatientList .list-group-item').on('click',function(){
			if(event.toElement.id.indexOf('check')>-1){
				return;
			}
			
			$('.list-group-item').removeClass('active');
			$(this).addClass('active');
			
			var patientNo = event.currentTarget.attributes.patientNo.value;
			var patientInfo = outPatientList[patientNo];
			patientInfo.treatDt=patientInfo.treatDt;
			patientInfo.treatTyp=treatType;
			localStorage.setItem('patientInfo', JSON.stringify(patientInfo));
							
			$('#nursingPopup  [id*=popContent]').removeClass('in');
			$('#nursingPopup  #popContentNursingRecode').addClass('in');
			if(!$('#openToggle').is('.on')){
				$('#nursingRecodeTab.nav-tabs a[href="#tabInfo"]').tab('show');
			}else{
				mplusNursing.reInit($("ul#nursingRecodeTab.nav-tabs li.active a").attr('aria-controls'));
			}
			$('#newPopupFooter').css('display', 'block');
			/*$('#nursingPopup').css('display', 'block');*/
			
			$('.list-group-item').removeClass('active');
			$(this).addClass('active');

			// 선택한 환자의 스크롤 위치 구하기
			var pos = $('#tabOut').scrollTop() + $('#outUlPatientList li a.list-group-item[patientno='+patientNo+']').offset().top;
			
			$('#outPatientList').css('margin-bottom', '100vh');
			
			if( self.isTablet() ) {
				// 적절한 위치로 이동
				$('#tabOut').animate({scrollTop: pos - 150}, 500); 
				$('#nursingPopup').height(max2-245);
				$('#nursingPopup .tab-content .tab-pane').height(max2-317);
				$('#openToggle').stop().animate({bottom: wh-280 },500);
			}else{
				// 적절한 위치로 이동
				$('#tabOut').animate({scrollTop: pos - 77}, 500);
				$('#nursingPopup').height(max2-105);
				$('#nursingPopup .tab-content .tab-pane').height(max2-177);
				$('#openToggle').stop().animate({bottom: wh-140 },500);
			}
			$('#openToggle').addClass('on');
			$('#openToggle').find('.fa').removeClass('fa-chevron-up');
			$('#openToggle').find('.fa').addClass('fa-chevron-down');
			$('#nursingPopup').stop().animate({bottom:0},500);
			$('#nursingPopup').css({'display': 'block'});
			mplusNursing.init();
						
			var param = {
						hospitalCd: localStorage.hospitalCd,
						patientId: patientInfo.patientId
						};
			var patientInfoData = self.nursing.getPatientInfo(param);
			bindingPatientDetail(patientInfo, patientInfoData);
			// 다음이벤트 (환자리스트가 아닌 화면영역을 클릭했을 때 토글 내려가게 하는 기능) 동작을 막기 위함
			return false;
			
			
			/*$('.list-group-item').removeClass('active');
			$(this).addClass('active');
			$('#openToggle').stop().animate({bottom:240},500);
			$('#overlay').stop().animate({bottom:-49},500);
			$(this).addClass('active');
			$('#footer').css('overflow','visible');
			$('#openToggle').addClass('on');
			$('#openToggle').find('.fa').removeClass('fa-chevron-up');
			$('#openToggle').find('.fa').addClass('fa-chevron-down');
			
			var patientInfo = outPatientList[event.currentTarget.attributes.patientNo.value];
			localStorage.setItem('patientInfo', JSON.stringify(patientInfo));
			
			var param = {
						patientId: patientInfo.patientId,
						departmentCd: patientInfo.departmentCd,
						treatTyp: treatType,
						treatDt: patientInfo.treatDt};
			self.patient.getTreatInfo(param);*/
		});
	};
	/*----------------------- 외래 resource 종료 ----------------------*/
	
	/*----------------------- 응급 resource  ----------------------*/
	var $emerTotalNumSpan = $('#emerTotalNumSpan'),
	 	$emerSearchBtn = $('#emerSearchBtn'),
	 	$emerUlPatientList = $('#emerUlPatientList'),
	 	$emerBtnSortOpen  = $('#emerBtnSortOpen'),
	 	$emerSltDept = $('#emerSltDept'),
	 	$emerPidSearch = $('#emerPidSearch');
	
	var emerPatientList = []; 
	
	var emerInit = function(){
		treatType = 'E';
		$emerPidSearch.val('');
		requestToServer = true;
		var sortList = [{key: 'age', type: 'number', value: '연령순'},
		            {key: 'patientNm', type: 'string', value: '이름순'}];
		emerPatientList = [];
		$emerUlPatientList.empty();
		$emerTotalNumSpan.text(0);
		sortInit(sortList);
		$('#sortConfirmBtn').unbind();
		$('#sortConfirmBtn').on("click", function(e){
			$('#sortModal').modal('hide');
			emerSortPatientList($('#sltSort').val(), $('#sltSort option:selected').attr('type'), $('input[type="radio"][name="sortRadio"]:checked').val());
			
			$('.header span').css('display', 'none');
			$('.header.sort_'+$('#sltSort').val()+' .sort-icon-'+$('input[type="radio"][name="sortRadio"]:checked').val()).css('display', 'inline-block');
		});
	};
	/**
	 * 이벤트등록
	 */
	var emerAddEvent = function(){
		$emerSearchBtn.on('click', function(e){
			$('.header span').css('display', 'none');
			// 검색조건(진료과) 변동사항이 없고, 환자번호 검색어가 입력된경우
		    // 서버로 따로 요청하지 않고 이미 받은 데이터에서 환자번호 필터링만 한다.
			if( !requestToServer && $emerPidSearch.val().length > 0) {
				emerPatientList = searchedPatientList.filter(val => {return val.patientId.indexOf($emerPidSearch.val()) >= 0;});
				emerBindingPatientList(emerPatientList, null);
			} else {
				emerSearchPatientList();
			}
		});
		$emerBtnSortOpen.on("click", function(e){
			$('#sortModal').modal('show');
		});
		$emerPidSearch.on('click', function(e){
			e.currentTarget.value = '';
		});
		$emerSltDept.on('change', function(e){
			requestToServer = true;
		}); 
	};
	
	/**
	 * 기초데이터 셋팅
	 * 20180727 shinsunwoo 전체 옵션의 기본값을 'A'로 지정
	 */
	var emerInitDataSetting = function(){
		var sltList = deptList; 
		$('#emerSltDept').empty();
		var totalOption = $('<option></option>').clone().attr('value', 'A')
				.text('전체');
		$('#emerSltDept').append(totalOption);

		for(var i=0; i<sltList.length; i++){
			option = $('<option></option>').clone().attr('value', sltList[i].departmentCd)
													.text(sltList[i].departmentNm);
			$('#emerSltDept').append(option);
		}
		$('#emerSltDept').val('A');
	};
	
	var emerSearchPatientList = function(){
		$emerUlPatientList.empty();
		emerPatientList = [];
		
		patientInfoInit();
		
		var param = {
					departmentCd: $('#emerSltDept').val()==null? ' ': $('#emerSltDept').val()
				};
		self.treatment.getErPatList(param, 'all');
		/*bindingPatientList('all', patientList);*/
	};
	
	var emerSortPatientList = function(key, type, method){
		emerPatientList = self.util.sortObj(emerPatientList, key, type, method);
		emerBindingPatientList(emerPatientList, null);
	};
	
	emerBindingPatientList = function(bindPatientList, extraMsg){ //all: 전체
		if( $emerPidSearch.val().length > 0 ) {
			emerPatientList = bindPatientList.filter(val => {return val.patientId.indexOf($emerPidSearch.val()) >= 0;});
		} else {
			emerPatientList = bindPatientList;
		}
		if( requestToServer ) {
			searchedPatientList = bindPatientList;
			requestToServer = false;
		}
		$emerUlPatientList.empty();
		
		$emerTotalNumSpan.text(emerPatientList.length);
		if(emerPatientList.length==0){
			$emerUlPatientList.append(li.clone().append(div.clone().addClass('text-center no-result').text('―')));
		}
	
		for(var i=0; i<emerPatientList.length; i++){
			var divWard = div.clone().addClass('col-xs-4 col-sm-5 pdr0 letter-control').text(emerPatientList[i].wardNm + '/' + emerPatientList[i].roomNm + '/' + emerPatientList[i].bedNm);
			var divName = div.clone().addClass('name col-xs-5 col-sm-4 pd0').text(emerPatientList[i].patientNm + ' ' + emerPatientList[i].patientId);
			var divNum = div.clone().addClass('num_3 col-xs-3 col-sm-3 pdr0').text(emerPatientList[i].gender +' / '+ emerPatientList[i].age);
			
			var divDay = div.clone().addClass('day col-xs-4 col-sm-4 pdr0').text(Math.floor(emerPatientList[i].elapsedTm/60) + '시간 ' + (emerPatientList[i].elapsedTm%60) + '분');
			var divDoctor = div.clone().addClass('doctor col-xs-5 col-sm-4 pd0').text(emerPatientList[i].departmentCd + ' / ' + emerPatientList[i].doctorNm);
			var divDate = div.clone().addClass('date col-xs-3 col-sm-4 pdr0 letter-control').text(emerPatientList[i].treatDt!=undefined&&emerPatientList[i].treatDt!=null&&emerPatientList[i].treatDt!=''? moment(emerPatientList[i].treatDt).format('YYYY-MM-DD'):'');
						
			var divPatientInfo1 = div.clone().addClass('list-row container').append(div.clone().addClass('col-xs-12 col-sm-7 pd0').append(divWard).append(divName).append(divNum));
			var divPatientInfo2 = div.clone().addClass('col-xs-12 col-sm-5 pd0').append(divDay).append(divDoctor).append(divDate);
			
			var divRow = a.clone().addClass('list-group-item').attr('patientNo', i).attr('patientId', emerPatientList[i].patientId).append(divPatientInfo1.append(divPatientInfo2));
			// 퇴실사유가 있는 경우 아래에 출력해준다.
			if(emerPatientList[i].outRsn != undefined && emerPatientList[i].outRsn != '' && emerPatientList[i].outRsn != '') {
				var divOutReasonWrap = div.clone().addClass('list-row container');
				var divOutReason = div.clone().addClass('col-xs-9 col-sm-10').append($("<strong></strong>").text("퇴실사유: ")).append(span.clone().text(emerPatientList[i].outRsn));
				divOutReasonWrap.append(div.clone().addClass('col-xs-3 col-sm-2')).append(divOutReason);
				divRow.append(divOutReasonWrap);
			}
			$emerUlPatientList.append(li.clone().append(divRow));
		}
		$('#emerPatientList .list-group-item').on('click',function(){
			if(event.toElement.id.indexOf('check')>-1){
				return;
			}
			
			$('.list-group-item').removeClass('active');
			$(this).addClass('active');
			
			var patientNo = event.currentTarget.attributes.patientNo.value;
			var patientInfo = emerPatientList[patientNo];
			patientInfo.treatDt=patientInfo.treatDt;
			patientInfo.treatTyp=treatType;
			localStorage.setItem('patientInfo', JSON.stringify(patientInfo));
							
			$('#nursingPopup  [id*=popContent]').removeClass('in');
			$('#nursingPopup  #popContentNursingRecode').addClass('in');
			if(!$('#openToggle').is('.on')){
				$('#nursingRecodeTab.nav-tabs a[href="#tabInfo"]').tab('show');
			}else{
				mplusNursing.reInit($("ul#nursingRecodeTab.nav-tabs li.active a").attr('aria-controls'));
			}
			$('#newPopupFooter').css('display', 'block');
			/*$('#nursingPopup').css('display', 'block');*/
			
			$('.list-group-item').removeClass('active');
			$(this).addClass('active');

			// 선택한 환자의 스크롤 위치 구하기
			var pos = $('#tabEmer').scrollTop() + $('#emerUlPatientList li a.list-group-item[patientno='+patientNo+']').offset().top;
			
			$('#emerPatientList').css('margin-bottom', '100vh');
			
			if( self.isTablet() ) {
				// 적절한 위치로 이동
				$('#tabEmer').animate({scrollTop: pos - 150}, 500); 
				$('#nursingPopup').height(max2-245);
				$('#nursingPopup .tab-content .tab-pane').height(max2-317);
				$('#openToggle').stop().animate({bottom: wh-280 },500);
			}else{
				// 적절한 위치로 이동
				$('#tabEmer').animate({scrollTop: pos - 77}, 500);
				$('#nursingPopup').height(max2-105);
				$('#nursingPopup .tab-content .tab-pane').height(max2-177);
				$('#openToggle').stop().animate({bottom: wh-140 },500);
			};
			$('#openToggle').addClass('on');
			$('#openToggle').find('.fa').removeClass('fa-chevron-up');
			$('#openToggle').find('.fa').addClass('fa-chevron-down');
			$('#nursingPopup').stop().animate({bottom:0},500);
			$('#nursingPopup').css({'display': 'block'});
			mplusNursing.init();
						
			var param = {
						hospitalCd: localStorage.hospitalCd,
						patientId: patientInfo.patientId
						};
			var patientInfoData = self.nursing.getPatientInfo(param);
			bindingPatientDetail(patientInfo, patientInfoData);
			// 다음이벤트 (환자리스트가 아닌 화면영역을 클릭했을 때 토글 내려가게 하는 기능) 동작을 막기 위함
			return false;
			
			/*$('.list-group-item').removeClass('active');
			$(this).addClass('active');
			$('#openToggle').stop().animate({bottom:240},500);
			$('#overlay').stop().animate({bottom:-49},500);
			$(this).addClass('active');
			$('#footer').css('overflow','visible');
			$('#openToggle').addClass('on');
			$('#openToggle').find('.fa').removeClass('fa-chevron-up');
			$('#openToggle').find('.fa').addClass('fa-chevron-down');
			
			var patientInfo = emerPatientList[event.currentTarget.attributes.patientNo.value];
			localStorage.setItem('patientInfo', JSON.stringify(patientInfo));
			
			var param = {
						patientId: patientInfo.patientId,
						departmentCd: patientInfo.departmentCd,
						treatTyp: treatType,
						treatDt: patientInfo.treatDt};
			self.patient.getTreatInfo(param);*/
		});
	};
	
	/*----------------------- 응급 resource 종료 ----------------------*/
	
	/*----------------------- 검색 resource  ----------------------*/
	var $searchSearchBtn = $('#searchSearchBtn'),
		$searchSearchDate = $('#searchSearchDate'),
	 	$searchUlPatientList = $('#searchUlPatientList'),
	 	$searchSearchConditionUpper = $('#searchSearchConditionUpper'),
	 	$searchSearchConditionLower = $('#searchSearchConditionLower'),
	 	$searchSearchConditionType = $('#searchSearchConditionType'); 
	
	var searchPatientList = []; 
	
	var searchInit = function(){
		treatType = 'S';
		$searchSearchDate.val(moment(new Date()).format('YYYY-MM-DD'));
		$('input[type="radio"][name="plist-search"][value="treat"]').prop('checked', true);
		searchSearchTypeChange('treat');
		var sortList = [{key: 'wardNm', type: 'string',  value: '병동순'},
		            {key: 'age', type: 'number', value: '연령순'},
		            {key: 'patientNm', type: 'string', value: '이름순'}];
		searchPatientList = [];
		$searchUlPatientList.empty();
		sortInit(sortList);
		
		if( self.isTablet() ){
			$('#searchPatientHeaderPhone').css('display', 'none');
			$('#searchPatientHeaderTablet').css('display', 'block');
		}else{
			$('#searchPatientHeaderPhone').css('display', 'block');
			$('#searchPatientHeaderTablet').css('display', 'none');
		}
	}
	/**
	 * 이벤트등록
	 */
	var searchAddEvent = function(){
		$searchSearchBtn.on("click", function(e){
			searchSearchPatientList();
		});
		/*$searchRecentSearchBtn.on("click", function(e){
			searchSearchPatientList();
		});*/
		$('input[type="radio"][name="plist-search"]').on('change', function(e) {
			patientInfoInit();
			searchSearchTypeChange(e.currentTarget.value);
		});
		$('input[type="radio"][name="treatment"]').on('change', function(e) {
			$searchUlPatientList.empty();
		    searchPatientList = [];
		    patientInfoInit();
			if(e.currentTarget.value=='in'){
				$searchSearchDate.attr('readonly', true);
				$('.treat-header').text('입원일');
			}else{
				$searchSearchDate.val(moment(new Date()).format('YYYY-MM-DD'));
				$searchSearchDate.attr('readonly', false);
				$('.treat-header').text('진료일');
			}
		});
	};
	
	/**
	 * 기초데이터 셋팅
	 */
	var searchInitDataSetting = function(){
	};
	
	/**
	 * 검색 상태변경 이벤트
	 */
	var searchSearchTypeChange = function(type){
		$searchSearchConditionUpper.empty();
	    $searchSearchConditionLower.empty();
	    $searchUlPatientList.empty();
	    searchPatientList = [];
	    var conditionUpper;
	    var conditionLower;
	    if(type == 'treat'){
	    	$searchSearchConditionUpper.attr('class', 'col-xs-5 pdr5');
	    	$searchSearchConditionLower.attr('class', 'col-xs-5 pdl5');
	    	
	    	conditionUpper = $('<select></select>').clone().addClass('form-control').attr('id', 'searchSltDept');
	    	for(var i=0; i<deptList.length; i++){
	    		option = $('<option></option>').clone().attr('value', deptList[i].departmentCd)
				.text(deptList[i].departmentNm);
	    		conditionUpper.append(option);
	    	}
	    	
	    	conditionLower = $('<select></select>').clone().addClass('form-control').attr('id', 'search_sltDoctor');
	    	$searchSearchConditionType.css('display', 'block');
	    	
		    $searchSearchConditionUpper.html(conditionUpper);
		    $searchSearchConditionLower.html(conditionLower);
	    	
	    	$('#searchSltDept').change(function(e) {
				var doctorList = self.hospital.getDoctorList({
																departmentCd: e.currentTarget.value
																});
				$('#search_sltDoctor').empty();
				
				for(var i=0; i<doctorList.length; i++){
		    		option = $('<option></option>').clone().attr('value', doctorList[i].doctorId)
					.text(doctorList[i].doctorNm);
		    		conditionLower.append(option);
		    	}
		    	
		    	$searchSearchConditionLower.html(conditionLower);
			});
	    	$('#searchSltDept').change();
	    	$('input[type="radio"][name="treatment"][value="in"]').prop("checked", true);
	    	$searchSearchDate.val(moment(new Date()).format('YYYY-MM-DD'));
			$searchSearchDate.attr('readonly', true);
	    	
	    }else if(type == 'hospital'){
	    	$searchSearchConditionUpper.attr('class', 'col-xs-5 pdr5');
	    	$searchSearchConditionLower.attr('class', 'col-xs-5 pdl5');
	    	
	    	conditionUpper = $('<select></select>').clone().addClass('form-control').attr('id', 'search_sltWard');
	    	for(var i=0; i<wardList.length; i++){
	    		option = $('<option></option>').clone().attr('value', wardList[i].departmentCd)
				.text(wardList[i].departmentNm);
	    		conditionUpper.append(option);
	    	}
	    	
	    	conditionLower = $('<select></select>').clone().addClass('form-control').attr('id', 'searchSltDept');
	    	
	    	for(var i=0; i<deptList.length; i++){
	    		option = $('<option></option>').clone().attr('value', deptList[i].departmentCd)
				.text(deptList[i].departmentNm);
	    		conditionLower.append(option);
	    	}
	    		    	
	    	$searchSearchConditionType.css('display', 'none');

		    $searchSearchConditionUpper.html(conditionUpper);
		    $searchSearchConditionLower.html(conditionLower);
	    }else{
	    	$searchSearchConditionUpper.attr('class', 'col-xs-5 pdr5');
	    	$searchSearchConditionLower.attr('class', 'col-xs-5 pdl5');
	    	conditionUpper = 
				$('<select></select>').clone().addClass('form-control').attr('id', 'search_sltPatientCondition').append(
					$('<option></option>').clone().attr('value', 'name').text('환자명')
				).append(
					$('<option></option>').clone().attr('value', 'num').text('등록번호')
				);
	    	
	    	conditionLower = 
	    		$('<input></input>').clone().addClass('form-control').attr('type', 'text').attr('placeholder', '검색').attr('id', 'search_txtSrData');
	    	
	    	$searchSearchConditionType.css('display', 'none');

		    $searchSearchConditionUpper.html(conditionUpper);
		    $searchSearchConditionLower.html(conditionLower);
	    }
	    
	};

	var searchSearchPatientList = function(){
		$searchUlPatientList.empty();
		searchPatientList = [];
		
		patientInfoInit();
		
		// 진료과/진료의 검색
		if($('input[type="radio"][name="plist-search"]:checked').val()=='treat'){
			var param = {};
			if($('input[type="radio"][name="treatment"]:checked').val()=='in'){
				param = {
						departmentCd: $('#searchSltDept').val(), 
						doctorId: $('#search_sltDoctor').val()
						};
				self.treatment.getInPatListPerDeptOrWard(param, 'I', 'search');
			}else{
				if($('#searchSearchDate').val()==''){
					self.alert('조회 일자를 입력해주세요.');
					return;
				}
				param = {
						departmentCd: $('#searchSltDept').val(), 
						doctorId: $('#search_sltDoctor').val(), 
						treatDt: moment($('#searchSearchDate').val()).format('YYYYMMDD')
						};
				self.treatment.getOutPatList(param, 'search');
			}
		//병동/진료과 검색
		}else if($('input[type="radio"][name="plist-search"]:checked').val()=='hospital'){
			var param = {};
			param = {
					wardCd: $('#search_sltWard').val(), 
					departmentCd: $('#searchSltDept').val()
					};
			self.treatment.getSrPatListByWD(param);
		//재원환자검색
		}else if($('input[type="radio"][name="plist-search"]:checked').val()=='patient'){
			if($('#search_txtSrData').val()==''){
				self.alert('조회할 '+ $('#search_sltPatientCondition option:selected').text() +'을(를) 입력해주세요.');
				return;
			}else if($('#search_sltPatientCondition option:selected').val()=='name' && $('#search_txtSrData').val().length<2){
				self.alert($('#search_sltPatientCondition option:selected').text() + '을 2글자 이상 입력해주세요.');
				return;
			}
			var param = {};
			if($('#search_sltPatientCondition').val()=='name'){
				param = {
						patientNm: $('#search_txtSrData').val()
						};
			}else{
				param = {
						patientId: $('#search_txtSrData').val()
						};
			}
			self.treatment.getSrPatList(param);
		}else{
		}
	};
	
	searchBindingPatientList = function(bindPatientList, extraMsg){ //all: 전체, mine: 본인
		searchPatientList = bindPatientList;
		if(searchPatientList.length==0){
			$searchUlPatientList.append(li.clone().append(div.clone().addClass('text-center no-result').text('―')));
		}
		
		for(var i=0; i<searchPatientList.length; i++){
			var divNum = div.clone().addClass("col-xs-3 col-sm-2 pdr0").text( (searchPatientList[i].gender=='F'? 'F':'M') + ' / ' + searchPatientList[i].age); 
			var divName = div.clone().addClass("name col-xs-4 col-sm-2 pd0").text(searchPatientList[i].patientNm + ' ' + searchPatientList[i].patientId);
			var divNumHospital = div.clone().addClass("num_b col-xs-5 col-sm-2 pdr0 letter-control").text(searchPatientList[i].treatTyp=='O'? '외래': searchPatientList[i].wardNm + '/' + searchPatientList[i].roomNm + '/' + searchPatientList[i].bedNm);
			
			var divDoctor = div.clone().addClass("doctor col-xs-4 col-sm-2 pd0").text(searchPatientList[i].departmentCd + ' / ' + searchPatientList[i].doctorNm);
			var divDate = div.clone().addClass("date col-xs-5 col-sm-3 pdr0 letter-control").text(searchPatientList[i].treatTyp=='O'? moment(searchPatientList[i].treatDt).format('YYYY-MM-DD') : moment(searchPatientList[i].inDt).format('YYYY-MM-DD')+ ' HOD '+ searchPatientList[i].inDay);
			
			if(self.isTablet()){
				var divPatientInfo = div.clone().addClass("list-row container").append(divNumHospital).append(divDate).append(divName).append(divNum).append(divDoctor);
			}else{
				var divPatientInfo = div.clone().addClass("list-row container").append(divNumHospital).append(divName).append(divNum).append(divDate).append(divDoctor);
			}
			
			$searchUlPatientList.append(li.clone().append(a.clone().addClass("list-group-item").attr('patientNo', i).attr('patientId', searchPatientList[i].patientId).append(divPatientInfo)));
		}
		
		$('#searchPatientList .list-group-item').on('click',function(){
			var patientInfo = searchPatientList[event.currentTarget.attributes.patientNo.value];
			var patientNo = event.currentTarget.attributes.patientNo.value;
			
			if($('input[type="radio"][name="plist-search"]:checked').val()=='treat'){
				if($('input[type="radio"][name="treatment"]:checked').val()=='in'){
					patientInfo.treatTyp='I';					
				}
			}else{
				patientInfo.treatTyp='I';
			}
			localStorage.setItem('patientInfo', JSON.stringify(patientInfo));
			
			var param = {
						patientId: patientInfo.patientId,
						departmentCd: patientInfo.departmentCd,
						treatTyp: patientInfo.treatTyp, 
						treatDt: patientInfo.inDt==undefined? patientInfo.treatDt: patientInfo.inDt};
			
			$('.list-group-item').removeClass('active');
			$(this).addClass('active');

			/*$('#nursingPopup  [id*=popContent]').removeClass('in');
			$('#nursingPopup  #popContentNursingRecode').addClass('in');
			$('#nursingRecodeTab.nav-tabs a[href="#tabInfo"]').tab('show');
			$('#nursingPopup').css('display', 'block');*/
			
			$('.list-group-item').removeClass('active');
			$(this).addClass('active');
			
			var patientNo = event.currentTarget.attributes.patientNo.value;
			var patientInfo = searchPatientList[patientNo];
			patientInfo.treatDt=patientInfo.inDt;
			patientInfo.treatTyp=patientInfo.treatTyp;
			localStorage.setItem('patientInfo', JSON.stringify(patientInfo));
							
			$('#nursingPopup  [id*=popContent]').removeClass('in');
			$('#nursingPopup  #popContentNursingRecode').addClass('in');
			if(!$('#openToggle').is('.on')){
				$('#nursingRecodeTab.nav-tabs a[href="#tabInfo"]').tab('show');
			}else{
				mplusNursing.reInit($("ul#nursingRecodeTab.nav-tabs li.active a").attr('aria-controls'));
			}
			$('#newPopupFooter').css('display', 'block');
			/*$('#nursingPopup').css('display', 'block');*/
			
			$('.list-group-item').removeClass('active');
			$(this).addClass('active');

			// 선택한 환자의 스크롤 위치 구하기
			var pos = $('#tabSearch').scrollTop() + $('#searchPatientList li a.list-group-item[patientno='+patientNo+']').offset().top;
			
			$('#searchPatientList').css('margin-bottom', '100vh');
			
			if( self.isTablet() ) {
				// 적절한 위치로 이동
				$('#tabSearch').animate({scrollTop: pos - 150}, 500); 
				$('#nursingPopup').height(max2-245);
				$('#nursingPopup .tab-content .tab-pane').height(max2-317);
				$('#openToggle').stop().animate({bottom: wh-280 },500);
			}else{
				// 적절한 위치로 이동
				$('#tabSearch').animate({scrollTop: pos - 77}, 500);
				$('#nursingPopup').height(max2-105);
				$('#nursingPopup .tab-content .tab-pane').height(max2-177);
				$('#openToggle').stop().animate({bottom: wh-140 },500);
			}
			$('#openToggle').addClass('on');
			$('#openToggle').find('.fa').removeClass('fa-chevron-up');
			$('#openToggle').find('.fa').addClass('fa-chevron-down');
			$('#nursingPopup').stop().animate({bottom:0},500);
			$('#nursingPopup').css({'display': 'block'});
			mplusNursing.init();
			
			var patientInfo = searchPatientList[event.currentTarget.attributes.patientNo.value];
			patientInfo.treatTyp=patientInfo.treatTyp;
			localStorage.setItem('patientInfo', JSON.stringify(patientInfo));
			
			var param = {
						hospitalCd: localStorage.hospitalCd,
						patientId: patientInfo.patientId
						};
			var patientInfoData = self.nursing.getPatientInfo(param);
			bindingPatientDetail(patientInfo, patientInfoData);
		// 다음이벤트 (환자리스트가 아닌 화면영역을 클릭했을 때 토글 내려가게 하는 기능) 동작을 막기 위함
		return false;
		});
	};
	
	/*----------------------- 검색 resource 종료 ----------------------*/
	
	/*----------------------- 상세-정보탭 공통 --------------------------*/
	var bindingPatientDetail = function(patientInfo, patientInfoData) {
		if(patientInfoData!=undefined){
			// if(patientInfoData.patientDtl!="") {console.log('테스트');}
			$('#nursingPopupId').text(patientInfoData.patientId);
			$('#nursingPopupNameNum').text(patientInfoData.patientNm + ' / ' + patientInfoData.patientId);
			$('#nursingPopupBirth').text(patientInfoData.birthDt!=""&&patientInfoData.birthDt!=null&&patientInfoData.birthDt!=undefined? moment(patientInfoData.birthDt).format('YYYY-MM-DD'):patientInfoData.birthDt);
			$('#nursingPopupSex').text(patientInfoData.gender + ' / '+ patientInfoData.age);
			$('#nursingPopupRoom').text(patientInfoData.wardNm + ' / '+ patientInfoData.roomNm + ' / '+ patientInfoData.bedNm);
			$('#nursingDiagnosisNm').text(patientInfoData.diagnosisNm);
			$('#nursingOperatingDt').text(patientInfoData.operatingDt!=""&&patientInfoData.operatingDt!=null&&patientInfoData.operatingDt!=undefined? moment(patientInfoData.operatingDt).format('YYYY-MM-DD'):patientInfoData.operatingDt);
			$('#nursingOperatingNm').text(patientInfoData.operatingNm);
			if(patientInfo.treatTyp == 'E') {
				$('#nursingInDt').text(patientInfo.treatDt!=""&&patientInfo.treatDt!=null&&patientInfo.treatDt!=undefined? moment(patientInfo.treatDt).format('YYYY-MM-DD'):patientInfo.treatDt);
			} else {
				$('#nursingInDt').text(patientInfoData.inDt!=""&&patientInfoData.inDt!=null&&patientInfoData.inDt!=undefined? moment(patientInfoData.inDt).format('YYYY-MM-DD'):patientInfoData.inDt);
			}
			$('#nursingInRsn').html(patientInfoData.inRsn.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>'));
			$('#nursingCurrentStat').html(patientInfoData.currentStat.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>'));
		}else{
			$('#nursingPopupId').text(patientInfo.patientId);
			$('#nursingPopupNameNum').text('');
			$('#nursingPopupBirth').text('');
			$('#nursingPopupSex').text('');
			$('#nursingPopupRoom').text('');
			$('#nursingDiagnosisNm').text('');
			$('#nursingOperatingDt').text('');
			$('#nursingOperatingNm').text('');
			$('#nursingInDt').text('');
			$('#nursingInRsn').text('');
			$('#nursingCurrentStat').text('');
		}
	};
};
