var app = {
	loading: function(is) {
		$('#loading').css('display', is ? 'block': 'none');
	},
	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 assets===============
	editAsset : function(event, assetId) {
		assetId = event ? $(event.target).data("id") : assetId;
		if (assetId) {
			$.getJSON('api/asset/' + assetId, function(data){
				app.showAssetModal(data.content);
			});
		} else {
			app.showAssetModal({
			});
		}
	},
	showAssetModal: function(content) {
		$('#assetModal').showModal(function(){
			var scope = $(this);
			scope.renderData(content);
			scope.find('.btn-submit').click(scope.find('form[name=assetForm]'), app.saveAsset);
			if(content.id) {
				scope.find('.btn-del').click(content, app.deleteAsset);
				scope.find('.btn-del').show();
			} else {
				scope.find('.btn-del').hide();
			}
			scope.find('[name=file]').change(scope, app.uploadFile);
			// load apps
			app.getApps(function(apps){
				var box = scope.find('#apps-box'), curr_id = content.appId;
				if(curr_id) {
					for(var i in apps) {
						if(apps[i].uid == curr_id) {
							box.find('.active').text(apps[i].description);
							break;
						}
					}
				}
				box.find('ul').appendTpl('<li><a href="javascript:void(0);" title="#{uid}" data-id="#{uid}">#{description}</a></li>', apps);
				box.find('a').click(function() {
					var that = $(this);
					box.find('.active').text(that.text());
					scope.find('input[name=appId]').val(that.data('id'));
				});
			});
		});
	},
	saveAsset : function(event) {
		var form = event.data, content = form.serializeObject();
		// 检验json格式+去掉\n\t等字符
		var json = [];
		if(content.btns) {
			if(content.btns.indexOf('{') != 0) {
				var params = content.btns.split(/\n+|\t+|,|;/);
				$.each(params, function(i, param){
					var kv = param.split('=');
					json.push({'text': kv[0].trim(), 'link': kv[1].trim()});
				});
			} else {
				json = $.parseJSON(content.btns);
			}
		}
		content.btns = json.length > 0 ? JSON.stringify(json) : null;
		app.loading(true);
		$.post('api/asset', content, function(data){
			app.loading(false);
			if (data && data.errMsg) {
				app.error(data.errMsg, '保存失败', 'top-right');
			} else {
				window.location.reload();
			}
		}, 'json');
	},
	deleteAsset: function(event){
		var assetId = event.data.id;
		if(assetId) {
			app.loading(true);
			$.del('api/asset/' + assetId, function(data) {
				app.loading(false);
				if (data && data.errMsg) {
					app.error(data.errMsg, '删除失败', 'top-right');
				} else {
					window.location.reload();
				}
			});
		}
	},
	//============list view===============
	showAssetList: function(params) {
		$('.pagination').pagination({
			url: 'api/asset/list',
			params: params,
			renderData: function(content){
				app.loading(false);
				if(content.length == 0) {
					$('.x-img-list-wrap .x-empty').show();
				} else {
					var list = $('.x-img-list');
					list.appendTpl('<div class="x-item"><div class="x-img"><img src="#{url}"></div><p><a class="x-title" href="javascript:void(0);" data-id="#{id}">#{url}</a><span class="pull-right x-text-muted">#{appId}</span></p></div>', content);
					list.find('a').click(app.editAsset);
				}
			}
		});
	},
	searchAsset: function(event) {
		var target = $(event.target), form = $('.x-nav-tabs form'), data = form.serializeObject();
		if (!target.is('a')) {
			target = $('.x-nav-tabs .active a');
		}
		data.pageNumber = 1;
		app.showAssetList(data);
		$('.x-nav-tabs .active').removeClass('active');
		target.parent().addClass('active');
	},
	getApps: function(callback) {
		$.getJSON('api/app/list', function(data){
			callback.call(null, data.content);
		});
	},
	uploadFile: function(e) {
		var scope = e.data;
		$.ajaxFileUpload({
			url: 'api/util/upload',
			secureuri: false,
			fileElementId: 'assetModal_backgroundImage',
			dataType: 'json',
			success: function (data, status){
				if (data.errMsg) {
					app.error(data.errMsg);
				} else if(data.content) {
					scope.find('[name=url]').val(data.content);
				}
			},
			error: function (data, status, e){
				app.error('出现错误');
			}
		});
	},
	//============document ready===============
	init : function() {
		$('.x-content .x-editor-trigger').click(app.editAsset);
		app.showAssetList();
	}
};
$(document).ready(function() {
	app.init();
});