/**
 * admin/vers
 */
var mplus_admin_version = function(){
	//상속
	mplus_admin.call(this);
	
	var self = this;
	//변수
	var $crudServiceBaseUrl = contextPath + "/admin/version";
	/**
	 * 초기화
	 */
	this.init = function(){
		initAppVersionList(1);
		setPageList(1);
		if($('#page_1')!=null) $('#page_1').addClass('active');
		addEvent();		
	};
	/**
	 * 이벤트 등록
	 */
	var addEvent = function(){
		$('#btnCreate, #btnCreateEmpty').on('click', function(){
			newAppVersion();
		});
		$('#btnRemove').on('click', function(){
			removeAppVersion();
		});
		$('#btnSave').on('click', function(){
			saveAppVersion();
		});
	};

	var appVersionList = [];
	var saveType = '';
	var totalCount = '';
	var pageSize = 15;
    /**
     * 그리드 초기화
     */
    var initAppVersionList = function(page){
    	var opt = {
				url: $crudServiceBaseUrl + "/getAllVersionList.json",
				type: "post",
				async: false,
				dataType: "json",
				contentType: "application/json",
				data: self.util.stringifyJson({
					pageSize: pageSize, 
					page: page
				})
			};
    	var success = function(result){
    		appVersionList = result.data;
    		totalCount = result.totalCount;
    		$('#table_appVersion').empty();
    		for(var i=0; i<appVersionList.length; i++){
    			var tr = $('<tr></tr>').clone().attr('seq', i).attr('appName', appVersionList[i].appName).attr('platformType', appVersionList[i].platformType).attr('certType', appVersionList[i].certType);
    			var tdAppName = $('<td></td>').clone().text(appVersionList[i].appName);
    			var tdPlatformType = $('<td></td>').clone().text(appVersionList[i].platformType=='I'? 'iOS': appVersionList[i].platformType=='A'?'Android': appVersionList[i].platformType);
    			var tdCertType = $('<td></td>').clone().text(appVersionList[i].certType);
    			var tdVersionOrder = $('<td></td>').clone().text(appVersionList[i].versionOrder);
    			/*var tdMarketUrl = $('<td></td>').clone().text(appVersionList[i].marketUrl);*/
    			
    			$('#table_appVersion').append(tr.append(tdAppName).append(tdPlatformType).append(tdCertType).append(tdVersionOrder));
    			
    			$('#table_appVersion tr').on('click', function(e){
    				getAppVersionInfo(e.currentTarget.attributes.seq.value);
    				
    				$('#table_appVersion tr').removeClass('active');
    				$(this).addClass('active');
    			});
    		}
    		
    		if($('#table_appVersion tr')[0]==undefined){
				$('#versionDetail').css('display', 'none');
		    	$('#versionDetailEmpty').css('display', 'block');
			}else{
				$('#table_appVersion 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' ) {
    		initAppVersionList(page);
    		$('#ulPagination li[id*="page_"]').removeClass('active');
    	} else if ( type == 'next') {
    		initAppVersionList(page);
    		setPageList(page);
    	} else if ( type == 'previous' ) {
    		initAppVersionList(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 getAppVersionInfo = function(seq){
    	var versionInfo = appVersionList[seq];
    	
    	$('#versionDetail').css('display', 'block');
    	$('#versionDetailEmpty').css('display', 'none');
    	
    	$('#sltPlatform').val(versionInfo.platformType);
    	$('#sltCertType').val(versionInfo.certType);
    	$('#txtAppName').val(versionInfo.appName);
    	$('#txtVersionOrder').val(versionInfo.versionOrder);
    	$('#txtMarketUrl').val(versionInfo.marketUrl);
    	changeSaveType('edit');
    };
    
    var changeSaveType = function(type){
    	if(type=='edit'){
    		saveType = 'edit';
    		$('#sltPlatform').prop('disabled', true);
    		$('#sltCertType').prop('disabled', true);
    		$('#txtAppName').prop('readonly', true);
    	}else{
    		saveType = 'new';
    		$('#sltPlatform').removeAttr('disabled');
    		$('#sltCertType').removeAttr('disabled');
    		$('#txtAppName').removeAttr('readonly');
    	}
    };
    
    var newAppVersion = function(){
    	changeSaveType('new');
    	$('#sltPlatform').val('');
    	$('#sltCertType').val('');
    	$('#txtAppName').val('');
    	$('#txtVersionOrder').val('');
    	$('#txtMarketUrl').val('');
    	$('#table_appVersion tr').removeClass('active');
    	
    	$('#versionDetail').css('display', 'block');
    	$('#versionDetailEmpty').css('display', 'none');
    	
    	$('#txtAppName').focus();
    };
    
    var removeAppVersion = function(){
    	if($('#table_appVersion tr.active').length==0){
    		alert('삭제할 버전을 선택해주세요.');
    		return;
    	};
    	if(confirm('해당 앱버전을 삭제하시곘습니까?')){
	    	var opt = {
					url: $crudServiceBaseUrl + "/removeVersion.json",
					method: "post",
					dataType: "json",
					contentType: "application/json",
					data: self.util.stringifyJson({
						platformType: $('#sltPlatform').val(),
						certType: $('#sltCertType').val(),
						appName: $('#txtAppName').val(),
						versionOrder: $('#txtVersionOrder').val(),
						marketUrl: $('#txtMarketUrl').val()
					})
			};
			
			var success = function(result){
				alert("삭제되었습니다.");
				
				if(appVersionList.length==1){
					initAppVersionList(Number($('#ulPagination li.active')[0].id.split('_')[1])-1);
    			}else{
    				initAppVersionList(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 saveAppVersion = function(){
    	var ajaxUrl = '';
    	if($('#txtAppName').val()==''){
    		alert('이름을 입력해주세요.');
    		return;
    	};
    	if($('#sltPlatform').val()==''){
    		alert('타입을 선택해주세요.');
    		return;
    	};
    	if($('#sltCertType').val()==''){
    		alert('인증서를 선택해주세요.');
    		return;
    	};
    	if($('#txtVersionOrder').val()==''){
    		alert('버전을 입력해주세요.');
    		return;
    	};
    	if($('#txtMarketUrl').val()==''){
    		alert('마켓주소를 입력해주세요.');
    		return;
    	};
    	if(saveType=='edit'){
    		ajaxUrl = $crudServiceBaseUrl + "/updateVersion.json";
    	}else{
    		ajaxUrl = $crudServiceBaseUrl + "/insertVersion.json";
    		for(var i=0; i<appVersionList.length; i++){
    			if(appVersionList[i].platformType == $('#sltPlatform').val()
    					&& appVersionList[i].certType == $('#sltCertType').val()
    					&& appVersionList[i].appName == $('#txtAppName').val()){
    				alert('타입, 인증서, 이름은 동일하게 지정할 수 없습니다.');
    				return false;
    			}
    		};
    	};
    	var opt = {
				url: ajaxUrl,
				method: "post",
				dataType: "json",
				contentType: "application/json",
				data: self.util.stringifyJson({
					platformType: $('#sltPlatform').val(),
					certType: $('#sltCertType').val(),
					appName: $('#txtAppName').val(),
					versionOrder: $('#txtVersionOrder').val(),
					marketUrl: $('#txtMarketUrl').val()
				})
		};
		
		var success = function(result){
			alert("저장되었습니다.");
			initAppVersionList(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 );
    }
};