var app = {
	loading : function(is, position) {
		app.isLoading = is;
		toastr.clear();
		$('#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.clear();
		toastr.info(message, title, {
			positionClass : 'toast-' + (position || 'top-center'),
			timeOut : 5000
		});
	},
	error : function(message, title, position) {
		toastr.clear();
		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();
		});
	},
	loadCity: function() {
		app.cityData = {province: null, city: null, district: null};
		$.getJSON('static/data/city.json', function(data){
			var wraps = $('.x-union-list ul');
			wraps.eq(0).appendTpl('<li>#{this}</li>', Object.keys(data));
			wraps.eq(0).find('li').click(function(){
				var curr = $(this), prov = curr.text(), oldActive = wraps.eq(0).find('li.active');
				if(prov != oldActive.text()) {
					oldActive.removeClass('active');
					curr.addClass('active');
					app.cityData.province = prov;
					app.cityData.city = null;
					app.cityData.district = null;
					wraps.eq(1).appendTpl('<li data-parent="' + prov + '">#{this}</li>', Object.keys(data[prov]));
					wraps.eq(2).empty();
					wraps.eq(1).find('li').click(function(){
						var curr2 = $(this), prov = curr2.data('parent'), ct = curr2.text(), oldActive2 = wraps.eq(1).find('li.active');
						if(ct != oldActive2.text()) {
							oldActive2.removeClass('active');
							curr2.addClass('active');
							app.cityData.city = ct;
							app.cityData.district = null;
							wraps.eq(2).appendTpl('<li>#{this}</li>', data[prov][ct]);
							wraps.eq(2).find('li').click(function(){
								var curr3 = $(this), dt = curr3.text(), oldActive3 = wraps.eq(2).find('li.active');
								if(dt != oldActive3.text()) {
									oldActive3.removeClass('active');
									curr3.addClass('active');
									app.cityData.district = dt;
									$('#street').focus();
								}
							});
						}
					});
				}
			});
			$('.x-union-list .x-btn-ok').click(app.onAddrChange);
		});
	},
	onAddrChange: function(e) {
		var street = $('#street').val();
		if(!app.cityData.province || !app.cityData.city || !app.cityData.district) {
			app.error('请先选择省、市、区');
			e.stopPropagation();
		} else if(!street) {
			app.error('请填写详细地址');
			e.stopPropagation();
		} else {
			$('#address').val(app.cityData.province + app.cityData.city + app.cityData.district + street);
		}
		app.checkAddress();
	},
	loadProfession: function() {
		app.professionData = {profession: null};
		$.getJSON('static/data/profession.json', function(data){
			var wraps = $('.x-profession-list ul');
			wraps.eq(0).appendTpl('<li>#{this}</li>', Object.keys(data));
			wraps.eq(0).find('li').click(function() {
				var curr = $(this), prov = curr.text(), oldActive = wraps.eq(0).find('li.active');
                wraps.eq(2).empty();
				if(prov != oldActive.text()) {
					oldActive.removeClass('active');
					curr.addClass('active');
                    if (data[prov] == '[object Object]'){
                        wraps.eq(1).appendTpl('<li data-parent="' + prov + '">#{this}</li>', Object.keys(data[prov]));
                        wraps.eq(1).find('li').click(function (e) {
                        var curr = $(this), temp = curr.text(), oldActive = wraps.eq(1).find('li.active');
                            if(temp != oldActive.text()) {
                                oldActive.removeClass('active');
                                curr.addClass('active');
                                // wraps.eq(2).style.display = 'inline';
                                wraps.eq(2).appendTpl('<li data-parent="' + prov + '" class="x-btn">#{this}</li>', data[prov][temp]);
                                wraps.eq(2).find('li').click(function (e) {
                                    var curr = $(this);
                                    $('#profession').val(curr.text());
                                })
                            }
                        })
					} else {
                        wraps.eq(1).appendTpl('<li data-parent="' + prov + '" class="x-btn">#{this}</li>', data[prov]);
                        wraps.eq(1).find('li').click(function (e) {
                            var curr = $(this);
                            $('#profession').val(curr.text());
                        })
                    }
				}
			})
		});
	},
	postFileAndData: function(formData) {
		if (app.isLoading)
			return;
		app.loading(true);
		var btn = $('.x-btn-submit');
		btn.attr('disabled', 'disabled');
		$.ajaxFileUpload({
			url: 'sso/userspace/register',
			secureuri: false,
			fileElementId: ['businessImage', 'logoImage'],
			data: formData,
			dataType: 'json',
			success: function (data){
				if(typeof data === 'string') {
					data = JSON.parse(data);
				}
				app.loading(false);
				if(data.success) {
                    btn.attr('disabled', null);
					window.location.reload();
				} else if (data.errMsg) {
					btn.attr('disabled', null);
					app.error(data.errMsg);
				} else if (data.errDetail) {
					btn.attr('disabled', null);
					app.error('填写信息有误');
					
				}
				if(data.pageToken) {
					$('input[name=pageToken]').val(data.pageToken);
				}
			},
			error: function (){
				btn.attr('disabled', null);
				app.loading(false);
				app.error('出现错误');
			}
		});
	},
	/**
	 * 禁用/启用发送验证码按钮
	 * @param el
	 * @param value
	 */
	enableCheckcode: function () {
		var telInput = $('[name=adminTel]'), emailInput = $('[name=adminEmail]'), checkcodeBtn = $('.x-btn-checkcode');
		function updateEnable() {
			var timeout = localStorage.getItem('checkcodeTimeOut');
			if(!(timeout && timeout > 0) && telInput.val() && checkPattern(telInput) && emailInput.val() && checkPattern(emailInput)) {
				checkcodeBtn.removeAttr('disabled');
			} else {
				checkcodeBtn.attr('disabled', 'disabled');
			}
		};
		telInput.bind('input propertychange', function (event) {
			updateEnable();
		});
		emailInput.bind('input propertychange', function (event) {
			updateEnable();
		});
	},
	initUserSpaceForm: function() {
        app.initData();
		$('.x-form').validation({
			// 允许没校验过的情况下点击按钮，这样可以提示错误在哪
			disable: true,
			success: function(form, data) {
				if (!data.agree) {
					app.error('您还未同意优软平台服务协议');
				} else if (!data.address) {
					app.error('请填写营业执照上的企业地址');
				} else {
					$.extend(data, app.cityData);
					app.postFileAndData(data);
				}
			},
			error: function(form, errEl, errMsg) {
				app.error(errMsg);
			},
			listeners: {
				'name': app.checkName,
				'businessCode': app.checkBusCode,
				'businessImage': app.showLocalFile,
				'logoFile': app.showLocalFile,
				// 'contactMan': app.checkContantMan
				// 'checkcode': app.checkCheckcode
			}
		});
		// app.enableCheckcode();// 监听获取验证码的按钮状态
		// $('.x-btn-checkcode').click(app.getCheckcode);
		// app.checkcodeTimeout();
		$(".x-btn-cancel").click(app.checkAddress);
		$('#addTag').click(app.addTag);
	},
    initData: function () {
        $.post('sso/session/data', {
			key: 'userspace'
		},function (data) {
			if (data.success && data.content) {
				app.userspace = data.content;
				var temp = data.content;
				$("input[name='name']").val(temp.name);
				$("input[name='businessCode']").val(temp.businessCode);
				$("input[name='businessCodeImage']").val(temp.businessCodeImage);
                $('#businessImagePreview div a img').attr('src', temp.businessCodeImage);
                $('#businessImagePreview').show();
                $("input[name='corporation']").val(temp.corporation);
				$("input[name='address']").val(temp.address);
				$("input[name='contactMan']").val(temp.contactMan);
				$("input[name='contactTel']").val(temp.contactTel);
				$("input[name='contactEmail']").val(temp.contactEmail);
				$("input[name='fax']").val(temp.fax);
				$("input[name='url']").val(temp.url);
				$("input[name='profession']").val(temp.profession);
				// $("input[name='logoFile']").val(temp.logoFile);
				$("input[name='logoImage']").val(temp.logoImage);
				$('#logoImageView div img').attr('src', temp.logoImage);
				$('#logoImageView').show();
                if (null != temp.tags && "" != temp.tags) {
                     app.tags = temp.tags.split(',');
                     app.datatags = temp.tags.split(',');
					    app.showTags();
                }
                var submitBtn = $('.x-btn-submit');
                submitBtn.removeClass('disabled');
			}
        })
	},
	getIpAddr: function() {
		// 按客户端IP查找地理位置
		$.get('api/util/ipAddr', function(){
			
		});
	},
	checkName: function(el, name) {
		$.get('sso/userspace/valid', {
			name: name
		}, function(data){
			if (data.errMsg) {
				// app.error(data.errMsg);
				el.addClass('x-error');
				toggleError(el, false, data.errMsg);
			}
		});
	},
	checkBusCode: function(el, busCode) {
		$.get('sso/userspace/valid', {
			businessCode: busCode
		}, function(data){
			if (data.errMsg) {
				// app.error(data.errMsg);
				el.addClass('x-error');
				toggleError(el, false, data.errMsg);
			}
		});
	},
	/**
	 * 验证验证码是否正确
	 * @param el
	 * @param val
	 */
	checkCheckcode: function (el, code) {
		var token = el.data('token');
        var tel = $("input[name='adminTel']").val();
        var email = $("input[name='adminEmail']").val();
		if(token) {
			$.post('sso/userspace/checkcode', {
				token: token,
				code: code,
                tel: tel,
                email: email
			}, function (res) {
				if (res.success) {
					// app.info('验证码正确');
					app.onCheckSuccess();
				} else {
					// app.error(res.errMsg);
					el.addClass('x-error');
					toggleError(el, false, res.errMsg);
				}
			});
		} else {
			app.error('请先获取验证码');
			el.addClass('x-error');
		}
	},
	checkAddress: function () {
		var el = $("input[name = 'address']");
		var address = el.val();
		if (address) {
			$('#address_help').show();
			$('#address_err').hide();
			el.removeClass('x-error');
		} else {
			$('#address_help').hide();
			$('#address_err').show();
			el.addClass('x-error');
		}
	},
	checkContantMan: function () {
		var contactMan = $("input[name='contactMan']").val();$('#contactMan_error').hide();
		contactMan && (contactMan.length < 2 || contactMan.length > 20) && ($('#contactMan_error').show(),$("input[name='contactMan']").addClass('x-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) {
		var previewEl = $('#' + el.attr('arias-preview')), info = el.attr('arias-file-info');
		var files = el.context.files;
		// var pageStep = $('input[name=pageStep]').val();
		if(el.context.id == 'businessImage') {
			if(files.length > 0) {
				if(files[0].size/1024/1024 > 5) {
					el.addClass('x-error');
					toggleError(el, false, '营业执照大小不能超过5M');
				}
			}
		}else if (el.context.id == 'logoImage') {
			if(files.length > 0) {
				if(files[0].size/1024/1024 > 0.1) {
					el.addClass('x-error');
					toggleError(el, false, 'logo大小不能超过100K');
				}
			}
		}
		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
		            }
		        }
			}
			$('#' + info).hide();
		} else if (info && /^.*\.pdf$/i.test(val)) {
			previewEl.hide();
			$('#' + info).show().find('span').text(val);
		} else if (val) {
			el.val("");
			app.error('您上传的文件格式有误');
		}
	},
	addTag: function () {
		if (app.tags == null){
			app.tags = new Array();
			app.datatags = new Array();
		}
		var tag = $("#tag").val();
		if (tag.indexOf(',') != -1){
			app.error("标签不允许有逗号！");
			$("#tag").val("");
			return;
		}
		if (tag.trim() && jQuery.inArray(tag.trim(), app.datatags) == -1) {
			app.tags.push(tag);
			app.datatags.push(tag);
			$('#tags').val(app.datatags);
			var item = app.tags[app.tags.length-1];
			// $('.form-horizontal .form-group #sss').append("<div id='"+ app.tags.length + "'><span></span><i class='glyphicon glyphicon-remove' aria-hidden='true' style='top: -10.5px; color: red; left: 19.5px;'></i></div>");
			// $('.form-horizontal .form-group #sss #'+app.tags.length + ' >span').html(item);
			// $('.glyphicon-remove').off("click"); // 动态添加绑定事件时需要先解除绑定的点击事件
			// $('.glyphicon-remove').click(function(){
			// 	app.datatags.splice(jQuery.inArray($(this).parent().attr('id'), app.datatags), 1);
			// 	$(this).parent().remove();
			// 	if (!app.datatags.length > 0){
			// 		$('.no-tags').show();
			// 	}
			// })
            app.showTags();
		}
		$("#tag").val("");
		if (app.datatags.length > 0){
			$('.no-tags').hide();
		}
	},
    showTags: function () {
        $('.form-horizontal .form-group #sss').children().remove();
		if (app.datatags.length > 0){
			$('.no-tags').hide();
		} else {
			$('.no-tags').show();
		}
        for (var i=0; i<app.datatags.length; i++) {
            var tag = app.datatags[i];
            $('.form-horizontal .form-group #sss').append("<div id='"+ i + "'><span></span><i class='glyphicon glyphicon-remove' aria-hidden='true' style='top: -10.5px; color: red; left: 19.5px;'></i></div>");
            $('.form-horizontal .form-group #sss #'+ i + ' >span').html(tag);
            $('.glyphicon-remove').off("click"); // 动态添加绑定事件时需要先解除绑定的点击事件
            $('.glyphicon-remove').click(function(){
                app.datatags.splice(jQuery.inArray($(this).parent().attr('id'), app.datatags), 1);
                $(this).parent().remove();
                if (!app.datatags.length > 0){
                    $('.no-tags').show();
                }
            })
        }
    },

	initAdminForm: function() {
		var form = $('.x-form');
		form.validation({
			disable: false,
			success: function (form, data) {
				app.setAdmin(data);
			},
			error: function(form, errEl, errMsg) {
//				if(errMsg != null) {
//					app.error(errMsg, '密码错误');
//				} else {
//					app.error('企业已注册，请刷新页面');
//				}
                app.error(errMsg);
			},
			listeners: {
				'checkcode':  app.checkCheckcode
			}
			
		});
		// $('#checkcode').bind('input propertychange', function() {
		//    var submitBtn = $('.x-btn-submit');
		//    if($('#checkcode').val().length != 6) {
		// 	   submitBtn.attr('disabled', 'disabled');
		//    } else {
		// 	   app.checkCheckcode($(this), $('#checkcode').val());
		//    }
		// });
		$('input[name=adminTel]').blur(app.checkAdminTel);
		app.enableCheckcode();// 监听获取验证码的按钮状态
		$('.x-btn-checkcode').click(app.getCheckcode);
		app.checkcodeTimeout();
	},

	checkAdminTel: function () {
		var mobile = $('input[name=adminTel]').val();
		$.get('api/user/detail', {
			mobile: mobile
		}, function (data) {
			if (data.content != null) {
				$('#password_help').show();
				$('#password_error').hide();
				$('#password_err').hide();
			}
		})
	},

    setAdmin: function (formData) {
		var token = $("input[name='checkcode']").data('token');
		$.extend(formData, {token: token});
		if (app.isLoading)
            return;
        app.loading(true);
        $.ajax("sso/userspace/setAdmin", {
            data: formData,
            method: 'POST',
            success: function (data) {
                if (data.success) {
                    app.login(formData, data.content.enuu);
					window.location.reload();
                } else {
                    app.error(data.errMsg);
					if (data.errMsg == '用户名或密码错误！') {
						$('#password_help').hide();
						$('#password_error').show();
                        $('#password').addClass('x-error');
					}
                }
                app.loading(false);
            },
            error: function (data) {
                app.error(data.errMsg);
                app.loading(false);
            }
        });
    },
	login: function (formData, enuu) {
		$.ajax("sso/login/auto",{
			data: {
				appId: 'b2b',
				enuu: enuu,
				tel: formData.adminTel,
				password: formData.password,
			},
			method: 'POST',
			success: function (data) {
				console.log("Ok");
			}
		})
	},
	lastStep: function () {
		var pageStep = $('input[name=pageStep]').val();
		$.ajax("sso/lastStep",{
			data: {
				pageStep: pageStep,
			},
			method: 'GET',
			success: function (data) {
				if (data.success) {
					window.location.reload();
				}

			}
		})
	},
	initApps: function() {
		$.ajaxFileUpload({
			url: 'sso/register/applyApp',
			secureuri: false,
			dataType: 'json',
			timeout : 5000, //超时时间设置，单位毫秒
			success: function (data) {
			},
			error: function (data) {
				error(data, "注册失败");
			}
		})
	},
	checkDomain: function(el, domain) {
		$.get('sso/userspace/valid', {
			domain: domain
		}, function(data){
			if (data.errMsg) {
				app.error(data.errMsg);
				el.addClass('x-error');
			}
		});
	},
	applyApps: function(form, formData) {
		// if(formData.password != formData.passwordConfirm){
		// 	app.error('密码不一致');
		// } else {
			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);
			}
			var applySaas = (formData.applyApps && formData.applyApps.indexOf('saas') > -1);
			if (!applySaas) {
				formData.domain = null;
			}
			app.loadingProgress(applySaas ? 180 : 5);
			$.ajaxFileUpload({
				url: 'sso/register/applyApp',
				secureuri: false,
				fileElementId: 'logoImage',
				data: formData,
				dataType: 'json',
				success: function (data){
					var returnUrl = null;
					if(data.cotent) {
						returnUrl = data.content.returnUrl;
					}
					if(typeof data === 'string') {
						data = JSON.parse(data);
					}
					if (data && data.errMsg) {
						app.loadingProgress(null, true);
						app.error(data.errMsg, '操作失败');
					} else {
						app.loadingProgress(null, false, true, function(){
							if(returnUrl != null) {
								window.location.href = returnUrl;
							} else {
								window.location.href = 'http://www.ubtob.com';
							}
						});
					}
				},
				error: function (){
					app.loadingProgress(null, true);
					app.error('出现错误');
				}
			});
		// }
	},
	/**
	 * 获取验证码
	 * @param e
	 */
	getCheckcode: function (e) {
		var me = $(this);
		app.loading(true);
		$.get('sso/userspace/checkcode', {
			tel: $('[name=adminTel]').val(),
			email: $('[name=adminEmail]').val(),
			pageToken: $('[name=pageToken]').val()
		}, function (res) {
			app.loading(false);
			if(res && res.success) {
				me.attr('disabled', 'disabled');
				$('[name=checkcode]').show();
				$('[name=checkcode]').data('token', res.content.token);
				$('[name=checkcodeToken]').val(res.content.token);
				app.checkcodeTimeout(60);
				app.info('验证码已经发送到您的手机和邮箱');
			}
		});
	},
	/**
	 * 获取验证码倒计时
	 * @param time
	 */
	checkcodeTimeout: function (time) {
		var localStorageKey = 'checkcodeTimeOut';
		time = time || localStorage.getItem(localStorageKey);
		if(time > 0) {
			$('.x-timeout-word').show().siblings().hide();
			var interval = app.checkcodeInterval = setInterval(function () {
				$('.x-timeout-num').text(time);
				time --;
				localStorage.setItem(localStorageKey, time);
				if (time < 0) {
					app.removeCheckcodeInterval(interval);
				}
			}, 1000);
		}
	},
	removeCheckcodeInterval: function(interval) {
		localStorage.removeItem('checkcodeTimeOut');
		$('.x-timeout-word').hide().siblings().show();
		clearInterval(interval);
		var telInput = $('[name=adminTel]'), emailInput = $('[name=adminEmail]'), checkcodeBtn = $('.x-btn-checkcode');
		if(telInput.val() && checkPattern(telInput) && emailInput.val() && checkPattern(emailInput)) {
			checkcodeBtn.removeAttr('disabled');
		}
	},
	onCheckSuccess: function() {
		var interval = app.checkcodeInterval;
		if (interval) {
			// clear interval
			app.removeCheckcodeInterval(interval);
		}
		// 验证码没问题，且未修改手机号情况下，不应该继续点击“获取验证码”
//		$('.x-btn-checkcode').attr('disabled', 'disabled');
	},
	init : function() {
		new Router({
			'#/valid': function() {
				app.initApps();
				// 滚动到密码框
//				$('input[name=password]').scrollTo();
			}
		}, function(){
			var pageStep = $('input[name=pageStep]').val();
			$('.x-btn-image').click(app.showImageBox);
			$('.x-btn-lastStep').click(app.lastStep);
			app.loadCity();
			app.loadProfession();
			// disable close
			$(document).on('click.bs.dropdown.data-api', '.dropdown-menu', function (e) {
				if(!$(e.target).is('.x-btn'))
					e.stopPropagation();
			});
			if(pageStep == 1) {
				app.initUserSpaceForm();
			} else if(pageStep == 2) {
				app.initAdminForm();
			} else if(pageStep == 3) {
				app.initApps();
			}
		}).start();
		app.loading(false);
	}
};
$(document).ready(function() {
	app.init();
});

var goHref = function (url) {
	window.location.href = url;
}