/**
 * admin/menu
 */
var mplus_admin_auth = function( language_code ){
	//상속
	mplus_admin.call(this);
	
	var self = this;
	//언어코드
	var DEFAULT_LANGUAGE = language_code;
	//변수
	var $txtAuthId = $('#txtAuthId'),
		$txtAuthName = $('#txtAuthName'),
		$txtAuthDesc = $('#txtAuthDesc'),
		$btnSave = $('#btnSave'),
		$btnRemove = $('#btnRemove'),
		$btnSearch = $('#btnSearch'),
		$btnConfirmAttr = $('#btnConfirmAttr'),
		$btnEditPlusAttr = $('#btnEditPlusAttr'),
		$btnEditMinusAttr = $('#btnEditMinusAttr'),
		$crudServiceBaseUrl = contextPath + "/admin/auth"
		$attrCrudServiceBaseUrl = contextPath + "/admin/attr";		//속성 관련 요청을 위해 별도로 작성
		
	var authInfo = {};
	var authList = [];
	var totalCount = 0;
	var plusAttrList = [];
	var plusAttrEditList = [];
	var minusAttrList = [];
	var minusAttrEditList = [];
	var hospitalList = [];
	var dutyList = [];
	var workList = [];
	var attrTypeList = [];
	
	/**
	 * 객체 초기화
	 */
	this.init = function(){
		initAuthList();
		initAttrTypeList();
		//설명 글자수 이벤트 - core에 선언
		self.checkDescBytes($txtAuthDesc);
		addEvent();
		
		if($('#table_authAttr tr')[0]==undefined){
			$('#authDetail').css('display', 'none');
			$('#authDetailEmpty').css('display', 'block');
		}else{
			$('#table_authAttr tr')[0].click();
		};
	};
	/**
	 * 이벤트 등록
	 */
	var addEvent = function(){
		$('#btnNew, #btnNewEmpty').on('click', function(e){
			newItem();
		});
		$btnSave.on('click', function(e){
			saveItem();
		});
		$btnRemove.on('click', function(e){
			removeItem();
		});
		$btnEditPlusAttr.on('click', function(e){
			editAttr('plus');
		});
		$btnEditMinusAttr.on('click', function(e){
			editAttr('minus');
		});
	};
	
	var initAuthList = function(){
		var opt = {
				url: $crudServiceBaseUrl + "/getList.json",
		    	type : "post",
		    	async: false,
		        dataType: "json",
		        contentType: "application/json"
		}
		
		var success = function(result){
			authList = result;
    		totalCount = result.totalCount;
			$('#table_authAttr').empty();
			
			for(var i=0; i<authList.length; i++){
    			var tr = $('<tr></tr>').clone().attr('seq', i).attr('authSeq', authList[i].authSeq).attr('authId', authList[i].authId);
    			var tdAuthId = $('<td></td>').clone().text(authList[i].authId);
    			var tdAuthName = $('<td></td>').clone().text(authList[i].authName);
    			
    			$('#table_authAttr').append(tr.append(tdAuthId).append(tdAuthName));    			
    		};
    		
    		$('#table_authAttr tr').on('click', function(e){
				getAuthInfo(e.currentTarget.attributes.seq.value);
				$('#table_authAttr tr').removeClass('active');
				$(this).addClass('active');
			})
		}
		
		var error = function(xhr,d,t){
    		console.log(xhr);
			console.log(t);
    	};
    	self.ajaxAdmin( opt, success, error );
	};

	var initAttrTypeList = function(){
		var opt = {
				url: $attrCrudServiceBaseUrl + "/getAttrTypeList.json",
		    	type : "post",
		    	async: false,
		        dataType: "json",
		        contentType: "application/json"
		}
		
		var success = function(result){
			var typeList = result.attrTypeList;
			for(var i=0; i<typeList.length; i++){
				if(typeList[i].attrType!='extra'){
					var option = $('<option></option>').clone().attr('value', typeList[i].attrType).text(typeList[i].attrTypeName);
					$('#sltAttrType').append(option);
					
					attrTypeList[typeList[i].attrType] = typeList[i].attrTypeName;
				};				
			};
			$('#sltAttrType').on('change', function(e){
				if(e.currentTarget.value!=''){
					getLowerAttrList(e.currentTarget.value);
				};
			});			
		}
		
		var error = function(xhr,d,t){
    		console.log(xhr);
			console.log(t);
    	};
    	self.ajaxAdmin( opt, success, error );
	};
	
	var getLowerAttrList = function(attrType){
		$('#sltAttr').empty();
		var opt = {
				url: $attrCrudServiceBaseUrl + "/getAttrList.json",
				type: "post",
				dataType: "json",
				async: false,
				contentType: "application/json",
				data: self.util.stringifyJson({
                    attrType: attrType
				})
		};
		var success = function(result){
			var attrList = result.attrList;
			
			var option = $('<option></option>').clone().attr('value', '').text('선택');
			$('#sltAttr').append(option);
			
			for(var i=0; i<attrList.length; i++){
				var option = $('<option></option>').clone().attr('value', attrList[i].attrId).text(attrList[i].attrName);
				$('#sltAttr').append(option);
			};
		};
		var error = function(xhr,d,t){
    		console.log(xhr);
			console.log(t);
    	};
    	self.ajaxAdmin( opt, success, error );
	
	}
	
	var getAuthInfo = function(seq){
		authInfo = authList[seq];
		$txtAuthId.val(authInfo.authId);
		$txtAuthName.val(authInfo.authName);
		$txtAuthDesc.val(authInfo.authDesc);
		
		getAttrList(authInfo.authId, 'plus');
		getAttrList(authInfo.authId, 'minus');
		$txtAuthId.attr('readonly', true);
		
		$('#authDetail').css('display', 'block');
		$('#authDetailEmpty').css('display', 'none');
	};
	
	var getAttrList = function(authId, type){
		var opt = {
				url: $crudServiceBaseUrl + "/getAuthAttrList.json",
		    	type : "POST",
		    	async: false,
		        dataType: "json",
		        contentType: "application/json",
		        data: self.util.stringifyJson({authId: authId,
		        	authType: type})
		}
		
		var success = function(result){
			if(type=='plus'){
				plusAttrList = result;
				$('#table_plusAuth_view').empty();
	    		for(var i=0; i<plusAttrList.length; i++){
	    			var tr = $('<tr></tr>').clone().attr('seq', i);
	    			var tdAuthId = $('<td></td>').clone().text(attrTypeList[plusAttrList[i].authAttrType]);
	    			var tdAuthName = $('<td></td>').clone().text(plusAttrList[i].attrName);
	    			
	    			$('#table_plusAuth_view').append(tr.append(tdAuthId).append(tdAuthName));    			
	    		}
			}else{
				minusAttrList = result;
				$('#table_minusAuth_view').empty();
	    		for(var i=0; i<minusAttrList.length; i++){
	    			var tr = $('<tr></tr>').clone().attr('seq', i);
	    			var tdAuthId = $('<td></td>').clone().text(attrTypeList[minusAttrList[i].authAttrType]);
	    			var tdAuthName = $('<td></td>').clone().text(minusAttrList[i].attrName);
	    			
	    			$('#table_minusAuth_view').append(tr.append(tdAuthId).append(tdAuthName));    			
	    		}
			};			
		}
		
		var error = function(xhr,d,t){
    		console.log(xhr);
			console.log(t);
    	};
    	self.ajaxAdmin( opt, success, error );
	};
	
	var newItem = function(){
		authInfo = {};
		$txtAuthId.val('');
		$txtAuthName.val('');
		$txtAuthDesc.val('');
		plusAttrList = [];
		plusAttrEditList = [];
		minusAttrList = [];
		minusAttrEditList = [];
		$('#table_plusAuth_view').empty();
		$('#table_minusAuth_view').empty();
		$txtAuthId.attr('readonly', false);
		
		$('#table_authAttr tr').removeClass('active');
		
		$('#authDetail').css('display', 'block');
		$('#authDetailEmpty').css('display', 'none');
		
		$txtAuthId.focus();
	};
	
	var saveItem = function(){
		var param = {};
		var authAttrList = [];
		if($txtAuthId.val()==''){
			alert('아이디를 입력해주세요.');
			return;
		};
		if($txtAuthName.val()==''){
			alert('이름을 입력해주세요.');
			return; 
		};
		
		for(var i=0; i<plusAttrList.length; i++){
			authAttrList.push({'attrName': plusAttrList[i].attrName,
							 'attrTypeName': plusAttrList[i].attrTypeName,
							 'authAttrId': plusAttrList[i].authAttrId,
							 'authAttrType': plusAttrList[i].authAttrType,
							 'authId': authInfo.authId,
							 'authType': 'plus'
			});
		};
		for(var j=0; j<minusAttrList.length; j++){
			authAttrList.push({'attrName': minusAttrList[j].attrName,
				 'attrTypeName': minusAttrList[j].attrTypeName,
				 'authAttrId': minusAttrList[j].authAttrId,
				 'authAttrType': minusAttrList[j].authAttrType,
				 'authId': authInfo.authId,
				 'authType': 'minus'
			});
		};
		if(authInfo.authId==undefined){
			param = {
					authId: $txtAuthId.val(),
					authName: $txtAuthName.val(),
					authDesc: $txtAuthDesc.val(),
					authSeq: null,
					authAttrList: authAttrList
			}
		}else{
			param = {
					authId: authInfo.authId,
					authSeq: authInfo.authSeq,
					authName: $txtAuthName.val(),
					authDesc: $txtAuthDesc.val(),
					authAttrList: authAttrList,
			}
		};
		
		var opt = {
				url : $crudServiceBaseUrl + "/save.json",
				method : "POST",
				data : self.util.stringifyJson(param),
				dataType : "json",
				contentType: "application/json; charset=UTF-8"
    	};
    	var success = function(data){
    		alert("저장 되었습니다");
    		initAuthList();
    		$('#table_authAttr tr[authId='+data.authId+']').click(); 
    	};
    	var error = function(xhr,d,t){
    		console.log(xhr);
			console.log(t);
    	};
    	self.ajaxAdmin( opt, success, error );
	};
	
	var removeItem = function(e){
		if($('#table_authAttr tr.active').length==0){
			alert('삭제할 권한을 선택해주세요.');
			return;
		};
		if(confirm('해당 권한을 삭제하시겠습니까?')){
			var param = {
					authId: authInfo.authId	
				};
				var opt = {
						url : $crudServiceBaseUrl + "/remove.json",
						method : "POST",
						data : self.util.stringifyJson(param),
						dataType : "json",
						contentType: "application/json; charset=UTF-8"
		    	};
		    	var success = function(data){
		    		alert("삭제 되었습니다");
		    		initAuthList();
		    		$('#authDetail').css('display', 'none');
					$('#authDetailEmpty').css('display', 'block');
		    	};
		    	var error = function(xhr,d,t){
		    		console.log(xhr);
					console.log(t);
		    	};
		    	self.ajaxAdmin( opt, success, error );
		}		
	}
	
	var editAttr = function(type){
		$("#sltAttrType").val($("#sltAttrType option:first").val());
		$("#sltAttr").val('');
		var viewList = [];
		var editList = [];
		if(type=='plus'){
			$('#modalHeaderText').text('⊙ 속성 추가 리스트 정보');
			viewList = plusAttrList;
			editList = plusAttrEditList;
		}else{
			$('#modalHeaderText').text('⊙ 속성 제거 리스트 정보');
			viewList = minusAttrList;
			editList = minusAttrEditList;
		};
		$('#table_attr').empty();
		
		for (var i = 0; i < viewList.length; i++) {
			var tr = $('<tr itemData="' + viewList[i].authAttrId + '/' + viewList[i].authAttrType + '"></tr>').clone();
			var tdAttrType = $('<td></td>').clone().text(attrTypeList[viewList[i].authAttrType]);
			var tdAttrName = $('<td></td>').clone().text(viewList[i].attrName);
			var tdEdit = $('<td></td>').clone().append(
					'<button type="button" class="btn btn-default  btn-xs" itemData="' + viewList[i].authAttrId + '/' + viewList[i].authAttrType + '"><span class="glyphicon glyphicon-minus">&nbsp;삭제</span></button>');

			$('#table_attr').append(tr.append(tdAttrType).append(tdAttrName).append(tdEdit));
		};
		
		editList = [];
		$.extend(editList, viewList); // 객체 복사, 위의 방식으로하면 객체 공유가 되어버림!
		
		if(type=='plus'){
			plusAttrEditList = editList;
		}else{
			minusAttrEditList = editList;
		};
		
		$('#btnSaveAttr').unbind();
		$('#btnSaveAttr').on('click', function() {
			var param = {
				'authAttrType' : $('#sltAttrType').val(),
				'attrTypeName': $('#sltAttrType option:selected').text(),
				'authAttrId' : $('#sltAttr').val(),
				'attrName' : $('#sltAttr option:selected').text()
			};
			saveItemAttr(param, 'new', type);
		});
		$('#btnConfirmAttr').unbind();
		$('#btnConfirmAttr').on('click', function(){
			confirmItemAttr(type);
		});
		$('#btnNewItem_attr').unbind();
		$('#btnNewItem_attr').on('click', function(){
			newItemAttr(type);
		});
				
		$('#table_attr tr').unbind();
		$('#table_attr tr').on('click', function(e) {
			editItemAttr(e, type);
			$('#table_attr tr').removeClass('active');
			$(this).addClass('active');
		});
		$('#table_attr tr td button').unbind();
		$('#table_attr tr td button').on('click', function(e) {
			removeItemAttr(e, type);
		});
		
		$('#attrModal').modal('show');
		
		$('#attrModal').on('shown.bs.modal', function () {
			$('#sltAttrType').focus();
		});
		
		if($('#table_attr tr').length>0){
			$('#table_attr tr')[0].click();
			$('#modalAttrDetail').css('display', 'block');
			$('#modalAttrDetailEmpty').css('display', 'none');
		}else{
			$('#modalAttrDetail').css('display', 'none');
			$('#modalAttrDetailEmpty').css('display', 'block');
		};
	};
	
	var newItemAttr = function(type) {
		$("#sltAttrType").val($("#sltAttrType option:first").val());
		$("#sltAttr").val('');
		$('#table_attr tr').removeClass('active');
		$('#modalAttrDetail').css('display', 'block');
		$('#modalAttrDetailEmpty').css('display', 'none');
		
		$('#sltAttrType').focus();

		$('#btnSaveAttr').unbind();
		$('#btnSaveAttr').on('click', function() {
			var param = {
				'authAttrType' : $('#sltAttrType').val(),
				'attrTypeName': $('#sltAttrType option:selected').text(),
				'authAttrId' : $('#sltAttr').val(),
				'attrName' : $('#sltAttr option:selected').text()
			};
			saveItemAttr(param, 'new', type);
		});
	};
	
	var saveItemAttr = function(param, newYn, type){
		if(param.authAttrType == '' || param.authAttrType == null || param.authAttrId == '' || param.authAttrId == null){
			alert('저장할 속성을 선택해주세요.');
			return;
		};
		
		if($('#table_attr tr[class!="active"][itemData="'+param.authAttrId + '/' + param.authAttrType +'"]').length>0){
			alert('이미 추가된 속성입니다.');
			return;
		};
		
		if(newYn=='edit'){	
			olderValue = $('#table_attr tr.active')[0].attributes.itemData.value;
			olderValueAuthAttrId = olderValue.split('/')[0];
			olderValueAuthAttrType = olderValue.split('/')[1];
			$('#table_attr tr[itemData="'+olderValue+'"]')[0].children[0].innerText=param.attrTypeName;
			$('#table_attr tr[itemData="'+olderValue+'"]')[0].children[1].innerText=param.attrName;
			$('#table_attr tr[itemData="'+olderValue+'"]')[0].children[2].children[0].attributes.itemData.value=param.authAttrId + '/' + param.authAttrType;
			$('#table_attr tr[itemData="'+olderValue+'"]')[0].attributes.itemdata.value=param.authAttrId + '/' + param.authAttrType;
			if(type=='plus'){
				for(var i=0; i<plusAttrEditList.length; i++){
					if(plusAttrEditList[i].authAttrId==olderValueAuthAttrId
							&& plusAttrEditList[i].authAttrType==olderValueAuthAttrType){
						plusAttrEditList[i].authAttrId = param.authAttrId;
						plusAttrEditList[i].attrName = param.attrName;
						plusAttrEditList[i].authAttrType = param.authAttrType;
						plusAttrEditList[i].attrTypeName = param.attrTypeName;
					}
				};
			}else{
				for(var i=0; i<minusAttrEditList.length; i++){
					if(minusAttrEditList[i].authAttrId==olderValueAuthAttrId
							&& minusAttrEditList[i].authAttrType==olderValueAuthAttrType){
						minusAttrEditList[i].authAttrId = param.authAttrId;
						minusAttrEditList[i].attrName = param.attrName;
						minusAttrEditList[i].authAttrType = param.authAttrType;
						minusAttrEditList[i].attrTypeName = param.attrTypeName;
					}
				};
			}
		}else{
			var tr = $('<tr itemData="'+ param.authAttrId + '/' + param.authAttrType +'"></tr>').clone();
			var tdName = $('<td></td>').clone().text(attrTypeList[param.authAttrType]);
			var tdValue = $('<td></td>').clone().text(param.attrName);
			var tdEdit = $('<td></td>').clone().append(
					'<button type="button" class="btn btn-default  btn-xs" itemData="' + param.authAttrId + '/' + param.authAttrType + '"><span class="glyphicon glyphicon-minus">&nbsp;삭제</span></button>');

			$('#table_attr').append(tr.append(tdName).append(tdValue).append(tdEdit));
			
			if(type=='plus'){
				plusAttrEditList.push(param);
			}else{
				minusAttrEditList.push(param);
			}
		};
		

		$('#table_attr tr').unbind();
		$('#table_attr tr').on('click', function(e) {
			editItemAttr(e, type);
			$('#table_attr tr').removeClass('active');
			$(this).addClass('active');
		});

		$('#table_attr tr td button').unbind();
		$('#table_attr tr td button').on('click', function(e) {
			removeItemAttr(e, type);
		});
		
		$('#table_attr tr[itemData="'+ param.authAttrId + '/' + param.authAttrType +'"]').click();
	};
	
	var getItemData = function(itemList, tableCheckValue, checkValue){
		var itemData = {};
		var tableCheckValue1 = tableCheckValue.split('/')[0];
		var tableCheckValue2 = tableCheckValue.split('/')[1];
		var checkValue1 = checkValue.split('/')[0];
		var checkValue2 = checkValue.split('/')[1];
		for(i=0; i<itemList.length; i++){
			if(itemList[i][tableCheckValue1] == checkValue1
					&& itemList[i][tableCheckValue2] == checkValue2){
				itemData = itemList[i];
				break;
			}
		};
		return itemData;
	};
	
	var editItemAttr = function(e, type) {		
		var editList = [];
		if(type=='plus'){
			editList = plusAttrEditList;
		}else{
			editList = minusAttrEditList;
		};
		var itemData = getItemData(editList, 'authAttrId/authAttrType', e.currentTarget.attributes.itemData.value);
		
		if(itemData==undefined || itemData ==null){
			alert('정상적인 데이터가 아닙니다.'); //이표시가 맞을까?
			return;
		};
		
		$('#sltAttrType').val(itemData.authAttrType);
		getLowerAttrList(itemData.authAttrType);
		$('#sltAttr').val(itemData.authAttrId);

		$('#btnSaveAttr').unbind();
		$('#btnSaveAttr').on('click', function() {
			var param = {
				'authAttrType' : $('#sltAttrType').val(),
				'attrTypeName': $('#sltAttrType option:selected').text(),
				'authAttrId' : $('#sltAttr').val(),
				'attrName' : $('#sltAttr option:selected').text()
			};
			saveItemAttr(param, 'edit', type);
		});
		
		$('#modalAttrDetail').css('display', 'block');
		$('#modalAttrDetailEmpty').css('display', 'none');
	};
	
	var removeItemAttr = function(e, type){
		$('#table_attr tr[itemData="'+e.currentTarget.attributes.itemData.value+'"]').remove();
		var editList = [];
		if(type=='plus'){
			editList = plusAttrEditList;
		}else{
			editList = minusAttrEditList;
		};
		var olderValue = e.currentTarget.attributes.itemData.value;
		var olderValueAuthAttrId = olderValue.split('/')[0];
		var olderValueAuthAttrType = olderValue.split('/')[1];
		
		for(var i=0; i<editList.length; i++){
			if(editList[i].authAttrId == olderValueAuthAttrId
					&& editList[i].authAttrType == olderValueAuthAttrType){
				editList.splice(i, 1);
				break;
			}
		};
		$('#table_attr tr').removeClass('active');
		
		$('#modalAttrDetail').css('display', 'none');
		$('#modalAttrDetailEmpty').css('display', 'block');
	};
	var confirmItemAttr = function(type){
		$('#attrModal').modal('hide');
		$('#table_'+type+'Auth_view').empty();
		var editList = [];
		var viewList = [];
		
		if(type=='plus'){
			editList = plusAttrEditList;
			viewList = plusAttrList;
		}else{
			editList = minusAttrEditList;
			viewList = minusAttrList;
		};
		
		for (var i = 0; i < editList.length; i++) {
			var tr = $('<tr>').clone();
			var tdAttrType = $('<td></td>').clone().text(attrTypeList[editList[i].authAttrType]);
			var tdAttrName = $('<td></td>').clone().text(editList[i].attrName);

			$('#table_'+type+'Auth_view').append(tr.append(tdAttrType).append(tdAttrName));
		};
		viewList = [];
		$.extend(viewList, editList); // 객체 복사
		
		if(type=='plus'){
			plusAttrList = viewList;
		}else{
			minusAttrList = viewList;
		};
		
	};	
}; 
var rowNum = 0;
function resetRowNum(){
	rowNum = 0;
}
function getNum(){
	return ++rowNum;
}