/**
 * admin/agreement
 */
var mplus_admin_agreement = function(){
	//상속
	mplus_admin.call(this);
	
	var self = this;
	//변수
	var $crudServiceBaseUrl = contextPath + "/admin/agreement";
	/**
	 * 초기화
	 */
	this.init = function(){
		initAgreementList(1);
		setPageList(1);
		if($('#page_1')!=null) $('#page_1').addClass('active');
		addEvent();
	};
	/**
	 * 이벤트 등록
	 */
	var addEvent = function(){
		$('#btnCreate, #btnCreateEmpty').on('click', function(){
			newAgreement();
		});
		/*$('#btnRemove').on('click', function(){
			removeAgreement();
		});*/
		$('#btnSave').on('click', function(){
			saveAgreement();
		});
	};
	var agreementList = [];
	var totalCount = '';
	var saveType = '';
	var pageSize = 15;
	
    /**
     * 그리드 초기화
     */
    var initAgreementList = 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){
    		agreementList = result.data;
    		totalCount = result.totalCount;
    		$('#table_agreement').empty();
    		for(var i=0; i<agreementList.length; i++){
    			var tr = $('<tr></tr>').clone().attr('seq', i);
    			/*var tdAgreementId = $('<td></td>').clone().text(agreementList[i].agreementId);*/
    			var tdAgreementName = $('<td></td>').clone().text(agreementList[i].agreementName);
    			var tdAgreementOrder = $('<td></td>').clone().text(agreementList[i].agreementOrder);
    			var tdVersionNumber = $('<td></td>').clone().text(agreementList[i].versionNumber);
    			var tdAgreementCl = $('<td></td>').clone().text(agreementList[i].agreementCl.length>10? agreementList[i].agreementCl.substring(0, 10)+'...':agreementList[i].agreementCl);
    			/*var tdRequiredYn = $('<td></td>').clone().text(agreementList[i].requiredYn);*/
    			var tdEnabledYn = $('<td></td>').clone().text(agreementList[i].enabledYn);
    			/*var tdTypeName = $('<td></td>').clone().text(agreementList[i].typeName=='ALL'? '일반': '14세이하');*/
    			
    			$('#table_agreement').append(tr.append(tdAgreementName).append(tdAgreementOrder)
    					.append(tdVersionNumber).append(tdAgreementCl).append(tdEnabledYn));
    			
    			$('#table_agreement tr').on('click', function(e){
    				getAgreementInfo(e.currentTarget.attributes.seq.value);
    				$('#table_agreement tr').removeClass('active');
    				$(this).addClass('active');
    			});
    		}
    		
    		if($('#table_agreement tr')[0]==undefined){
				$('#agreementDetail').css('display', 'none');
				$('#agreementDetailEmpty').css('display', 'block');
			}else{
				$('#table_agreement 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' ) {
    		initAgreementList(page);
    		$('#ulPagination li[id*="page_"]').removeClass('active');
    	} else if ( type == 'next') {
    		initAgreementList(page);
    		setPageList(page);
    	} else if ( type == 'previous' ) {
    		initAgreementList(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 getAgreementInfo = function(seq){
    	var agreementInfo = agreementList[seq];
    	
    	$('#txtSeq').val(seq);
    	$('#txtAgreementOrder').val(agreementInfo.agreementOrder);
    	$('#txtAgreementId').val(agreementInfo.agreementId);
    	$('#txtAgreementName').val(agreementInfo.agreementName);
    	$('#txtAgreementCl').val(agreementInfo.agreementCl);
    	$(':radio[name="requiredYn"][value="'+agreementInfo.requiredYn+'"]').prop('checked', true);
    	$(':radio[name="enabledYn"][value="'+agreementInfo.enabledYn+'"]').prop('checked', true);
    	$('#sltTypeName').val(agreementInfo.typeName);
    	changeSaveType('edit');
    	
    	$('#agreementDetail').css('display', 'block');
		$('#agreementDetailEmpty').css('display', 'none');
    };
    
    var changeSaveType = function(type){
    	if(type=='edit'){
    		saveType = 'edit';
    		$('#txtAgreementId').prop('readonly', true);
    	}else{
    		saveType = 'new';
    		$('#txtAgreementId').removeAttr('readonly');
    	}
    };
    
    var newAgreement = function(){
    	changeSaveType('new');
    	
    	$('#txtSeq').val('');
    	$('#txtAgreementOrder').val('');
    	$('#txtAgreementId').val('');
    	$('#txtAgreementName').val('');
    	$('#txtAgreementCl').val('');
    	$(':radio[name="requiredYn"][value="Y"]').prop('checked', true);
    	$(':radio[name="enabledYn"][value="Y"]').prop('checked', true);
    	$('#sltTypeName').val('ALL');
    	
    	$('#agreementDetail').css('display', 'block');
		$('#agreementDetailEmpty').css('display', 'none');
		
		$('#txtAgreementId').focus();
    };
    
   /* var removeAgreement = function(){
    	var opt = {
				url: $crudServiceBaseUrl + "/remove.json",
				method: "post",
				dataType: "json",
				contentType: "application/json",
				data: self.util.stringifyJson(agreementList[$('#txtSeq').val()])
		};
		
		var success = function(result){
			alert("삭제되었습니다.");
			initAgreementList(Number($('#ulPagination li.active')[0].id.split('_')[1]));
			newAgreement();
    	};
    	var error = function(xhr,d,t){
    		console.log(xhr);
			console.log(t);
    	};
    	self.ajaxAdmin( opt, success, error );
    };
    */
    var saveAgreement = function(){
    	var saveUrl = '';
    	
    	if($('#txtAgreementId').val()==''){
    		alert('아이디를 입력해주세요.');
    		return;
    	};
    	
    	if($('#txtAgreementName').val()==''){
    		alert('이름을 입력해주세요.');
    		return;
    	};
    	
    	if($('#txtAgreementOrder').val()==''){
    		alert('순서를 입력해주세요.');
    		return;
    	};
    	
    	if($('#txtAgreementCl').val()==''){
    		alert('내용을 입력해주세요.');
    		return;
    	};
    	
    	if(saveType=='edit'){
    		saveUrl = $crudServiceBaseUrl + "/addVersion.json"
    		var param = agreementList[$('#txtSeq').val()];
    		param.agreementOrder = $('#txtAgreementOrder').val();
	    	param.agreementId = $('#txtAgreementId').val();
	    	param.agreementName = $('#txtAgreementName').val();
	    	param.agreementCl = $('#txtAgreementCl').val();
	    	param.requiredYn = $(':radio[name="requiredYn"]:checked').val();
	    	param.enabledYn = $(':radio[name="enabledYn"]:checked').val();
	    	param.typeName = $('#sltTypeName').val();
    	}else{
    		for(var i=0; i<agreementList.length; i++){
				if(agreementList[i].agreementId == $('#txtAgreementId').val()){
					alert('동일한 아이디가 존재합니다.');
					$('#txtAgreementId').focus();
					return false;
				}
			};
			saveUrl = $crudServiceBaseUrl + "/save.json"
			var param = {
					agreementSeq: null,
					agreementOrder: $('#txtAgreementOrder').val(),
					agreementId: $('#txtAgreementId').val(),
					versionNumber: 1, 
					agreementName: $('#txtAgreementName').val(),
					agreementCl: $('#txtAgreementCl').val(),
					requiredYn: $(':radio[name="requiredYn"]:checked').val(),
			    	enabledYn: $(':radio[name="enabledYn"]:checked').val(),
			    	typeName: $('#sltTypeName').val()
			}
    	};
    	
    	var opt = {
				url: saveUrl,
				method: "post",
				dataType: "json",
				contentType: "application/json",
				data: self.util.stringifyJson(param)
		};
		
		var success = function(result){
			alert("저장되었습니다.");
			initAgreementList(Number($('#ulPagination li.active')[0].id.split('_')[1]));
			
			$('#agreementDetail').css('display', 'none');
			$('#agreementDetailEmpty').css('display', 'block');
    	};
    	var error = function(xhr,d,t){
    		console.log(xhr);
			console.log(t);
    	};
    	self.ajaxAdmin( opt, success, error );
    };
};