var app = {
	loading : function(is, position) {
		$('#loading').css('display', is ? 'block' : 'none');
		is && position && ($('#loading').addClass(position));
	},
	info : function(message, title, position) {
		toastr.info(message, title, {
			positionClass : 'toast-' + (position || 'top-center'),
			timeOut : 1000
		});
	},
	error : function(message, title, position) {
		toastr.error(message, title, {
			positionClass : 'toast-' + (position || 'top-center')
		});
	},
	//============CRUD about setting===============
	editSetting : function(event, key) {
		key = event ? $(event.target).data("id") : key;
		if (key) {
			$.getJSON('api/setting', {key: key}, function(data){
				app.showSettingModal(data.content);
			});
		} else {
			// new
			app.showSettingModal({
			});
		}
	},
	showSettingModal: function(content) {
		$('#settingModal').showModal(function(){
			var scope = $(this);
			scope.renderData(content);
			scope.find('.btn-submit').click(scope.find('form'), app.saveSetting);
			if(content.key) {
				scope.find('input[name=key]').attr('readonly', 'readonly');
				if (!content.deleteable) {
					scope.find('#allowDeleteWrap').hide();
					scope.find('.btn-del').hide();
				} else {
					scope.find('.btn-del').click(content, app.deleteSetting);
					scope.find('.btn-del').show();
				}
			} else {
				scope.find('.btn-del').hide();
			}
		});
	},
	saveSetting : function(event) {
		var form = event.data, content = form.serializeObject();
		app.loading(true, 'right-center');
		$.post('api/setting', content, function(data){
			app.loading(false);
			if (data && data.errMsg) {
				app.error(data.errMsg, '保存失败', 'top-right');
			} else {
				window.location.reload();
			}
		}, 'json');
	},
	deleteSetting: function(event){
		var key = event.data.key;
		if(key) {
			app.loading(true);
			$.del('api/setting', {key: key}, function(data) {
				app.loading(false);
				if (data && data.errMsg) {
					app.error(data.errMsg, '删除失败', 'top-right');
				} else {
					window.location.reload();
				}
			});
		}
	},
	init : function() {
		$('.x-chunk-list-wrap .x-editor-trigger').click(app.editSetting);
		app.loading(false);
	}
};
$(document).ready(function() {
	app.init();
});