/**
 * mplus_mobile_patient
 */
var mplus_mobile_patient = function(){
	// 상속
	mplus_common.call(this);
	
	// 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 thead = $("<thead></thead>");
	var tbody = $("<tbody></tbody>");
	var li = $("<li></li>");
	var a = $("<a></a>");
	var span = $("<span></span>");
	var button = $("<button></button>");
		
	//기본
	var $searchBtn = $('#searchBtn'),
		$recentSearchBtn = $('#recentSearchBtn'),
	 	$ulPatientList = $('#ulPatientList');

	//처방
	var $prescriptionPatientName = $('#prescriptionPatientName'),
	$prescriptionDtpSrchdd = $('#prescriptionDtpSrchdd'),
	$prescriptionSelectdd = $('#prescriptionSelectdd'),
 	$prescriptionSelectbox = $('#prescriptionSelectbox'),
 	$prescriptionList = $('#prescriptionList'); 
	
	var patientInfo;
	var prescribeInfo;
	var prescribeList = [];
	
	//검사
	var $patientName = $('#patientName'),
	$btnExamSearch = $('#btnExamSearch'),
	$datepicker = $('#datepicker'),
 	$selectbox = $('#selectbox'),
 	$examineList = $('#examineList'),
 	$examinePlusBtn = $('#examinePlusBtn'),
 	$examinePrevBtn = $('#prevExamBtn'),
 	$examineNextBtn = $('#nextExamBtn'),
 	examInfo;
	targetExamSeq = 0;
	
	// EMR
	$emrPrevBtn = $('#prevEmrBtn');
 	$emrNextBtn = $('#nextEmrBtn');
	
	/**
	 * 초기화
	 */
	this.detailInit = function(){
		$('.bottom-menu.selected').removeClass('selected');
		$('[name=btnMoveDetail]').addClass('selected');
		headerTitle.text("환자정보");
		detailBinding();
	};
	this.prescriptionInit = function(){
		$('.bottom-menu.selected').removeClass('selected');
		$('[name=btnMovePrescription]').addClass('selected');
		headerTitle.text("환자정보");
		patientInfo = JSON.parse(localStorage.getItem('patientInfo'));
		$prescriptionPatientName.text(patientInfo.patientNm + ' ' + patientInfo.patientId);
		
		prescriptionAddEvent();
		// 조회일자를 오늘날짜로 변경 - 2017/01/18
		var today = moment(new Date()).format('YYYY-MM-DD');
		$prescriptionDtpSrchdd.val(today);
		$('#prescriptionSelectbox').val('sel');
		
		// 외래환자일 경우 날짜 선택을 과거 진료일자들 콤보박스로 할수있도록 함
		if( patientInfo.treatTyp =='O') {
			$('#prescriptionDtpSrchdd').css('display', 'none');	
			$('#prescriptionSelectdd').css('display', 'block');
			$('#prescriptionSelectdd').empty();
			
			var param = {
					patientId: patientInfo.patientId,
					departmentCd: patientInfo.departmentCd==undefined? patientInfo.requestDeptCd: patientInfo.departmentCd, 
					treatDt: patientInfo.treatDt
			};
			
			var pastTreatDateList = self.treatment.getPastTreatDate(param);
			
			// 최근 10개만 표시
			for(var i=0; (i<pastTreatDateList.length && i<10); i++){
				option = $('<option></option>').clone().attr('value', pastTreatDateList[i].treatDt)
														.text(moment(pastTreatDateList[i].treatDt).format('YYYY-MM-DD'));
				$('#prescriptionSelectdd').append(option);
			}
			
			// 오늘의 외래환자가 아닌경우 진료일자에 오늘이 포함되어있지 않으므로, 초기 조회날짜 변수 today를 첫번째 진료날짜로 바꿔치기함
			today = pastTreatDateList[0].treatDt;
			
		} else {
			$('#prescriptionDtpSrchdd').css('display', 'block');
			$('#prescriptionSelectdd').css('display', 'none');
		}
		
		searchPrescriptionList(today, "sel");
	};
	this.examineInit = function(){
		$('.bottom-menu.selected').removeClass('selected');
		$('[name=btnMoveExamine]').addClass('selected');
		headerTitle.text("환자정보");
		patientInfo = JSON.parse(localStorage.getItem('patientInfo'));
		var today = new Date();
		var prevDay = new Date(Date.parse(new Date()) - 365 * 1000 * 60 * 60 * 24); //일년전!!
		$('#examEndSrchdd').val(moment(today).format('YYYY-MM-DD'));
		$('#examStartSrchdd').val(moment(prevDay).format('YYYY-MM-DD'));
		
		searchExamineList();
		//var categorys = ['검체검사', '기능검사', '병리검사', '영상검사'];
		//examineTreeCtrl.init(categorys);
		examineAddEvent();
		//var today = new Date();
		//$('#dtpSrchdd1').val(moment(today).format('YYYY-MM-DD'));

	};
	this.consultInit = function(){
		headerTitle.text("협진상세");
		initConsultDetail();
	};
	
	this.emrInit = function(){
		headerTitle.text("환자정보");
		emrAddEvent();
		searchEmrList();
	};
	/**
	 * 이벤트 등록
	 */
	var prescriptionAddEvent = function(){
		$prescriptionDtpSrchdd.unbind();
		$prescriptionDtpSrchdd.change(function(){
			$('#prescriptionSelectbox').val('sel');
			searchPrescriptionList($('#prescriptionDtpSrchdd').val(), $('#prescriptionSelectbox option:selected').val());
		});
		
		$prescriptionSelectdd.unbind();
		$prescriptionSelectdd.change(function(){
			$('#prescriptionSelectbox').val('sel');
			searchPrescriptionList($('#prescriptionSelectdd').val(), $('#prescriptionSelectbox option:selected').val());
		});
		
		$prescriptionSelectbox.unbind();
		$prescriptionSelectbox.change(function(){
			bindingPrescription(prescribeList, $('#prescriptionSelectbox option:selected').val());
		});
	};
	
	var examineAddEvent = function(){
		$btnExamSearch.unbind();
		$btnExamSearch.click(function(){
			searchExamineList();
		});
	};
	
	var examineInfoAddEvent = function() {
		// 이동할 때 로딩 뜨면 좋은데 어떻게 해도 안되네 ㅜㅜ
		$examinePrevBtn.unbind();
		$examinePrevBtn.on('click', function(e){
			if(targetExamSeq == 0) {
				self.alert('첫번째 검사입니다.');
				return;
			}
			targetExamSeq--;
			bindExaminInfo(targetExamSeq);
		});
		
		$examineNextBtn.unbind();
		$examineNextBtn.on('click', function(e){
			if(targetExamSeq + 1 == examList.length) {
				self.alert('마지막 검사입니다.');
				return;
			}
			targetExamSeq++;
			bindExaminInfo(targetExamSeq);
		});
	}
	
	//기본 데이터 바인딩
	var detailBinding = function(){
		var patient = JSON.parse(localStorage.getItem('patientInfo'));
		var param;
		if(patient.treatTyp=='I'||patient.consultTyp=='I'){ //patient.treatTyp=='I'인 경우는 없긴하다. 데이터 정상적으로 다 들어오면 테스트해보기.171103
			param = {
					patientId: patient.patientId,
					treatTyp: 'I'/*, 
					deptCode: patient.departmentCd==undefined? patient.reqDeptCode: patient.departmentCd*/
					};
		}else if(patient.treatTyp=='O'||patient.consultTyp=='O'){
			param = {
					patientId: patient.patientId, 
					treatTyp: 'O', 
					departmentCd: patient.departmentCd==undefined? patient.reqDeptCode: patient.departmentCd, 
					treatDt: patient.treatDt
					};
		}else if(patient.treatTyp=='E'||patient.consultTyp=='E'){
			param = {
					patientId: patient.patientId, 
					treatTyp: 'E'/*, 
					deptCode: patient.departmentCd==undefined? patient.reqDeptCode: patient.departmentCd, 
					treatDate: patient.treatDt*/
					};
		}else{
			
		}
		
		var patientInfo = self.patient.getPatInfo(param);
		
		$('#patientPopupNum').text(patientInfo.patientId);
		$('#patientPopupName').text(patientInfo.patientNm);
		$('#patientPopupBirth').text(patientInfo.birthDt!=''? moment(patientInfo.birthDt).format('YYYY-MM-DD'): '');
		$('#patientPopupSex').text(patientInfo.gender + ' / ' + patientInfo.age);
		$('#patientPopupBloodTyp').text(patientInfo.bloodTyp);
		$('#patientPopupCellphone').text(patientInfo.cellphoneNo);
		$('#patientPopupGuardianphone').text(patientInfo.guardianPhoneNo);
		$('#patientPopupAddress').text(patientInfo.address);
		
		if(patientInfo.cellphoneNo!=undefined && patientInfo.cellphoneNo!=null&& patientInfo.cellphoneNo!=''){
			$('#patientTelBtnBox').css('display', 'block');
			
			$('#patientTelBtn').unbind();
			$('#patientTelBtn').on('click', function(e){
				location.href = 'tel:'+patientInfo.cellphoneNo;
			});
			$('#patientSmsBtn').unbind();
			$('#patientSmsBtn').on('click', function(e){
				location.href = 'sms:'+patientInfo.cellphoneNo;
			});
		}else{
			$('#patientTelBtnBox').css('display', 'none');
		}
		
		if(patientInfo.guardianPhoneNo!=undefined && patientInfo.guardianPhoneNo!=null&& patientInfo.guardianPhoneNo!=''){
			$('#guardianTelBtnBox').css('display', 'block');
			$('#guardianTelBtn').unbind();
			$('#guardianTelBtn').on('click', function(e){
				location.href = 'tel:'+patientInfo.guardianPhoneNo;
			});
			$('#guardianSmsBtn').unbind();
			$('#guardianSmsBtn').on('click', function(e){
				location.href = 'sms:'+patientInfo.guardianPhoneNo;
			});
		}else{
			$('#guardianTelBtnBox').css('display', 'none');
		}
	};
	
	//처방 데이터바인딩
	var searchPrescriptionList = function(date, type){
		$prescriptionList.empty();
		prescribeList = [];
		$('#prescriptionList').removeClass();
		var patientInfo = JSON.parse(localStorage.getItem('patientInfo'));
		
		var param = {};
		if(patientInfo.treatTyp == 'I' || patientInfo.consultTyp == 'I' || patientInfo.treatTyp=='E'){
			param = {
					patientId: patientInfo.patientId,
					treatDt: patientInfo.inDt ==undefined? patientInfo.treatDt: patientInfo.inDt,
					prescriptionDt: moment(date).format('YYYYMMDD')
					};
		}else{
			param = {
					patientId: patientInfo.patientId,
					departmentCd: patientInfo.departmentCd==undefined? patientInfo.requestDeptCd: patientInfo.departmentCd,
					treatTyp: patientInfo.treatTyp==undefined? patientInfo.consultTyp: patientInfo.treatTyp,
					prescriptionDt: moment(date).format('YYYYMMDD')
					};
		}
		self.patient.getPatPrescribeList(param, type, function(prescribeList, type) {bindingPrescription(prescribeList, type);});
	};
	
	var prescriptionCdArr = [
		{prescriptionCd: 'A', prescriptionCdNm : '마취', prescriptionList: []},
		{prescriptionCd: 'B', prescriptionCdNm : '진료예약', prescriptionList: []},
		{prescriptionCd: 'C', prescriptionCdNm : '협진', prescriptionList: []},
		{prescriptionCd: 'D', prescriptionCdNm : '식이', prescriptionList: []},
		{prescriptionCd: 'G', prescriptionCdNm : '진단서', prescriptionList: []},
		{prescriptionCd: 'H', prescriptionCdNm : '퇴원처방', prescriptionList: []},
		{prescriptionCd: 'L', prescriptionCdNm : '진단검사', prescriptionList: []},
		{prescriptionCd: 'M', prescriptionCdNm : '소모품', prescriptionList: []},
		{prescriptionCd: 'O', prescriptionCdNm : '수술', prescriptionList: []},
		{prescriptionCd: 'P', prescriptionCdNm : '약', prescriptionList: []},
		{prescriptionCd: 'Q', prescriptionCdNm : '병실이동', prescriptionList: []},
		{prescriptionCd: 'R', prescriptionCdNm : '통합검사', prescriptionList: []},
		{prescriptionCd: 'S', prescriptionCdNm : '입원결정', prescriptionList: []},
		{prescriptionCd: 'T', prescriptionCdNm : '처치', prescriptionList: []},
		{prescriptionCd: 'W', prescriptionCdNm : '전과', prescriptionList: []},
		{prescriptionCd: 'X', prescriptionCdNm : '기타', prescriptionList: []},
		{prescriptionCd: 'Y', prescriptionCdNm : '건진', prescriptionList: []},
		{prescriptionCd: 'Z', prescriptionCdNm : '메시지', prescriptionList: []}];
	
	var prescriptionStatArr = [
		{prescriptionStat: '00', prescriptionStatNm : '처방'},
		{prescriptionStat: '01', prescriptionStatNm : '약신청'},
		{prescriptionStat: '05', prescriptionStatNm : '대기'},
		{prescriptionStat: '10', prescriptionStatNm : '출력'},
		{prescriptionStat: '11', prescriptionStatNm : '조제완료'},
		{prescriptionStat: '12', prescriptionStatNm : '조제취소'},
		{prescriptionStat: '13', prescriptionStatNm : '불출'},
		{prescriptionStat: '14', prescriptionStatNm : 'List출력'},
		{prescriptionStat: '30', prescriptionStatNm : '채혈'},
		{prescriptionStat: '31', prescriptionStatNm : '접수'},
		{prescriptionStat: '32', prescriptionStatNm : '예약'},
		{prescriptionStat: '33', prescriptionStatNm : '도착'},
		{prescriptionStat: '34', prescriptionStatNm : '주사'},
		{prescriptionStat: '35', prescriptionStatNm : '검사대기'},
		{prescriptionStat: '36', prescriptionStatNm : 'RI주문'},
		{prescriptionStat: '37', prescriptionStatNm : '검체도착'},
		{prescriptionStat: '38', prescriptionStatNm : '검사중'},
		{prescriptionStat: '39', prescriptionStatNm : '투여중'},
		{prescriptionStat: '40', prescriptionStatNm : '시행'},
		{prescriptionStat: '41', prescriptionStatNm : '완료'},
		{prescriptionStat: '42', prescriptionStatNm : '서명대기'},
		{prescriptionStat: '49', prescriptionStatNm : 'Rec.'},
		{prescriptionStat: '50', prescriptionStatNm : '예결'},
		{prescriptionStat: '51', prescriptionStatNm : '결과'},
		{prescriptionStat: '90', prescriptionStatNm : '보류'},
		{prescriptionStat: '91', prescriptionStatNm : '종료'},
		{prescriptionStat: '92', prescriptionStatNm : '종료'},
		{prescriptionStat: '93', prescriptionStatNm : '종료'},
		{prescriptionStat: '95', prescriptionStatNm : '종료'}];
	
	var bindingPrescription = function(prescribeListData, type){ 
		$prescriptionList.empty();
		prescribeList = prescribeListData;
		
		if(type=='sel'){
			$prescriptionList.addClass("panel-group panel-group-joined");
			
			prescriptionCdArr.forEach(function(item){item.prescriptionList.length = 0;});
			for ( var i = 0; i < prescribeListData.length ; i++ ){
				/* 2018.06.18. 안드로이드 호환 변경
				prescriptionCdArr.find(function(item, index, array) {
					if( item.prescriptionCd == prescribeListData[i].prescriptionCd) { 
						array[index].prescriptionList.push(prescribeListData[i]); 
						return true;
					}});
				*/
				for(var j=0; j<prescriptionCdArr.length ; j++){
					if( prescriptionCdArr[j].prescriptionCd == prescribeListData[i].prescriptionCd ){
						prescriptionCdArr[j].prescriptionList.push(prescribeListData[i]);
						break;
					}
				}
			}
			
			for ( var i = 0; i < prescriptionCdArr.length ; i++ ){
				if( prescriptionCdArr[i].prescriptionList.length > 0 ) {
					bindingPrescriptionList(prescriptionCdArr[i].prescriptionList, type, prescriptionCdArr[i].prescriptionCdNm);
				}
			}
		}else if(type=='presno'){
			$prescriptionList.addClass("panel-group panel-group-joined");
			
			var groupingPresNo = [];
			for( var i = 0; i < prescribeListData.length; i++) {
				var presIndex = groupingPresNo.map(function(item){ return item.prescriptionNo;}).indexOf(prescribeListData[i].prescriptionNo);
			
				if(presIndex == -1) { //처음보는 처방번호
					var prescription = {};
					prescription.prescriptionNo = prescribeListData[i].prescriptionNo;
					prescription.prescriptionList = [ prescribeListData[i] ];
					groupingPresNo.push(prescription);
				} else { // 봤던 처방번호
					groupingPresNo[presIndex].prescriptionList.push(prescribeListData[i]);
				}
			}
			
			for ( var i = 0; i < groupingPresNo.length ; i++ ){
				bindingPrescriptionList(groupingPresNo[i].prescriptionList, type, groupingPresNo[i].prescriptionNo);
			}
		}
	};
	
	var bindingPrescriptionList = function(prescribeList, type, selName){
		var divPanelHeading = div.clone().addClass("panel-heading");
		var h4 = $("<h4></h4>").addClass("panel-title");
		var h4A = $("<a data-toggle='collapse' data-target='#collapse_"+$('[data-toggle="collapse"]').length+"' class='collapsed' aria-expanded='false'>").text(selName).append(
				$("<i></i>").addClass("fa fa-chevron-circle-up")
		);
		var panelHeading = divPanelHeading.append(h4.append(h4A));
		var divCollapse = div.clone().attr("id", 'collapse_'+$('[data-toggle="collapse"]').length).attr("aria-expanded", "false").addClass("panel-collapse collapse");
		var divPanelBody = div.clone().addClass("panel-body");
		
		for(var j=0; j<prescribeList.length; j++){
			var thContent = th.clone().text("처방내역");
			var tdContentBox = div.clone().addClass('col-xs-9 pd0').text(prescribeList[j].prescriptionNm);
			var tdContentBox1 = span.clone().addClass("label-1").text(prescribeList[j].prescriptionCd);
			//약처리
			if(prescribeList[j].prescriptionCd == "P"){
				tdContentBox.append(span.clone().addClass("spaninject").attr('id','pat_spaninjec_'+j).attr('injecOrdCd',prescribeList[j].orderCd).text("복약정보"));
			}
			var tdContent = td.clone().append(tdContentBox).append(tdContentBox1);
			var trContent = tr.clone().append(thContent).append(tdContent);
			
			var thCode = th.clone().text("처방상태");
			var tdCode = td.clone().text(getPrescriptionCode(prescribeList[j].prescriptionStat));
			var trCode = tr.clone().append(thCode).append(tdCode);
			
			var thDoctor = th.clone().text("처방의");
			var tdDoctor = td.clone().text(prescribeList[j].doctorNm);
			var trDoctor = tr.clone().append(thDoctor).append(tdDoctor);
			
			//약과 처치처방만 횟수 표시
			if(prescribeList[j].prescriptionCd == "P" || prescribeList[j].prescriptionCd == "T"){
				var tdDetail, trDetail;
				if(prescribeList[j].prescriptionCd == "P"){
					tdDetail = td.clone().attr("colspan", "2").addClass("merge").text("투여량 "+ prescribeList[j].doseQtyPerTim + 
							' (' + prescribeList[j].doseTQty +"), 횟수 "+prescribeList[j].doseQtyPerDay+", 일수 "+prescribeList[j].doseDay);
					trDetail = tr.clone().append(tdDetail);
				}else{
					tdDetail = td.clone().attr("colspan", "2").addClass("merge").text("횟수 "+prescribeList[j].doseQtyPerDay);
					trDetail = tr.clone().append(tdDetail);
				}
				
				divPanelBody.append(table.clone().addClass("info-style").append(tbody.clone().append(trContent).append(trCode).append(trDoctor).append(trDetail)));
			}else{
				divPanelBody.append(table.clone().addClass("info-style").append(tbody.clone().append(trContent).append(trCode).append(trDoctor)));
			}
		}
		
		$prescriptionList.append(div.clone().addClass("panel panel-default").append(panelHeading).append(divCollapse.append(divPanelBody)));
		$('#prescriptionList .panel-title a').unbind();
		$('#prescriptionList .panel-title a').on('click',function(){
			if ($(this).is('.on')){
				$(this).find('.fa').removeClass('fa-chevron-circle-down')
				$(this).find('.fa').addClass('fa-chevron-circle-up')
				$(this).removeClass('on')
			}else{
				$(this).addClass('on')
				$(this).find('.fa').removeClass('fa-chevron-circle-up')
				$(this).find('.fa').addClass('fa-chevron-circle-down')
			}
		});
	};
	
	var getPrescriptionCode = function(code){
		//2018.06.18 안드로이드 호환변경
		//var prescriptionCode = prescriptionStatArr.find(function(item) {if( item.prescriptionStat == code) return true;});
		var prescriptionCode = undefined;
		for(var i = 0 ; i < prescriptionStatArr.length ; i++){
			if(prescriptionStatArr[i].prescriptionStat == code){
				prescriptionCode = prescriptionStatArr[i];
				break;
			}
		}
		if( prescriptionCode != undefined ) {
			return prescriptionCode.prescriptionStatNm;
		} else {
			return '-';
		}
	};
	
	//검사 데이터바인딩
	var searchExamineList = function(){
		$examineList.empty();
		var patientInfo = JSON.parse(localStorage.patientInfo);
		$('#examPatientName').text(patientInfo.patientNm + ' ' + patientInfo.patientId);
						
		var param = {
					patientId: patientInfo.patientId
					};
		self.patient.getExamList(param, function(result) { bindExamineList(result)});
	};
	
	var bindExamineList = function(examListData){
		examList = examListData;
		examineTreeCtrl.init(examListData);
	};
	
	/*var bindExaminInfo = function(seq) {
		var param = {
				examinationRst: examList[seq].examKey
				};
		examInfo = self.patient.getExamInfo(param);
		$('#examineInfo').empty();
		var tableData = table.clone().attr('id', 'examineDetailList');
		var tbodyData = tbody.clone();
		
		examineInfoAddEvent();
		
		//pacs버튼 생성 코드
		if(examInfo.pacs){
			var divPacsBtn = div.clone().addClass('div-btn-pacs').append(button.clone().addClass('btn btn-primary btn-block').attr('id', 'btnPacsOpen').text('PACS'));
			$('#examineInfo').append(divPacsBtn);
			
			$('#btnPacsOpen').on('click', function(){
				pacsOpen(examInfo);
			});
		};
		
		if(examInfo.type=='N'){
			if(examInfo.style){
				for(var j=0; j<examInfo.result.length; j++){
					var tdData1 = td.clone().addClass('examine-style_'+ examInfo.result[j].content1).append(div.clone().append($('<pre></pre>').clone().text(examInfo.result[j].content2)).append(span.clone().addClass('none-style').text(examInfo.result[j].content3!=undefined && examInfo.result[j].content3!=null && examInfo.result[j].content3!=''? '  '+ examInfo.result[j].content3: '')));
					var trData1 = tr.clone().append(tdData1);
					tbodyData.append(trData1);
					
				};
				tableData.append(tbodyData);
				$('#examineInfo').append(tableData);
			}else{
				for(var j=0; j<examInfo.result.length; j++){
					var tdData1 = td.clone().addClass('title-td').append(div.clone().text(examInfo.result[j].content1));
					var tdData2 = td.clone().addClass('text-center pd0').append(div.clone().text(examInfo.result[j].content2));
					var tdData3 = td.clone().addClass('text-center pd0').append(div.clone().addClass(examInfo.result[j].content3=='▲'? 'arrow-up': examInfo.result[j].content3=='▼'? 'arrow-down': '').text(examInfo.result[j].content3));
					var trData = tr.clone().append(tdData1).append(tdData2).append(tdData3);
					tbodyData.append(trData);
				};
				tableData.append(tbodyData);
				$('#examineInfo').append(tableData);
			}
		}else{
			for(var j=0; j<examInfo.result.length; j++){
				var divData = div.clone().addClass('type-T').append($('<pre></pre>').clone().addClass(examInfo.result[j].content2=='-'? 'content-type': '').text(examInfo.result[j].content1));
				$('#examineInfo').append(divData);
			};
		};
		
		$('#headerTitle2').text("상세정보");
		$('#nursingPopup  [id*=popContent]').removeClass('in');
		$('#nursingPopup  #popContentExamineInfo').addClass('in');
		$('#nursingPopup').css('display', 'block');
				
		$('#examineInfo').scrollTop(0);
		
		$( '#examineInfo' ).unbind();
		$( '#examineInfo' ).on('touchstart',function(){
			$('#examMoveBtn').css({display: 'none'}).fadeOut('slow'); 
		});
		$( '#examineInfo' ).on('touchend',function(){
			$('#examMoveBtn').css({display: 'block'}).fadeIn('slow');
		});
	}
	*/
	
	//협진 데이터바인딩
	var initConsultDetail = function(){
		var patientInfo = JSON.parse(localStorage.getItem('patientInfo'));
		var param = {
				patientId: patientInfo.patientId,
				requestDt: patientInfo.requestDt, 
				requestDeptCd: patientInfo.requestDeptCd==null? ' ': patientInfo.requestDeptCd, 
				requestDrId: patientInfo.requestDrId==null? ' ': patientInfo.requestDrId, 
				responseDeptCd: patientInfo.executeDeptCd==null? ' ': patientInfo.executeDeptCd, 
				responseDrId: patientInfo.hopeDrId==null? ' ': patientInfo.hopeDrId, 
				consultTyp: patientInfo.consultTyp
		};
			
		var consultInfo = self.consult.getConsultInfo(param);
		
			$('#tdConsultName').text(patientInfo.patientNm + ' ' + patientInfo.patientId);
		if(!$.isEmptyObject(consultInfo)){
			$('#tdDiagName').text(consultInfo.diagnosisNm);
			$('#tdRequest').html(decodeURI(patientInfo.requestDeptNm) + ' / ' + decodeURI(patientInfo.requestDrNm) + '<button id="btnDoctorTel" class="btn btn-danger" style="padding: 3px 8px; margin: -3.6px 0px -2.4px 7px"><i class="fa fa-phone"></i><span class="hidden">전화걸기</span></button>');
			$('#tdReply').text(patientInfo.executeDeptNm+' / ' + (patientInfo.responseDrNm!=undefined&&patientInfo.responseDrNm!=null&&patientInfo.responseDrNm!=''?patientInfo.responseDrNm: ''));
			$('#spanRequestDate').text(patientInfo.requestDt!=undefined&&patientInfo.requestDt!=null&&patientInfo.requestDt!=''?(patientInfo.requestDt!=''? moment(patientInfo.requestDt).format('YYYY-MM-DD'):''): '');
			$('#divRequestDetail').html(consultInfo.requestTxt.replace(/\\r\\n|\\r/gi, '</br>'));
			$('#spanReplyDate').text(consultInfo.responseDtTm!=undefined&&consultInfo.responseDtTm!=null&&consultInfo.responseDtTm!=''? moment(consultInfo.responseDtTm).format('YYYY-MM-DD'): '');
			$('#divReplyDetail').html(consultInfo.responseTxt!=undefined&&consultInfo.responseTxt!=null&&consultInfo.responseTxt!=''? consultInfo.responseTxt.replace(/\\r\\n|\\r/gi, '</br>'): '');
		}
		$('#btnDoctorTel').unbind();
		$('#btnDoctorTel').on('click', function(e){
			if(consultInfo.requestDrTel==undefined||consultInfo.requestDrTel==null||consultInfo.requestDrTel==''){
				self.alert('의뢰 의사의 전화번호가 존재하지 않습니다.');
				return;
			}
			location.href = 'tel:'+consultInfo.requestDrTel;
		});
		$('#popContentConsultDetail').scrollTop(0);
	};
	var emrAddEvent = function() {
		$emrPrevBtn.unbind();
		$emrPrevBtn.on('click', function(e){
			var totalImageCount = $('img[id^="emrImg_"]')[0].id.split('_')[1];
			var currentImageSeq = $('img[id^="emrImg_"].img-disp-Y')[0].id.split('_')[2];
			
			$('img[id^="emrImg_"]').removeClass('img-disp-Y').addClass('img-disp-N');
			if(currentImageSeq==0){
				$('#emrImg_'+totalImageCount+'_'+(parseInt(totalImageCount)-1)).removeClass('img-disp-N').addClass('img-disp-Y');
				$('#emrPageInfo').html(parseInt(totalImageCount) + ' / ' + totalImageCount);
			}else{
				$('#emrImg_'+totalImageCount+'_'+(parseInt(currentImageSeq)-1)).removeClass('img-disp-N').addClass('img-disp-Y');
				$('#emrPageInfo').html(parseInt(currentImageSeq) + ' / ' + totalImageCount);
			};
			$('.emr-detail').scrollTop(0);
			
		});
		
		$emrNextBtn.unbind();
		$emrNextBtn.on('click', function(e){
			var totalImageCount = $('img[id^="emrImg_"]')[0].id.split('_')[1];
			var currentImageSeq = $('img[id^="emrImg_"].img-disp-Y')[0].id.split('_')[2];
			
			$('img[id^="emrImg_"]').removeClass('img-disp-Y').addClass('img-disp-N');
			if(currentImageSeq==(totalImageCount-1)){
				$('#emrImg_'+totalImageCount+'_0').removeClass('img-disp-N').addClass('img-disp-Y');
				$('#emrPageInfo').html('1 / ' + totalImageCount);
			}else{
				$('#emrImg_'+totalImageCount+'_'+(parseInt(currentImageSeq)+1)).removeClass('img-disp-N').addClass('img-disp-Y');
				$('#emrPageInfo').html((parseInt(currentImageSeq)+2) + ' / ' + totalImageCount);
			};
			$('.emr-detail').scrollTop(0);
		});
	}
	
	//emr리스트 조회
	var searchEmrList = function(){
		var patientInfo = JSON.parse(localStorage.getItem('patientInfo'));
		var param = {
				patientId: patientInfo.patientId,
				certCode: 'ALL',
				treatDate: patientInfo.treatDate,
				deptCode: patientInfo.deptCode,
				treatType: 'O',
		}; 
		var emrList = self.patient.getEmrList(param);
		if(emrList==undefined||emrList==null||emrList.length==0){
			self.alert('조회할 이미지가 없습니다.');
			$('#nursingPopup').css('display', 'none');
			return;
		};
		$('.tab-content .tab-pane').css('overflow', 'hidden');
				
		var emrImageList = [];
		for(var i=0; i<emrList.length; i++){
			emrImageList.push({imgPath: contextPath+'/mobile/patient/getEmrImage.json?fileName='+emrList[i].fileName});
		};

		$('.mp-page-header, #emrPageInfo').css('display', 'block');
		if( emrImageList.length > 1 ) {
			$('#prevEmrBtn, #nextEmrBtn').css('display', 'block');
		} else {
			$('#prevEmrBtn, #nextEmrBtn').css('display', 'none');
		};
		
		var wh=$(window).height();
				
		// EMR 이미지 리스트 추가
		$('#emrList').empty();
		for(var j=0; j<emrImageList.length; j++){
			var imageItem = '';
			if(j==0){
				imageItem = $('<img src="'+emrImageList[j].imgPath+'" id="emrImg_'+emrImageList.length+'_'+j+'" class="img-disp-Y">');
			}else{
				imageItem = $('<img src="'+emrImageList[j].imgPath+'" id="emrImg_'+emrImageList.length+'_'+j+'" class="img-disp-N">');
			};
			 $('#emrList').append(imageItem);
		};
			
		// 첫번째 이미지 보이게 하기 / 페이지 정보 셋팅
		$('#emrPageInfo').html('1 / ' + emrImageList.length);

		var element = $('meta[name=viewport]')[0];

		element.setAttribute('content','width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=3.0, user-scalable=yes');
				
		$('#emrList').unbind();
		$('#emrList').on('click touchend', function(event) {//터치엔드일때만 클릭을한번 더먹이면어떨까?
			var zoom = document.documentElement.clientWidth / window.innerWidth;
			if(zoom > 1){
				$('.mp-page-header, #prevEmrBtn, #nextEmrBtn, #emrPageInfo').css('display', 'none');
				
			}else{
				if( $('#emrList img').length > 1 ) {
					$('#prevEmrBtn, #nextEmrBtn').css('display', 'block');
				}
				$('.mp-page-header, #emrPageInfo').css('display', 'block');
			};
			if(event.type=='touchend'){ //아이폰에서 헤더와 버튼이 제대로 나타나지 않아서 한번더 이벤트를 먹임
				$('#emrList').click();
			};
			
	    });
	};

	//pacsOpen 버튼클릭
	var pacsOpen = function(examInfo){
		var jsonmsg = {
				"type" : "command",
				"functionType" : "callPacs",
				"value" : {"user_id": "hyumc", "user_pw": "mob*app/hy01", "accno": examInfo.accNo}
		};
		self.toNative(jsonmsg);
	};
	
	// 검사 Tree
	var treeClose = $('<span class="glyphicon glyphicon-menu-up" aria-hidden="true"></span>');
	var treeOpen = $('<span class="glyphicon glyphicon-menu-down" aria-hidden="true"></span>');
	var highIcon = $('<span class="exam-ref-result-high">H</span>');
	var lowIcon = $('<span class="exam-ref-result-low">L</span>');
	var $btnPacs = $('#btnPacs');
	/**
	 * 검사 Tree
	 * 상위 카테고리(대분류), 하위 카테고리(중분류), 검사 Title 이 각각 레벨 1, 2, 3으로 존재한다.
	 * 카테고리 상태: 열림, 닫힘 - "open" class의 존재 여부로 판단한다.
	 * 
	 * */
	var examineTreeCtrl = {
		/* 전체 검사리스트를 받아서 데이터를 쓰기 좋게 편집하고, 대분류 카테고리들만 화면에 배치한다. */
		init: function(examList) {
			var examineList = $('#examineList');
			examineList.empty();
			var level1 = div.clone().addClass('tree-level-1').append(div.clone().addClass('item').append(treeClose));
			var level2 = div.clone().addClass('tree-level-2');

			examineTreeCtrl.examList = examList;
			examineTreeCtrl.grouping(examList);
			/* 상위 카테고리 배치 - Level 1 */
			for( var i = 0; i < examineTreeCtrl.examData.length; i++) {
				var node = level1.clone();
				var nodeData = node.find('.item').attr('id', 'node_' + examineTreeCtrl.examData[i].categoryCd).attr('level', '1');
				nodeData.append(examineTreeCtrl.examData[i].categoryNm);
				nodeData.click(function(e) {examineTreeCtrl.nodeOpen(e);});
				examineList.append(node);
				/* 하위 카테고리 컨테이너 배치 - Level 2 (border-left)*/
				/* 상위 카테고리의 바로 아래에 위치한다. */
				var nodeLvl2 = level2.clone().attr('parent', 'node_' + examineTreeCtrl.examData[i].categoryCd); // parent 속성은 상위 카테고리의 ID
				examineList.append(nodeLvl2);
				/* 마지막 Level 2는 닫힌 상태에서 border left가 없어야 하기 때문에 last class 추가*/
				if( i == (examineTreeCtrl.examData.length - 1)) {
					nodeData.addClass('last');
					nodeLvl2.css('display', 'none');
				}
			};
			
			$('.tree-level-1 .item').click(); //level 2까지 열기위함
		},
		/* 카테고리를 열거나 닫는다. */
		nodeOpen: function(e) {
			var targetNode = $(e.currentTarget);
			var targetNodeId = e.currentTarget.id;
			var level = targetNode.attr('level');
			var isOpen = targetNode.hasClass('open');
			var isLast = targetNode.hasClass('last');
			
			if( isOpen ) { /* 닫기 */
				targetNode.removeClass('open');
				targetNode.find('span').removeClass('glyphicon-menu-down').addClass('glyphicon-menu-up'); // 화살표 방향 전환
				if (level == '1') {
					/* Level 2를 비운다. */
					var level2 = $('#examineList .tree-level-2[parent=' + targetNodeId + ']');
					level2.empty();
					if(isLast) {
						level2.css('display', 'none');
					}
				} else if (level == '2') {
					/* Level 3를 없앤다. */
					var level3 = $('#examineList .tree-level-3[parent=' + targetNodeId + ']');
					level3.remove();
				}
			} else { /* 열기 */
				targetNode.addClass('open');
				targetNode.find('span').removeClass('glyphicon-menu-up').addClass('glyphicon-menu-down'); // 화살표 방향 전환
				if (level == '1') {
					// 중분류 가져오기
					var lowerCategorys = examineTreeCtrl.getLowerCategory(targetNodeId.split('node_')[1]);
					var level2 = $('#examineList .tree-level-2[parent=' + targetNodeId + ']');
					if(isLast) {
						level2.css('display', 'block');
					}
					for( var i = 0; i < lowerCategorys.length; i++ ) {
						var nodeLvl2Item = div.clone().addClass('item').append(treeClose.clone()).append(lowerCategorys[i].categoryNm);
						var nodeLvl2Data = div.clone().addClass('item-wrap').append(nodeLvl2Item).attr('level', '2').attr('id', 'node2_' + lowerCategorys[i].categoryCd);
						nodeLvl2Data.click(function(e) { examineTreeCtrl.nodeOpen(e); });
						level2.append(nodeLvl2Data);
					}
				} else if (level == '2') {
					var parentId = targetNode.parent().attr('parent').split('node_')[1];
					var examList = examineTreeCtrl.getExamList(parentId, targetNodeId.split('node2_')[1]);
					examList = self.util.sortObj(examList, 'examinationDt', 'date', 'down');
					var level3 = div.clone().addClass('tree-level-3').attr('parent', targetNodeId);

					for( var i = 0; i < examList.length; i++ ) {
						var examName = span.clone().addClass('').append(examList[i].examinationNm);
						var examDateStatus = span.clone().addClass('exam-date-status').append('&nbsp;&nbsp;[ ' + examList[i].examinationDt + ' ' + (examList[i].examinationRst==null? '': examList[i].examinationRst) + ' ]');
						var pacsYn = (examList[i].highClassCd!='B' && examList[i].pacs!=null && (examList[i].pacs=='H'||examList[i].pacs=='M'||examList[i].pacs=='S'||examList[i].pacs=='Y'))? span.clone().addClass('glyphicon glyphicon-picture pacs'): '';
						var examItem = div.clone().addClass('item').append(examName).append(examDateStatus).append(pacsYn).attr('id', 'node3_' + examList[i].examinationId).attr('highClassCd', examList[i].highClassCd).attr('accNo', examList[i].AccNo).attr('pacs', examList[i].pacs);
						/*examItem.click(function(e) { 
							examineTreeCtrl.getExamInfo(e.currentTarget.id.split('node3_')[1]); 
						});*/
						level3.append(examItem);
					}
					targetNode.after(level3);
					$('[id*=node3_]').unbind();
					$('[id*=node3_]').click(function(e){
						examineTreeCtrl.getExamInfo(e.currentTarget.id.split('node3_')[1]);
						$('#examName').text(e.currentTarget.innerText);
					});
				}
			}
		},
		getLowerCategory: function(categoryCd) {
			
			//2018.06.18. 안드로이드 호환 변경
			//return examineTreeCtrl.examData.find(function(item) {if(item.categoryCd == categoryCd){return true}}).lowerCategory;
			
			var rExamineTreeCtrl = undefined;
			for(var i = 0 ; i < examineTreeCtrl.examData.length ; i++){
				if(examineTreeCtrl.examData[i].categoryCd == categoryCd){
					rExamineTreeCtrl = examineTreeCtrl.examData[i];
					break;
				}
			}
			return rExamineTreeCtrl.lowerCategory;
		},
		getExamList: function(categoryCd, lowerCategoryCd) {
			var lowerCategory = examineTreeCtrl.getLowerCategory(categoryCd);
			
			//2018.06.18. 안드로이드 호환 변경
			//return lowerCategory.find(function(item) {if(item.categoryCd == lowerCategoryCd){return true}}).examList;
			var rLowerCategory = undefined;
			for(var i = 0 ; i < lowerCategory.length ; i++){
				if(lowerCategory[i].categoryCd == lowerCategoryCd){
					rLowerCategory = lowerCategory[i];
					break;
				}
			}
			return rLowerCategory.examList;
		},
		getExamInfo: function(examId) {
			var selectedExam = examineTreeCtrl.examList[examId];
			var patientInfo = JSON.parse(localStorage.getItem('patientInfo'));
			$('#examInfoPatientName').text(patientInfo.patientNm + ' ' + patientInfo.patientId);
			
			$btnPacs.css('display', 'none');
			$('#examineInfo').empty();
			
			if( selectedExam.highClassCd == 'B') { // 검체검사
				examineTreeCtrl.drawExam_B(selectedExam);
			} else if( selectedExam.highClassCd == 'D') { // 병리검사
				examineTreeCtrl.drawExam_D(selectedExam);
			} else if( selectedExam.highClassCd == 'E'){ // 기능검사
				examineTreeCtrl.drawExam_E(selectedExam);
			} else if( selectedExam.highClassCd == 'C'){ // 영상검사
				examineTreeCtrl.drawExam_C(selectedExam);
			} else { // 검체검사, 병리검사가 아닌 모든 검사
				examineTreeCtrl.drawExam(selectedExam);
			}
			
			$('#patientPopup  #popContentExamineInfo').addClass('in');
			$('#examineInfo').scrollLeft(0);
			$('.exam-wrap').scrollTop(0);
			$('#patientPopup').css('display', 'block');
		},
		drawExam: function(selectedExam){
			var tempExamText = "판독 결과 : <br> 판독결과 ~~~~~~~~~~~~ <br> 판독 결과 ~~~~~~~~~~~.";
			$('#examineInfo').append(div.clone().addClass('col-xs-12').append(span.clone().addClass('top-info-style').append(tempExamText)));
		},
		drawExam_D: function(selectedExam) {
//			var param = {
//					patientId: patientInfo.patientId,
//					accNo: selectedExam.AccNo
//				};
//			var examRslt = self.patient.getExamRsltByPA(param);
//			//console.log(examRslt);
//			if( examRslt.result.length == 0 ) {
//				$('#examineInfo').append(div.clone().addClass('col-xs-12').append(span.clone().addClass('top-info-style').append('판독 결과 없음')));
//			} else {
//				$('#examineInfo').append(div.clone().addClass('col-xs-12').append(span.clone().addClass('mp-dot')).append(span.clone().addClass('top-info-style').append('병리의사: ' + examRslt.result[0].ReadDrNm + ' / ' + examRslt.result[0].PthoDrNm)));
//				$('#examineInfo').append(div.clone().addClass('col-xs-12 mt5').append(span.clone().addClass('mp-dot')).append(span.clone().addClass('top-info-style').append('Name Of Operation')));
//				$('#examineInfo').append(div.clone().addClass('col-xs-12 mt5 top-info-style exam-rslt').append(span.clone().addClass('top-info-style').append(examRslt.result[0].ExNm)));
//				$('#examineInfo').append(div.clone().addClass('col-xs-12').append(span.clone().addClass('mp-dot')).append(span.clone().addClass('top-info-style').append('Pathological Diagnosis')));
//				$('#examineInfo').append(div.clone().addClass('col-xs-12 mt5 top-info-style exam-rslt').append(span.clone().addClass('top-info-style').html(examRslt.result[0].Diagnosis.replace(/\n/g, '<br>'))));
//				if(examRslt.result[0].GrossDiagnosis != undefined) { //2018.04.09 병원 요구사항으로 데이터 추가
//					$('#examineInfo').append(div.clone().addClass('col-xs-12').append(span.clone().addClass('mp-dot')).append(span.clone().addClass('top-info-style').append('Gross Description')));
//					$('#examineInfo').append(div.clone().addClass('col-xs-12 mt5 top-info-style exam-rslt').append(span.clone().addClass('top-info-style').html(examRslt.result[0].GrossDiagnosis.replace(/\n/g, '<br>'))));
//				}
//			}
			var tempReadDrNm = "홍길동";
			var tempPthoDrNm = "홍길동01, 홍길동 02";
			var tempExNm = "검체유형 : Voided Urine Cytology";
			var tempDiagnosis = "Negative for hight-grade urothelial carcinoma, according to The Paris System for Reportind Urinary Cytology";
			$('#examineInfo').append(div.clone().addClass('col-xs-12').append(span.clone().addClass('mp-dot')).append(span.clone().addClass('top-info-style').append('병리의사: ' + tempReadDrNm + ' / ' + tempPthoDrNm)));
			$('#examineInfo').append(div.clone().addClass('col-xs-12 mt5').append(span.clone().addClass('mp-dot')).append(span.clone().addClass('top-info-style').append('Name Of Operation')));
			$('#examineInfo').append(div.clone().addClass('col-xs-12 mt5 top-info-style exam-rslt').append(span.clone().addClass('top-info-style').append(tempExNm)));
			$('#examineInfo').append(div.clone().addClass('col-xs-12').append(span.clone().addClass('mp-dot')).append(span.clone().addClass('top-info-style').append('Pathological Diagnosis')));
			$('#examineInfo').append(div.clone().addClass('col-xs-12 mt5 top-info-style exam-rslt').append(span.clone().addClass('top-info-style').html(tempDiagnosis.replace(/\n/g, '<br>'))));	
		},
		drawExam_B: function(selectedExam) {
//			var param, examInfo;
//			if(selectedExam.middleClassCd == "B08"){ // 미생물 결과값 별도처리 "middleClassNm": "미생물"
//				param = {
//					ymdGb: 'B',
//					ordYmd: selectedExam.OrdYmd,
//					ordExecYmd: selectedExam.examinationDt.replace(/-/gi, ''),
//					unitNo: patientInfo.patientId,
//					ordSlipCd: selectedExam.OrdSlipCd
//				};
//				examInfo = self.patient.GetExamRsltByGer(param);
//			}else{
//				param = {
//					patientId: patientInfo.patientId,
//					prescriptionDt: selectedExam.OrdYmd,
//					executeDt: selectedExam.examinationDt.replace(/-/gi, ''),
//					ordSlipCd: selectedExam.OrdSlipCd
//				};
//				examInfo = self.patient.getExamInfo(param);
//			}
//			var examInfoList = examineTreeCtrl.examInfoGrouping(examInfo.result);
			
			var examTable = table.clone();
			var examThead = thead.clone();
			var examRow = tr.clone().addClass('exam-header');
			var spcNmCol = th.clone().append('검체명');
			var grExamNmCol = th.clone().attr('colspan', '2').append('검사명');
			var rsltCol = th.clone().append('결과');
			var refNmrcCol = th.clone().append('참고치');
			var rsltUnitCdNmCol = th.clone().append('단위');
			var refNmrcGbCol = th.clone().append('판<br>정');
			var rsltProgStusNmCol = th.clone().append('상태');
			var examinationDtTmCol = th.clone().append('일시');
			examRow.append(spcNmCol).append(grExamNmCol).append(rsltCol).append(refNmrcCol).append(rsltUnitCdNmCol).append(refNmrcGbCol).append(rsltProgStusNmCol).append(examinationDtTmCol);
			examTable.append(examThead.append(examRow));
			
			//if(examInfoList.length==0){
				var emptyCol = td.clone().attr('colspan', 9).append('-');
				examTable.append(tr.clone().addClass('text-center').append(emptyCol));
			//}
			
//			for(var i=0; i<examInfoList.length; i++){
//				for(var j=0; j<examInfoList[i].GrExam.length; j++){
//					for(var k=0; k<examInfoList[i].GrExam[j].examList.length; k++){
//						var examRow = tr.clone();
//						var spcNmCol = '';
//						var grExamNmCol = '';
//						var examNmCol = '';
//						if(j==0 && k==0) spcNmCol = td.clone().addClass('text-center').attr('rowspan', examInfoList[i].SpcLength).append(examInfoList[i].SpcNm);
//						if(k==0){
//							if(examInfoList[i].GrExam[j].examList.length>1){
//								grExamNmCol = td.clone().attr('rowspan', examInfoList[i].GrExam[j].examList.length).append(examInfoList[i].GrExam[j].examList[k].GrExamNm);
//								examNmCol = td.clone().append(examInfoList[i].GrExam[j].examList[k].ExamNm);
//							}else{
//								grExamNmCol = td.clone().attr('colspan', 2).append(examInfoList[i].GrExam[j].examList[k].GrExamNm);
//							}
//						}else{
//							examNmCol = td.clone().append(examInfoList[i].GrExam[j].examList[k].ExamNm);
//						}
//						var rsltCol;
//						if(examInfoList[i].GrExam[j].examList[k].IncrGrd != null || examInfoList[i].GrExam[j].examList[k].IncrGrd !== undefined){
//							if(examInfoList[i].GrExam[j].examList[k].Rslt == null){
//								examInfoList[i].GrExam[j].examList[k].Rslt = "";
//							}
//							rsltCol = td.clone().append(examInfoList[i].GrExam[j].examList[k].IncrGrd + examInfoList[i].GrExam[j].examList[k].Rslt);
//						}else{
//							if(examInfoList[i].GrExam[j].examList[k].Rslt == null){
//								examInfoList[i].GrExam[j].examList[k].Rslt = "";
//							}
//							rsltCol = td.clone().append( examInfoList[i].GrExam[j].examList[k].Rslt);
//						}
//						var refNmrcCol = td.clone().append(examInfoList[i].GrExam[j].examList[k].RefNmrc);
//						var rsltUnitCdNmCol = td.clone().append(examInfoList[i].GrExam[j].examList[k].RsltUnitCdNm);
//						var refNmrcGbCol = td.clone().addClass('text-center');
//						if( examInfoList[i].GrExam[j].examList[k].RefNmrcGb == 'H' ) {refNmrcGbCol.append(highIcon.clone());}
//						else if ( examInfoList[i].GrExam[j].examList[k].RefNmrcGb == 'L' ) {refNmrcGbCol.append(lowIcon.clone());}
//						
//						var rsltProgStusNmCol = td.clone().append(examInfoList[i].GrExam[j].examList[k].RsltProgStusNm);
//						var examinationDtTmCol = td.clone().append(examInfoList[i].GrExam[j].examList[k].examinationDtTm==null? '': (self.util.toPrettyDateFormat(examInfoList[i].GrExam[j].examList[k].examinationDtTm)));
//						
//						examRow.append(spcNmCol).append(grExamNmCol).append(examNmCol).append(rsltCol).append(refNmrcCol).append(rsltUnitCdNmCol).append(refNmrcGbCol).append(rsltProgStusNmCol).append(examinationDtTmCol);
//						examTable.append(examRow);
//					}
//				}
//			}
					
			$('#examineInfo').append(examTable);
		},
		drawExam_E: function(selectedExam) {
			var tempExamText = "1. Enlarged LA. <br>2.Relaxation abnormality of LV filling pattern with elevated LV filling pressure. <br>3. Concentric LVH. <br>4. Non-RHD.";
			$('#examineInfo').append(div.clone().addClass('col-xs-12').append(span.clone().addClass('top-info-style').append(tempExamText)));
			examineTreeCtrl.drawPacs(selectedExam);
		},
		drawExam_C: function(selectedExam) {
			var tempReadDrNm = "홍길동";
			var tempSplstDrNm  = "홍길동01";
			var tempRslt = "some scoliosis of thoracic and lumbar spines with degenerative spondylosis and osteoporosis or osteopenia.\nAbnormal opacity of Lt. retrocardiac areas are seen from pneumonia or atelectasis.";
			$('#examineInfo').append(div.clone().addClass('col-xs-6 col-sm-3').append(span.clone().addClass('mp-dot')).append(span.clone().addClass('top-info-style').append('판독의: ' + tempReadDrNm)));
			$('#examineInfo').append(div.clone().addClass('col-xs-6 col-sm-3').append(span.clone().addClass('mp-dot')).append(span.clone().addClass('top-info-style').append('전문의: ' + tempSplstDrNm)));
			$('#examineInfo').append(div.clone().addClass('col-xs-12 mt5 top-info-style exam-rslt').html(tempRslt.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>')));
			examineTreeCtrl.drawPacs(selectedExam);
		},
		drawPacs: function(selectedExam){
			var pacs = selectedExam.pacs;
			if( pacs == 'S' || pacs == 'M' || pacs == 'H' || pacs == 'Y' ) {
				$btnPacs.css('display', 'initial');
				$btnPacs.attr('examId', selectedExam.examinationId);
				$btnPacs.unbind();
				$btnPacs.click(function(e){
					var examId = e.currentTarget.attributes.examId.value;
					var selectedExam = examineTreeCtrl.examList[examId];
					var patientInfo = JSON.parse(localStorage.getItem('patientInfo'));
					var jsonmsg, url, title;
					if( selectedExam.pacs == 'S' ) { // GE PACS
						title = "GE";
						url = self.getPacsUrl(selectedExam.pacs, localStorage.hospitalCd);
						url = url.replace('{patientId}', patientInfo.patientId).replace('{accNo}', selectedExam.AccNo);
						
						//안드로이드 iOS분기처리
						if(/android/i.test(navigator.userAgent.toLowerCase())){
							
						}else if(/iphone|ipad|ipod/i.test(navigator.userAgent.toLowerCase())){
							url = encodeURIComponent(url);
						}
						
						jsonmsg = {
								"type" : "command",
								"functionType" : "popup",
								"value" : {"url": url}
						};
					} else if( selectedExam.pacs == 'M' ){ // MUSE
						title = "MUSE";
						url = self.getPacsUrl(selectedExam.pacs, localStorage.hospitalCd);
						url = url.replace('{patientId}', patientInfo.patientId);
						jsonmsg = {
								"type" : "command",
								"functionType" : "popup",
								"value" : {"url": url}
						};
					} else if( selectedExam.pacs == 'H' ){ // Cardiac PACS - infinitt 앱 연동
						title = "Cardiac PACS";
						self.alert('서비스 준비 중입니다.');
						return;
					} else if( selectedExam.pacs == 'Y' ){ // Cardiac PACS - infinitt 앱 연동
						//$('#examineInfo').append(div.clone().addClass('col-xs-12').append(span.clone().addClass('top-info-style').append( 'PACS Image !! ')));
						$('#modalSamplePACS').modal('show');
					} else {
						title = "ETC PACS";
						self.alert('서비스 준비 중입니다.');
						return;
					}
					
//					var logging = {
//						"logType" : "PACS",
//						"userId" : loginUserId,
//						"userName" : loginUserName,
//						"deptName" : selectDeptName,
//						"title" : title,
//						"content" : url,
//						"content2" : navigator.userAgent,
//						"content3" : localStorage.hospitalCd
//					};
//					var loggingResult = self.patient.loggingLookupPACS(logging);
//					if( loggingResult.result == 1 ) {
//						self.toNative(jsonmsg);
//					} else {
//						self.alert('다시 시도해주세요.');
//					}
				});
			}
		},
		/* 서버로부터 받은 데이터를 정리한다. examList */
		grouping: function(examList) {
			var groupingExam = [];
			for( var i = 0; i < examList.length; i++) {
				// ID 부여
				examList[i].examinationId = i;
				
				var categoryIndex = groupingExam.map(function(item){ return item.categoryCd;}).indexOf(examList[i].highClassCd);
				if(categoryIndex == -1) { //처음보는 대분류
					var group = {};
					group.categoryCd = examList[i].highClassCd;
					group.categoryNm = examList[i].highClassNm;
					group.lowerCategory = [{ categoryCd: examList[i].middleClassCd, categoryNm: examList[i].middleClassNm, examList: [ examList[i]] }];
					groupingExam.push(group);
				} else { // 기존에 등록된 대분류
					var lowerCategoryIndex = groupingExam[categoryIndex].lowerCategory.map(function(item) {return item.categoryCd;}).indexOf(examList[i].middleClassCd);
					if( lowerCategoryIndex == -1) { // 처음보는 중분류
						var lowerCategory = {};
						lowerCategory.categoryCd = examList[i].middleClassCd;
						lowerCategory.categoryNm = examList[i].middleClassNm;
						lowerCategory.examList = [ examList[i] ];
						groupingExam[categoryIndex].lowerCategory.push(lowerCategory);
					} else { // 기존에 등록된 중분류
						groupingExam[categoryIndex].lowerCategory[lowerCategoryIndex].examList.push(examList[i]);
					}
				}
			}
			examineTreeCtrl.examData = groupingExam;
		},
		examData: [],
		examList: []
	};
};
