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 : 5000
		});
	},
	error : function(message, title, position) {
		toastr.error(message, title, {
			positionClass : 'toast-' + (position || 'top-center')
		});
	},
	showImageBox: function() {
		var src = $(this).data('src') || $(this).find('img').attr('src'), box = $('#image-box');
		box.show();
		box.find('img').attr('src', src);
		box.find('a').click(function(){
			box.hide();
		});
		box.dblclick(function(){
			box.hide();
		});
	},
	postFileAndData: function(formData) {
		console.log(formData);
		app.loading(true);
		$.ajaxFileUpload({
			url: 'changeAdmin/userspace/changeAdmin',
			secureuri: false,
			fileElementId: 'businessImage',
			data: formData,
			dataType: 'json',
			contentType: "application/json",
			success: function (data){
				app.loading(false);
				if(data && (typeof data === 'string')) {
					data = jQuery.parseJSON(data);
				}
				if(data.success) {
					window.location.reload();
				} else if (data.errMsg) {
					app.error(data.errMsg);
				} else if (data.errDetail) {
					console.log(data.errDetail);
				}
			},
			error: function (){
				app.loading(false);
				app.error('出现错误');
			}
		});
	},
	getObjectURL: function (file) {
        var url = null;
        if (window.createObjectURL != undefined) {
            url = window.createObjectURL(file)
        } else if (window.URL != undefined) {
            url = window.URL.createObjectURL(file)
        } else if (window.webkitURL != undefined) {
            url = window.webkitURL.createObjectURL(file)
        }
        return url
    },
	showLocalFile: function(el, val) {
		if (/^.*\.(?:png|jpe?g|bmp|gif)$/i.test(val)) {
			$('#businessImagePreview').show();
			var img = $('#businessImagePreview img');
			var files = el.context.files;
			if (files && files[0] && window.FileReader) {
				var fr = new FileReader();
                fr.onloadend = function(e) {
                	img.attr('src', e.target.result);
                };
                fr.readAsDataURL(files[0]);
			} else {
				if (window.navigator.userAgent.indexOf("MSIE") >= 1) {
		            try {
		            	img.attr('src', app.getObjectURL(files[0]))
		            } catch (e) {
		                el.context.select();
		                if (top != self) {
		                    window.parent.document.body.focus();
		                } else {
		                	el.blur();
		                }
		                var src = document.selection.createRange().text, div = img.parent()[0];
		                document.selection.empty();
		                img.hide();
		                img.parent().css({
		                    'filter': 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)',
		                    'width': '150px',
		                    'height': '150px'
		                });
		                div.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = src
		            }
		        }
			}
		} else if (/^.*\.pdf$/i.test(val)) {
			$('#businessImageTip').show().find('span').text(val);
		} else {
			el.val("");
			app.error('您上传的文件格式有误');
		}
	},
	initForm: function() {
		$('.x-form').validation({
			// 允许没校验过的情况下点击按钮，这样可以提示错误在哪
			disable: false,
			success: function(form, data) {
				app.postFileAndData(data);
			},
			error: function(form, errEl, errMsg) {
				app.error(errMsg);
			},
			listeners: {
				'file': app.showLocalFile
			}
		});
	},
	init : function() {
		new Router({

		}, function(){
			$('.x-btn-image').click(app.showImageBox);
			app.initForm();
		}).start();
		app.loading(false);
	}
};
$(document).ready(function() {
	app.init();
});