/**
 * admin/menu
 */
var mcare_admin_extraAttr = 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"),
		$menuType = $("#menuType"),
		$extraAttrUsers = $("#extraAttrUsers"),
		$extraAttrDesc = $("#extraAttrDesc"),
		$crudServiceBaseUrl = contextPath + "/admin/extraAttr"
		$attrCrudServiceBaseUrl = contextPath + "/admin/userAttr";		//속성 관련 요청을 위해 별도로 작성
	
	var attrTyes = null;
		
	//트리
	this.treeView;
	this.extraAttrUsersGrid = null;
	/**
	 * 객체 초기화
	 */
	this.init = function(){
		initSplitter();
		initTree();
		initGrid();
		initAttrTypeList();
		//설명 글자수 이벤트 - core에 선언
		self.checkDescBytes($extraAttrDesc);
		addEvent();
	};
	/**
	 * 이벤트 등록
	 */
	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);
	    });
	};
	
	/**
	 * 화면에서 사용하는 속성 조회
	 */
	var initAttrTypeList = function(){
		$.ajax ({
		  url : '/mcare-plus/admin/attr/getAttrTypeList.json',
		  type : 'POST',
		  success: function(result){
			  hospitalList = result.hospital;
			  dutyList = result.duty;
			  workList = result.work;
			  attrTypeList = result.attrType;
			  searchTypeList = [{attrId: 'userId', attrName: '아이디'},{attrId: 'userName', attrName: '이름'}];
		  }
		 })
	};
	
	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",
 			enabledYn: "Y",
 			authYn: "Y",
 			authViewYn: "N",
 			aggYn: "N",
 			accessUriAddr: "",
 			imageUriAddr: "",
 			extraAttrDesc: "",
 			childCount: 0,
 			i18ns: [],
 			addedNode: true,
 			selected: false,
 			menuParam : []
  		};
    	node = null;
			
		nodeData = $.extend(true, {}, {
			menuType: 'MAIN'
		}, defData);
			
     	/*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.extraAttrName==undefined || item.extraAttrName === null || item.extraAttrName === "" ) {
    		alert( "메뉴명이 누락되었습니다" );
    		return false;
    	}
    	    	
    	console.log(self.util.stringifyJson($extraAttrUsers.data("kendoGrid").dataSource.data()));
    	var param = $.extend(true, {}, item, {
    		extraAttrUserList : $extraAttrUsers.data("kendoGrid").dataSource.data()
        }, 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 : { extraAttrId : item.extraAttrId },
					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){
		self.treeView.select( null );
	};
	
	/**
	 * 데이터소스 설정
	 */
	// tree 데이터소스
    var treeDataSource = new kendo.data.HierarchicalDataSource({
        transport: {
            read: {
                url: $crudServiceBaseUrl + "/getList.json",
            	method : "post",
                dataType: "json"
            }
        },
        schema : {
            model : {
                id: "extraAttrId",
                hasChildren: function(){
                	return (this.get("childCount") > 0);
                }
            }
        }
    });

	/**
	 * 트리 초기화
	 */
	var initTree = function(){	    
	    //kendo tree
		var option = {
		    	loadOnDemand: false,
		        dataSource : treeDataSource,
		        dataTextField : "extraAttrName",
		        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.extraAttrName;
	    };
	    /**
	     * 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) {
            	
            });
            self.extraAttrUsersGrid.dataSource.read({"extraAttrId" : item.extraAttrId} );
            kendo.bind( $wrapper, observer );
            if( observer.extraAttrId !== undefined && observer.extraAttrId !== null ){
            	$("#extraAttrId").prop("disabled",true);
            } else {
            	$("#extraAttrId").prop("disabled",false);
            }
           //설명 글자수제한 초기화
           $extraAttrDesc.trigger("keyup");
	    };
	    /**
	     * tree expand
	     * @private
	     * @description 트리 펼치기
	     */
	    function treeExpand(o){
//	    	var sourceData = this.dataItem(o.node);
//            if( !sourceData.get("enabled") ) {
//                return o.preventDefault();
//            }
	    };
	};
	var dataSource = new kendo.data.DataSource({
        transport: {
            read: function(options) {
                $.ajax({
                    url: $crudServiceBaseUrl + "/getExtraAttrUserList.json",
                    dataType: "json",
                    contentType : "application/json",
                    data: options.data.extraAttrId==undefined? "": {extraAttrId: options.data.extraAttrId},
            		success: function(result) {
                        options.success(result);
                      },
                    complate: function(result) {
                    	if(result.msg!=undefined){
                    		gridReadComplete(result);
                    	};
                    }
                });
            },
			create: function(e) {
				$("#extraAttrUsers").data("kendoGrid").dataSource.data().remove($("#extraAttrUsers").data("kendoGrid").dataSource.data()[$("#extraAttrUsers").data("kendoGrid").dataSource.data().length-1]);
				$("#extraAttrUsers").data("kendoGrid").dataSource.data().push(
						createData
						);
				return true; 
			},
			destroy: function(e) {
				console.log(e)
				return true; 
			}
        },
        serverPaging: true,
        serverSorting: true,
        schema: {
            data: function(response) {
            	return response;
            },
            total: function(response){
            	return response.length;
            },
            model: {
				id: "userId",
				fields: {
					userId: { type: "string", editable: false, nullable: false, validation: { required: true }},
					userName: { type: "string", editable: false, nullable: false, validation: { required: true }},
					hospitalId: { type: "string", nullable: false, validation: { required: true }},
					dutyId: { type: "string", nullable: false,validation: { required: true }},
					workId: { type: "string", nullable: false, validation: { required: true }}
				}
			}
        }
    });
	
	/**
	 * 그리드 초기화
	 */
	var initGrid = function(){		
		var grid = $("#extraAttrUsers").kendoGrid({
			dataSource : dataSource,
            sortable: true,
            resizable: true,
			toolbar : [{name: "create", text: "추가"}],
			columns : [
			           {field : "userId", title:"사용자ID", attributes: {style: "text-align: center;"}}
						,{field : "userName", title : "이름", attributes: {style: "text-align: center;"}}
						,{field : "hospitalName", title : "소속", attributes: {style: "text-align: center;"}}
						,{field : "dutyName", title : "직무", attributes: {style: "text-align: center;"}}
						,{field : "workName", title : "업무", attributes: {style: "text-align: center;"}}
						,{command : [{name:"destroy",text:"삭제"}], title : "", attributes: {style: "text-align: center;"}}
			           ],
			editable: {
				createAt : "bottom",
            	mode: "popup",
            	template: $('#popTemplate').html()
            },
            edit: function(e) {
        		var editWindow = this.editable.element.data("kendoWindow");
                $('.k-edit-form-container').css('width', '580px');
				editWindow.wrapper.css({ top: "20%" });
				$("div[id=createDataBox]").hide();
				popInitGrid();

			    $("#pop-search").on("click", function(e) {
			    	popSearchUserAttr(e);
			    });
			    $("#pop-select-hospital").width(100).kendoDropDownList({
				    dataSource: hospitalList,
				    dataTextField: "attrName",
		            dataValueField: "attrId",
		            optionLabel: {
		            	attrName: "전체",
		                attrId: ""
		            }
				});
			  $("#pop-select-duty").width(100).kendoDropDownList({
				    dataSource    : dutyList,
				    dataTextField: "attrName",
		            dataValueField: "attrId",
		            optionLabel: {
		            	attrName: "전체",
		                attrId: ""
		            }
				});
			  $("#pop-select-work").width(100).kendoDropDownList({
				    dataSource    : workList,
				    dataTextField: "attrName",
		            dataValueField: "attrId",
		            optionLabel: {
		            	attrName: "전체",
		                attrId: ""
		            }
				});
			  $("#pop-select-user").width(100).kendoDropDownList({
				    dataSource    : searchTypeList,
				    dataTextField: "attrName",
		            dataValueField: "attrId",
		            optionLabel: {
		            	attrName: "전체",
		                attrId: ""
		            }
				});
            },
            dataBound: function () {
                var rowCount = $extraAttrUsers.find( ".k-grid-content tbody tr" ).length;
                if( rowCount < dataSource._take ) {
                    var addRows = dataSource._take - rowCount;
                    for( var i = 0; i < addRows; i++ ) {
                         $extraAttrUsers.find( ".k-grid-content tbody" )
                            .append( "<tr class='kendo-data-row'><td>&nbsp;</td></tr>" );
                    }
                }
            }
		}).data("kendoGrid");
		
		function i18nDropDownEditor(container, options) {
			$("[data-id='i18nDropDownEditor']:first").clone().attr("data-bind", "value:" + options.field).appendTo(container).kendoDropDownList({autoBind: false});
		}
		
		$(".k-button k-button-icontext myCustomClass k-grid-test").click(function() {
		    alert("Click!");
		});
		
		/**
		 * 파라미터 LOV
		 */
		function reqParamTypeDropDownEditor(container, options) {
			$("[data-id='reqParamTypeDropDownEditor']:first").clone().attr("data-bind", "value:" + options.field).appendTo(container).kendoDropDownList({autoBind: false});
		}
		self.extraAttrUsersGrid = self.grid ( $extraAttrUsers, grid );
		
	};
    /**
     * 그리드 초기화
     */
    var popInitGrid = function(){
    	// 그리드 옵션
        var grid = $("#grid3").kendoGrid({
            dataSource: popDataSource,
            pageable: true,
            sortable: true,
            resizable: true,
            selectable: true,
            height: 400,
            columns: [
                 { title: "", width: 30, template: '<input type="radio" name="attrAddUser"/>'}
                ,{ field: "userId", title: "아이디", width: 80, attributes: {style: "text-align: center;"}}
                ,{ field: "userName", title: "이름", width: 100, attributes: {style: "text-align: center;"}}
                ,{ field: "userAttrOrder", title: "순서", width: 50, hidden: true, attributes: {style: "text-align: center;"}}
                ,{ field: "hospitalId", title: "소속ID", width: 120, hidden: true, attributes: {style: "text-align: center;"}}
                ,{ field: "hospitalName", title: "소속", width: 120, attributes: {style: "text-align: center;"}}
                ,{ field: "dutyId", title: "직무ID", width: 120, hidden: true, attributes: {style: "text-align: center;"}}
                ,{ field: "dutyName", title: "직무", width: 120, attributes: {style: "text-align: center;"}}
                ,{ field: "workId", title: "업무ID", width: 80, hidden: true, attributes: {style: "text-align: center;"}}
                ,{ field: "workName", title: "업무", width: 80, attributes: {style: "text-align: center;"}}
            ],
            change: function(data, arg){
            	$('input[name=attrAddUser]').removeAttr("checked");
            	$('input[name=attrAddUser]')[$(this.select()).index()].checked=true
            	var selected = this.select(),
                item = this.dataItem(selected);
            	$('.k-edit-field input[name="userId"]').val(item.userId);
            	$('.k-edit-field input[name="hospitalName"]').val(item.hospitalId);
            	$('.k-edit-field input[name="dutyName"]').val(item.dutyId);
            	$('.k-edit-field input[name="workName"]').val(item.workId);
            	createData = item;
            },
            dataBound: function () {
                var rowCount = $('#grid3').find( ".k-grid-content tbody tr" ).length;
                if( rowCount < popDataSource._take ) {
                    var addRows = popDataSource._take - rowCount;
                    for( var i = 0; i < addRows; i++ ) {
                         $('#grid3').find( ".k-grid-content tbody" )
                            .append( "<tr class='kendo-data-row'><td>&nbsp;</td></tr>" );
                    }
                };
            }
			}).data("kendoGrid");
	       
        };    
		var popDataSource = new kendo.data.DataSource({
	        transport: {
	            read: {
	                url: $attrCrudServiceBaseUrl + "/getList.json",
	                method: "post",
	                dataType: "json",
	                contentType: "application/json",
	                complete: gridReadComplete
	            },
	            parameterMap: function parameterMap( options, operation ){
	    			kendo.ui.progress($("#grid3"), true);
	    			var param = $.extend(true, {}, options, {
	    				hospitalId: $('#pop-select-hospital').val(),
	    				dutyId : $('#pop-select-duty').val(),
	    				workId : $('#pop-select-work').val(),
	    				selectUserType : $('#pop-select-user').val(),
	    				searchText : $('#pop-search-text').val(),
	    				userAttrOrder: "1"
	                }, null);
	    			console.log(self.util.stringifyJson( param ));
	            	return self.util.stringifyJson( param );
	    		}
	        },
	        selectable: "row",
	        pageSize: 10,
	        serverPaging: true,
	        serverSorting: true,
	        schema: {
	            data: "data",
	            total: "totalCount",
	            model: {
					id: "userId",
					fields: {
						userId: { type: "string", nullable: false, validation: { required: true }},
						userName: { type: "string", nullable: false, validation: { required: true }},
						userAttrOrder: { type: "string", nullable: false, validation: { required: true }},
						hospitalId: { type: "string", nullable: false, validation: { required: true }},
						dutyId: { type: "string", nullable: false,validation: { required: true }},
						workId: { type: "string", nullable: false, validation: { required: true }}
					}
				}
	        }
	    });

    function popSearchUserAttr(e) {
    	popDataSource.page(1);
    };
    
    /**
	 * 그리드 이벤트 동작 complate
	 * @private
	 */
	function gridActionComplete( e ){
		kendo.ui.progress($(".main-wrapper"), false);
		var result = self.util.parseJson( e.responseText );
		if( result.msg ){
			alert( result.msg );
			if( result.type == "AuthException" ){
				window.location.href = contextPath + "/admin/logout.page";
				return;
			}	
		};
		$extraAttrUsers.data("kendoGrid").dataSource.read(); 
	};
	/**
	 * 그리드 이벤트 동작 complate
	 * @private
	 */
	function gridReadComplete( e ){
		var result = self.util.parseJson( e.responseText );
		if( result.msg ){
			alert( result.msg );
			if( result.type == "AuthException" ){
				window.location.href = contextPath + "/admin/logout.page";
				return;
			}	
		}
	};
	
	
	// 저장하지 않은 아이템 배열
    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;
}