var app = {
	loading : function(is, position) {
		$('#loading').css('display', is ? 'block' : 'none');
		is && position && ($('#loading').addClass(position));
	},
	loadingProgress: function(max, isErr, isFinish, callback) {
		var progress = $('#progress');
		if(app.processTimer && (isErr || isFinish)) {
			clearInterval(app.processTimer);
			if(isErr) {
				progress.hide()
			} else {
				progress.find('.progress').width('100%');
				progress.find('.x-waiting-wrap').text('恭喜您，注册成功');
				setTimeout(function(){
					progress.fadeOut(2000);
					callback && (callback.call(null));
				}, 2000);
			}
		} else {
			progress.show();
			var val = 0;
			app.processTimer = setInterval(function(){
				if (val++ >= max) {
					clearInterval(app.processTimer);
				} else {
					progress.find('.progress').width(Math.round(100*val/max) + '%');
				}
			}, 1000);
		}
	},
	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')
		});
	},
	applyApps: function(form, formData) {
		if (formData.users) {
			var users = [], chkObjs = {}, err = false;
			$.each(formData.users, function(){
				if(!err && this.name && (this.mobile || this.email)) {
					var ch1 = (this.mobile ? this.name + this.email : null),
						ch2 = (this.email ? this.name + this.mobile : null),
						ex1 = (this.mobile ? chkObjs[this.mobile] : null),
						ex2 = (this.email ? chkObjs[this.email] : null);
					if((ex1 && ex1 != ch1) || (ex2 && ex2 != ch2)) {
						err = true;
						app.error(this.name + ' 的信息不正确，请核对填写的手机号和邮箱地址');
					} else {
						users.push(this);
						this.mobile && (chkObjs[this.mobile] = ch1);
						this.email && (chkObjs[this.email] = ch2);					
					}
				}
			});
			if (err)
				return;
			formData.users = JSON.stringify(users);
		}
		app.loadingProgress(180);
		$.ajaxFileUpload({
			url: 'userspace/applyApp',
			secureuri: false,
			fileElementId: 'logoImage',
			data: formData,
			dataType: 'json',
			success: function (data){
				if (data && data.errMsg) {
					app.loadingProgress(null, true);
					app.error(data.errMsg, '操作失败');
				} else {
					app.loadingProgress(null, false, true, function(){
						window.location.href = 'http://www.ubtob.com';
					});
				}
			},
			error: function (){
				app.loading(false);
				app.error('出现错误');
			}
		});
	},
	checkDomain: function(el, domain) {
		$.get('sso/userspace/valid', {
			domain: domain
		}, function(data){
			if (data.errMsg) {
				app.error(data.errMsg);
				el.addClass('x-error');
			}
		});
	},
	showLocalFile: function(el, val) {
		var previewEl = $('#' + el.attr('arias-preview')), info = el.attr('arias-file-info');
		if (/^.*\.(?:png|jpe?g|bmp|gif)$/i.test(val)) {
			previewEl.show();
			var img = previewEl.find('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 (info && /^.*\.pdf$/i.test(val)) {
			$('#' + info).show().find('span').text(val);
		} else if (val) {
			el.val("");
			app.error('您上传的文件格式有误');
		}
	},
	init : function() {
		app.loading(false);
		$('.x-form').validation({
			disable: false,
			success: app.applyApps,
			error: function(form, errEl, errMsg) {
				app.error(errMsg);
			},
			listeners: {
				'domain': app.checkDomain,
				'file': app.showLocalFile
			}
		});
		$('.x-listbox li').click(function() {
			var that = $(this), box = that.parent().parent();
			box.find('.dropdown-toggle .active').text(that.text());
			box.find('input').val(that.text());
			box.find('.dropdown-menu .active').removeClass('active');
			that.addClass('active');
		});
	}
};
$(document).ready(function() {
	app.init();
});