/**
 * admin/menu
 */
var mcare_admin_auth = function( language_code ){
	//상속
	mcare_admin.call(this);
	
	var self = this;
	//언어코드
	var DEFAULT_LANGUAGE = language_code;
	//변수
	var $wrapper = $(".main-wrapper #wrapper"),
		$addItem = $("#add-item"),
		$saveItem = $("#save-item"),
		$reloadItem = $("#reload-item"),
		$removeItem = $("#remove-item"),
		$deselectItem = $("#deselect-item"),
		$treeView = $("#tree-view"),
		$addAttrList = $("#addAttrList"),
		$minusAttrList = $("#minusAttrList")
		$authDesc = $("#authDesc");
		
		$crudServiceBaseUrl = contextPath + "/admin/auth"
		$attrCrudServiceBaseUrl = contextPath + "/admin/attr";		//속성 관련 요청을 위해 별도로 작성
		
	var attrTypes;
	var hospitalAttr;
	var dutyAttr;
	var workAttr;
	var extraAttr;
	var attrs = null;
	
	//트리
	this.treeView;
	// this.addAttrListGrid;
	// this.minusAttrListGrid = null;
	this.addAttrList;
	this.minusAttrList;
	
	/**
	 * 객체 초기화
	 */
	this.init = function(){
		// 왼쪽이랑 오른쪽 구분
		initSplitter();
		// 왼쪽 트리
		initTree();
		//설명 글자수 이벤트 - core에 선언
		self.checkDescBytes($authDesc);
		addEvent();
		initAttrTypes();
		initGrid();
	};
	/**
	 * 이벤트 등록
	 */
	var addEvent = function(){
		// 아이템 생성
		$addItem.on("click", function(e) {
	        addItem(e);
	    });	    
	    // 아이템 저장
		$saveItem.on("click",function(e) {
	    	saveItem(e);
	    });	    
	 	// 아이템 갱신 (to 모바일 서버)
	    $reloadItem.on("click",function(e) {
	    	reloadItem(e);
	    }); 
	 	// 아이템 삭제
		$removeItem.on("click",function(e) {
			removeItem(e);
	    }); 
		// 아이템 선택 해제
	    $deselectItem.on("click",function(e) {
	    	deselectItem(e);
	    });

	};
	
	// add 랑 minus 랑 따로 데이터소스를 정의 
	var addAuthAttrDataSource = new kendo.data.DataSource({
		transport: {
            read: function(options) {
				$.ajax({
					url: $crudServiceBaseUrl + "/getAuthAttrList.json",
		            method: "get",
		            dataType: "json",
                    data: {authId: self.selectedAuthId, authType : 'add'},
            		success: function(result) {
                        options.success(result);
                    }
                });
            },
            create: function(e) {
            	e.success();
            },
            destroy: {},
			parameterMap: function( options, operation ) {
				if( operation === "read" ){
					return {authId: self.selectedAuthId, authType : 'add'};
				};
			}
        },
        batch: true,
		schema: {
			data: function(response) {
	      	    return response;
			},
			// 요게 서버에서 속성들을 내려주는 데이터구조
			model: {
				id: "authAttrSeq",
				fields: {
					attrName: { type: "string", editable: true, validation: { required: false }},
					attrTypeName: { type: "string", editable: true, validation: { required: false }},
					authAttrId: { type: "string", editable: true, validation: { required: false }},
					authAttrSeq: { type: "string"},
					authAttrType: { type: "string", editable: true, validation: { required: false }},
					authId: { type: "string"},
					authType: { type: "string"}
				}
			}
		}
	});
	
	// 마이너스 쪽은 걍 손안댔다고보면됨.. add 하고 완료되면 해야지했는데ㅋㅋㅋ
	var minusAuthAttrDataSource = new kendo.data.DataSource({
		transport: {
			read: function(options) {
				$.ajax({
					url: $crudServiceBaseUrl + "/getAuthAttrList.json",
		            method: "get",
		            dataType: "json",
                    data: {authId: self.selectedAuthId, authType : 'minus'},
            		success: function(result) {
                        options.success(result);
                    }
                });
            },
            create: function(e) {
            	e.success();
            },
            destroy: {},
			parameterMap: function( options, operation ) {
				if( operation === "read" ){
					return {authId: self.selectedAuthId, authType : 'minus'};
				} else {
					return;
				}
			}
        },
		schema: {
			data: function(response) {
	      	    return response;
			},
			// 요게 서버에서 속성들을 내려주는 데이터구조
			model: {
				id: "authAttrSeq",
				fields: {
					attrName: { type: "string", editable: true, validation: { required: false }},
					attrTypeName: { type: "string", editable: true, validation: { required: false }},
					authAttrId: { type: "string", editable: true, validation: { required: false }},
					authAttrSeq: { type: "string"},
					authAttrType: { type: "string", editable: true, validation: { required: false }},
					authId: { type: "string"},
					authType: { type: "string"}
				}
			}
		}
	});
	
	
	var initGrid = function () {
		var grid = $addAttrList.kendoGrid({
			dataSource: addAuthAttrDataSource,
			resizable: true,
			sortable: false,
			toolbar: [{ name : "create", text: "추가" }],
    		columns: [
    		           { field: "authAttrType", title: "속성 타입", width: 35, attributes: {style: "text-align: center;"},
    		        	   template: function(data){ 
    		        		   for(var i = 0; i < attrTypes.length; i++) {
    		        			   if(attrTypes[i].attrType == data.authAttrType) 
    		        				   return attrTypes[i].attrTypeName;
    		        	    }}, editor:attrTypeEditor}
    		          ,{ field: "authAttrId", title: "속성",hidden:false, width: 35, attributes: {style: "text-align: center;"}, 
    		        	  template: function(data){ 
    		        		  if(data.authAttrType == "hospital") {
	   		        		   for(var i = 0; i < hospitalAttr.length; i++) {
	   		        			   if(hospitalAttr[i].attrId == data.authAttrId) 
	   		        				   return hospitalAttr[i].attrName;
	   		        		   }
    		        		  } else if(data.authAttrType == "duty") {
	   		        		   for(var i = 0; i < dutyAttr.length; i++) {
	   		        			   if(dutyAttr[i].attrId == data.authAttrId) 
	   		        				   return dutyAttr[i].attrName;
	   		        		   }
    		        		  } else if(data.authAttrType == "work") {
	   		        		   for(var i = 0; i < workAttr.length; i++) {
	   		        			   if(workAttr[i].attrId == data.authAttrId) 
	   		        				   return workAttr[i].attrName;
	   		        		   }
    		        		  } else if(data.authAttrType == "extra") {
	   		        		   for(var i = 0; i < extraAttr.length; i++) {
	   		        			   if(extraAttr[i].attrId == data.authAttrId) 
	   		        				   return extraAttr[i].attrName;
	   		        		   }
    		        		  } 
   		        	    },editor:attrEditor}
    		          ,{ command: [{name:"edit",text:{edit: "편집", update: "저장", cancel: "취소"}},{name:"destroy",text:"삭제"}], title: "&nbsp;", width: 30, attributes: {style: "text-align: center;"}}
    		],
    		editable: {
    			mode:"inline",
            	confirmation:"정말 삭제하시겠습니까?"
    		},
            edit: function(e) {
            	//추가event찍힘
            }
		});
		
		var gridMinus = $minusAttrList.kendoGrid({
			dataSource: minusAuthAttrDataSource,
			resizable: true,
			sortable: false,
			toolbar: [{ name : "create", text: "추가"}],
    		columns: [
    		           { field: "authAttrType", title: "속성 타입", width: 35, attributes: {style: "text-align: center;"},
    		        	   template: function(data){ 
    		        		   for(var i = 0; i < attrTypes.length; i++) {
    		        			   if(attrTypes[i].attrType == data.authAttrType) 
    		        				   return attrTypes[i].attrTypeName;
    		        	    }}, editor:attrTypeEditor}
    		          ,{ field: "authAttrId", title: "속성",hidden:false, width: 35, attributes: {style: "text-align: center;"}, 
    		        	  template: function(data){ 
    		        		  if(data.authAttrType == "hospital") {
	   		        		   for(var i = 0; i < hospitalAttr.length; i++) {
	   		        			   if(hospitalAttr[i].attrId == data.authAttrId) 
	   		        				   return hospitalAttr[i].attrName;
	   		        		   }
    		        		  } else if(data.authAttrType == "duty") {
	   		        		   for(var i = 0; i < dutyAttr.length; i++) {
	   		        			   if(dutyAttr[i].attrId == data.authAttrId) 
	   		        				   return dutyAttr[i].attrName;
	   		        		   }
    		        		  } else if(data.authAttrType == "work") {
	   		        		   for(var i = 0; i < workAttr.length; i++) {
	   		        			   if(workAttr[i].attrId == data.authAttrId) 
	   		        				   return workAttr[i].attrName;
	   		        		   }
    		        		  } else if(data.authAttrType == "extra") {
	   		        		   for(var i = 0; i < extraAttr.length; i++) {
	   		        			   if(extraAttr[i].attrId == data.authAttrId) 
	   		        				   return extraAttr[i].attrName;
	   		        		   }
    		        		  } 
   		        	    },editor:attrEditor}
    		          ,{ command: [{name:"edit",text:"편집"},{name:"destroy",text:"삭제"}], title: "&nbsp;", width: 30, attributes: {style: "text-align: center;"}}
    		],
    		editable: {
    			mode:"inline",
            	confirmation:"정말 삭제하시겠습니까?"
    		},
            edit: function(e) {
            	//추가event찍힘
            }
		});
		
		function attrTypeEditor(container, options) {
			 $('<input required name="' + options.field + '"/>')
	            .appendTo(container)
	            .kendoDropDownList({
	            	dataSource: attrTypes,
				    dataTextField: "attrTypeName",
		            dataValueField: "attrType",
		            change: selectChangeAttr,
		            optionLabel: {
		            	attrTypeName: "선택",
		            	attrType: ""
		            }
	              }).data("kendoDropDownList").select(0);
		};
		function selectChangeAttr(e){
	    	var options= e.sender._selectedValue;
	    	var container = $('.k-grid-edit-row [data-container-for=authAttrId]');
	    	
	    	if( options == 'hospital') {
				container.find('input').data("kendoDropDownList").dataSource.data(hospitalAttr);
			} else if( options == 'duty') {
				container.find('input').data("kendoDropDownList").dataSource.data(dutyAttr);
			} else if( options == 'work') {
				container.find('input').data("kendoDropDownList").dataSource.data(workAttr);
			} else if( options == 'extra') {
				container.find('input').data("kendoDropDownList").dataSource.data(extraAttr);
			};
	    };
		function attrEditor(container, options) {
			var dataSource;
			if(options.model.authAttrType=='hospital'){
				dataSource = hospitalAttr;
			}else if(options.model.authAttrType=='duty'){
				dataSource = dutyAttr;
			}else if(options.model.authAttrType=='work'){
				dataSource = workAttr;
			}else if(options.model.authAttrType=='extra'){
				dataSource = extraAttr;
			};
			$('<input required name="' + options.field + '"/>')
            .appendTo(container)
            .kendoDropDownList({
                autoBind: false,
                dataTextField: "attrName",
                dataValueField: "attrId",
                dataSource: dataSource,
                optionLabel: {
  				  attrId: "",
  				  attrName: "선택"
                  }
              }).data("kendoDropDownList").select(0);
		};
	}
	
	var initSplitter = function(){

		$wrapper.kendoSplitter({
	        panes: [
	            { collapsible: true, resizable: true, size: '240px' },
	            { collapsible: false }
	        ]
	    });
		
		$wrapper.data("kendoSplitter").trigger("resize");
	};
	
	/**
	 * 트리 아이템 신규 이벤트
	 * @private
	 */
	var addItem = function(e){
		var treeView = self.treeView;
		
		addedNodeCheck(e, treeView.dataSource.data().toJSON());
		
        if (addedNodeArr.length > 0) {
        	alert("저장하지 않은 아이템 [ " + addedNodeArr[0].menuName + " ] (이)가 있습니다");
        	addedNodeArr = [];
        	return false;
        }
        
    	var node = treeView.select(),
    		item = treeView.dataItem(node);
    	
    	var nodeData = null,
    		defData = {
			menuType: "CONT",
 			menuName: "NewItem",
 			menuOrder: 0,
 			enabledYn: "Y",
 			authYn: "Y",
 			authViewYn: "N",
 			aggYn: "N",
 			accessUriAddr: "",
 			imageUriAddr: "",
 			authDesc: "",
 			childCount: 0,
 			i18ns: [],
 			addedNode: true,
 			selected: false,
 			menuParam : []
  		};
        
     	/*if( node.length === 0 ) {*/
 			node = null;
 			
 			nodeData = $.extend(true, {}, {
				menuType: 'MAIN'
			}, defData);
 			
        /* } else {
     		if( item.childCount === 0 ) {
     			item.loaded(true);
            }
     		
     		nodeData = $.extend( true, {}, item.toJSON(), {
     			menuId: null,
     			parentMenuId: item.menuId
 			}, defData);
     	}*/
     	
     	treeView.append(nodeData, node);
	};
	
	// 다국어 코드 중복 체크
	var i18nArr = [];
	/**
	 * 트리 아이템 저장 이벤트
	 * @private
	 */
	var saveItem = function(e){
		var treeView = self.treeView;
		
		var node = treeView.select(),
			item = treeView.dataItem(node);
    	
    	if( node.length === 0 ) {
    		alert("선택한 아이템이 없습니다");
    		return false;
    	}
    	
    	if( item.authId === null || item.authId === "" ) {
    		alert( "아이디가 누락되었습니다" );
    		return false;
    	}
    	
    	
    	var addList = $addAttrList.data("kendoGrid").dataSource.data();
    	var minusList = $minusAttrList.data("kendoGrid").dataSource.data();

    	var attrList = [];
    	
    	for(var i=0; i<addList.length; i++) {		
    		var obj = {
	    		authId : addList[i].authId,
	    		authType : "add",
	    		authAttrType : addList[i].authAttrType,
	    		authAttrId : addList[i].authAttrId
	    	};
    		attrList.push(obj);
    	};
    	
    	for(var j=0; j<minusList.length; j++) {
    		var obj = {
	    		authId : minusList[j].authId,
	    		authType : "minus",
	    		authAttrType : minusList[j].authAttrType,
	    		authAttrId : minusList[j].authAttrId
	    	};
    		attrList.push(obj);
    	};
    	
    	var param = $.extend(true, {}, item, {
    		authAttrList : attrList
        }, null);
    	
    	
		var opt = {
				url : $crudServiceBaseUrl + "/save.json",
				method : "POST",
				data : self.util.stringifyJson(param),
				dataType : "json",
				contentType: "application/json; charset=UTF-8",
        		complete : function(){
        			kendo.ui.progress( $wrapper, false );
        		}
    	};
    	var success = function(data){
    		alert("저장 되었습니다");
    		location.reload(true);
    	};
    	var error = function(xhr,d,t){
    		console.log(xhr);
			console.log(t);
    	};
    	self.ajaxAdmin( opt, success, error );
	};
	/**
	 * 트리 아이템 reload 이벤트
	 * @private
	 */
	var reloadItem = function(e){
		kendo.ui.progress( $wrapper, true );
		var opt = {
				url : $crudServiceBaseUrl + "/cacheReload.json",
				type : "POST",
				contentType: "application/json; charset=UTF-8",
        		complete : function(){
        			kendo.ui.progress( $wrapper, false );
        		}
    	};
    	var success = function(data){
    		if( data === 1 ) {
				alert("갱신 되었습니다");
			} else {
				alert( "수행 중 에러가 발생하였습니다" );
			}
    	};
    	var error = function(xhr,d,t){
    		console.log(xhr);
			console.log(t);
    	};
    	self.ajaxAdmin( opt, success, error );
	};
	/**
	 * 트리 아이템 삭제 이벤트
	 * @private
	 */
	var removeItem = function(e){
		var treeView = self.treeView;
		
		var node = treeView.select(),
			item = treeView.dataItem(node);
		
    	if( node.length === 0 ) {
            alert( "선택한 아이템이 없습니다." );
            return false;
        }

    	kendo.unbind( $wrapper );
    	
		if( item.addedNode === true ) {
        	treeView.remove(node);
        } else {
			if( !confirm( "삭제 하시겠습니까?" ) ) {
	    		return false;
	    	}
			
			kendo.ui.progress( $wrapper, true );
			
			var opt = {
					url : $crudServiceBaseUrl + "/remove.json",
					type : "POST",
					data : { authId : item.authId },
					dataType : "json",
	        		complete : function(){
	        			kendo.ui.progress( $wrapper, false );
	        		}
	    	};
	    	var success = function(data){
	    		alert( "삭제 되었습니다" );
	    		location.reload(true);
	    	};
	    	var error = function(xhr,d,t){
	    		console.log(xhr);
				console.log(t);
	    	};
	    	self.ajaxAdmin( opt, success, error );
        }
	};
	/**
	 * 트리 아이템 선택 해제 이벤트
	 * @private
	 */
	var deselectItem = function(e){
		console.log(self.util.stringifyJson(e));
		self.treeView.select( null );
	};


	/**
	 * 데이터소스 설정
	 */
	// tree 데이터소스
    var treeDataSource = new kendo.data.HierarchicalDataSource({
        transport: {
            read: {
                url: $crudServiceBaseUrl + "/getList.json",
            	method : "post",
                dataType: "json"
            }
        },
        schema : {
            model : {
                id: "authId",
                hasChildren: function(){
                	return (this.get("childCount") > 0);
                }
            }
        }
    });

	/**
	 * 트리 초기화
	 */
	var initTree = function(){	    
	    //kendo tree
		var option = {
		    	loadOnDemand: false,
		        dataSource : treeDataSource,
		        dataTextField : "authName",
		        template : treeTemplate,
		        select : treeSelect,
		        expand : treeExpand
		};
	    self.treeView = self.tree( $treeView, option );

	    
	    /**
	     * tree template
	     * @private
	     * @description 트리 구성 
	     */
	    function treeTemplate(o){
        	var span = $("<span></span>").addClass("k-sprite");
        	span.addClass("html");
			
			return span[0].outerHTML + o.item.authName;
	    };
	    /**
	     * tree select
	     * @private
	     * @description 트리 선택
	     */
	    function treeSelect(o){
	    	kendo.unbind( $wrapper );
        	
        	var item = this.dataItem( o.node );
        	console.log(self.util.stringifyJson(item));
            var observer = new kendo.observable( item );
            observer.bind("change", function(o) {
            	
            });
            kendo.bind( $wrapper, observer );
            if( observer.menuId !== undefined && observer.menuId !== null ){
            	$("#authId").prop("disabled",true);
            } else {
            	$("#authId").prop("disabled",false);
            }
           //설명 글자수제한 초기화
           $authDesc.trigger("keyup");
           
           if(item.authId !== undefined) {
        	   // 왼쪽 아이템 선택 시 !!!!!!
        	   self.selectedAuthId = item.authId;
        	   $addAttrList.data("kendoGrid").dataSource.read();
        	   $minusAttrList.data("kendoGrid").dataSource.read();
           }
	    };
	    /**
	     * tree expand
	     * @private
	     * @description 트리 펼치기
	     */
	    function treeExpand(o){
	    };
	};
	
	/**
	 * 속성 데이터 가져오기
	 */
	var initAttrTypes = function() {
		$.ajax({
			url : $attrCrudServiceBaseUrl + "/getAttrTypeList.json",
			method : "POST",
			dataType : "json",
			contentType : "application/json",
			success : function(data){
				attrTypes = data.attrType;
				hospitalAttr = data.hospital;
				dutyAttr = data.duty;
				workAttr = data.work;
				extraAttr = [];
				if(data.extra!=undefined&&data.extra.length>0){
					for(var i=0; i<data.extra.length; i++){
					extraAttr.push({'attrSeq': data.extra[i].extraAttrSeq, 
						'attrId': data.extra[i].extraAttrId,
						'attrName': data.extra[i].extraAttrName
						})
					};
				}
			},
			error : function(xhr,d,t){
			},
			complete: function(){
			}
		});
	}

	// 저장하지 않은 아이템 배열
    var addedNodeArr = [];
    /**
     * 트리 저장하지 않은 아이템 확인
     */
	var addedNodeCheck = function(e, treeViewData) {
    	if( treeViewData ) {
	    	for( var n = 0; n < treeViewData.length; n++ ) {
				 var childData = treeViewData[n];
	   			 if( childData.addedNode === true ){
	   				 addedNodeArr.push( childData );
	   				 return;
	   				
	 			 } else {
		   			var child = childData.items;
		   			if( child ) {
			   			if( child.length > 0 ){
			   				addedNodeCheck( e, child );
			   			}
		   			}
	 			}
	   		}
    	}
    };
}; 
var rowNum = 0;
function resetRowNum(){
	rowNum = 0;
}
function getNum(){
	return ++rowNum;
}