/**
 * admin/vers
 */
var mplus_admin_manager = function(){
	//상속
	mplus_admin.call(this);
	
	var self = this;
	//변수
	var $crudServiceBaseUrl = contextPath + "/admin/manager";
	/**
	 * 초기화
	 */
	this.init = function(){
		initManagerList(1);
		setPageList(1);
		if($('#page_1')!=null) $('#page_1').addClass('active');
		addEvent();
	};
	/**
	 * 이벤트 등록
	 */
	var addEvent = function(){
		$('#btnCreate, #btnCreateEmpty').on('click', function(){
			newManager();
		});
		$('#btnRemove').on('click', function(){
			removeManager();
		});
		$('#btnSave').on('click', function(){
			saveManager();
		});
	};
	var managerList = [];
	var totalCount = '';
	var saveType = '';
	var pageSize = 15;
	
    /**
     * 그리드 초기화
     */
    var initManagerList = function(page){
    	var opt = {
				url: $crudServiceBaseUrl + "/getList.json",
				async: false,
				type: "post",
				dataType: "json",
				contentType: "application/json",
				data: self.util.stringifyJson({
					pageSize: pageSize, 
					page: page
				})
			};
    	var success = function(result){
    		managerList = result.data;
    		totalCount = result.totalCount;
    		$('#table_manager').empty();
    		for(var i=0; i<managerList.length; i++){
    			var tr = $('<tr></tr>').clone().attr('seq', i).attr('userId', managerList[i].userId);
    			var tdUserId = $('<td></td>').clone().text(managerList[i].userId);
    			var tdUserName = $('<td></td>').clone().text(managerList[i].userName);
    			var tdDeptName = $('<td></td>').clone().text(managerList[i].deptName ==null? '': managerList[i].deptName);
    			var tdEnabledYn = $('<td></td>').clone().addClass('max-width-xs text-center').text(managerList[i].enabledYn);
    			
    			$('#table_manager').append(tr.append(tdUserId).append(tdUserName).append(tdDeptName).append(tdEnabledYn));
    			
    			$('#table_manager tr').on('click', function(e){
    				getManagerInfo(e.currentTarget.attributes.seq.value);
    				$('#table_manager tr').removeClass('active');
    				$(this).addClass('active');
    			});
    		}
    		
			if($('#table_manager tr')[0]==undefined){
				$('#managerDetail').css('display', 'none');
				$('#managerDetailEmpty').css('display', 'block');
			}else{
				$('#table_manager tr')[0].click();
			}
    	};
    	var error = function(xhr,d,t){
    		console.log(xhr);
			console.log(t);
    	};
    	self.ajaxAdmin( opt, success, error );
    };
    
    var pageEvent = function(e) {
    	var type = e.currentTarget.id.split('_')[0];
    	var page = Number(e.currentTarget.id.split('_')[1]);
    	
    	if( type == 'page' ) {
    		initManagerList(page);
    		$('#ulPagination li[id*="page_"]').removeClass('active');
    	} else if ( type == 'next') {
    		initManagerList(page);
    		setPageList(page);
    	} else if ( type == 'previous' ) {
    		initManagerList(page);
    		setPageList(page - 9);
    	}
    	
    	if($('#page_'+page)!=null) $('#page_'+page).addClass('active');
    };
    
    var setPageList = function(start) {
    	$('#ulPagination').empty();
    	
    	var end = start + 9;
    	if( Math.ceil(totalCount/pageSize) < end ) {
    		end = Math.ceil(totalCount/pageSize);
    	}
    	
    	if( start > 10 ) {
    		$('#ulPagination').append('<li id="previous_'+(start - 1)+'"><a href="#"><<</a></li>');
    	}
    	    	
    	for( var i = start; i <= end; i++ ) {
    		$('#ulPagination').append('<li id="page_'+i+'"><a href="#">'+i+'</a></li>');
    	}
    	
    	if( end < Math.ceil(totalCount/pageSize) ) {
    		$('#ulPagination').append('<li id="next_'+(end + 1)+'"><a href="#">>></a></li>');
    	}
    	
    	$('#ulPagination li').unbind();
    	$('#ulPagination li').click(function(e) {pageEvent(e);});
    	
    };
    
    var getManagerInfo = function(seq){
    	var managerInfo = managerList[seq];
    	
    	$('#txtSeq').val(seq);
    	$('#txtUserId').val(managerInfo.userId);
    	$('#txtUserName').val(managerInfo.userName);
    	$('#txtPwdValue').val('');
    	$('#txtDeptName').val(managerInfo.deptName);
    	$(':radio[name="enabledYn"][value="'+managerInfo.enabledYn+'"]').prop('checked', true);
    	changeSaveType('edit');
    	
    	$('#managerDetail').css('display', 'block');
		$('#managerDetailEmpty').css('display', 'none');
    };
    
    var changeSaveType = function(type){
    	if(type=='edit'){
    		saveType = 'edit';
    		$('#txtUserId').prop('readonly', true);
    	}else{
    		saveType = 'new';
    		$('#txtUserId').removeAttr('readonly');
    	}
    };
    
    var newManager = function(){
    	changeSaveType('new');
    	
    	$('#txtSeq').val('');
    	$('#txtUserId').val('');
    	$('#txtUserName').val('');
    	$('#txtPwdValue').val('');
    	$('#txtDeptName').val('');
    	$(':radio[name="enabledYn"][value="Y"]').prop('checked', true);
    	
    	$('#table_manager tr').removeClass('active');
    	
    	$('#managerDetail').css('display', 'block');
		$('#managerDetailEmpty').css('display', 'none');
		
		$('#txtUserId').focus();
    };
    
    var removeManager = function(){
    	if($('#table_manager tr.active').length==0){
    		alert('삭제할 계정을 선택해주세요.');
    		return;
    	}
    	/*if($('#txtSeq').val()==null||$('#txtSeq').val()==""){
    		alert('삭제할 계정을 선택해주세요.')
    		return;
    	};*/
    	if(confirm('해당 계정을 삭제하시겠습니까?')){
    		var opt = {
    				url: $crudServiceBaseUrl + "/remove.json",
    				method: "post",
    				dataType: "json",
    				contentType: "application/json",
    				data: self.util.stringifyJson(managerList[$('#txtSeq').val()])
    		};
    		
    		var success = function(result){
    			alert("삭제되었습니다.");
    			if(managerList.length==1){
    				initManagerList(Number($('#ulPagination li.active')[0].id.split('_')[1])-1);
    			}else{
    				initManagerList(Number($('#ulPagination li.active')[0].id.split('_')[1]));
    			}
        	};
        	var error = function(xhr,d,t){
        		console.log(xhr);
    			console.log(t);
        	};
        	self.ajaxAdmin( opt, success, error );
    	};
    };
    
    var saveManager = function(){
    	if($('#txtUserId').val()==''){
    		alert('아이디를 입력해주세요.');
    		return;
    	}
    	if($('#txtUserName').val()==''){
    		alert('이름을 입력해주세요.');
    		return;
    	}
    	if($('#txtPwdValue').val()==''){
    		alert('패스워드를 입력해주세요.');
    		return;
    	}
    	if(saveType=='edit'){
    		var param = managerList[$('#txtSeq').val()];
    		param.userId = $('#txtUserId').val();
	    	param.userName = $('#txtUserName').val();
	    	param.pwdValue = $('#txtPwdValue').val();
	    	param.deptName = $('#txtDeptName').val();
	    	param.enabledYn = $(':radio[name="enabledYn"]:checked').val();
    	}else{
    		for(var i=0; i<managerList.length; i++){
				if(managerList[i].userId == $('#txtUserId').val()){
					alert('동일한 아이디가 존재합니다.');
					$('#txtUserId').focus();
					return false;
				}
			}
			var param = {
					userId: $('#txtUserId').val(),
			    	userName: $('#txtUserName').val(),
			    	pwdValue: $('#txtPwdValue').val(),
			    	deptName: $('#txtDeptName').val(),
			    	enabledYn: $(':radio[name="enabledYn"]:checked').val()
			}
    	}
    	
    	var opt = {
				url: $crudServiceBaseUrl + "/save.json",
				method: "post",
				dataType: "json",
				contentType: "application/json",
				data: self.util.stringifyJson(param)
		};
		
		var success = function(result){
			alert("저장되었습니다.");
			initManagerList(Number($('#ulPagination li.active')[0].id.split('_')[1]));
    	};
    	var error = function(xhr,d,t){
    		console.log(xhr);
			console.log(t);
    	};
    	self.ajaxAdmin( opt, success, error );
    };
};
