// mui.init({
// 	beforeback: function() { //获得父页面的webview
// 		var list = plus.webview.currentWebview().opener(); //触发父页面的自定义事件(refresh),从而进行刷新
// 		mui.fire(list, 'refresh');
// 		//返回true,继续页面关闭逻辑
// 		return true;
// 	}
// });

mui.plusReady(function() {
	
	var wait = 120;

	// 判断用户名是否存在 
	$('#loginName').on('blur', function() {
		var loginName = $('#loginName').val();
		JZL.ajax('http://t.ect99.com/app/users/check_login_name', {
			loginName: loginName
		}, function(data) {
			// console.log(data);
			if (1 != data.status) {
				mui.alert(data.msg)
			}
		})
	})

	function GetQueryString(name) {
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
		console.log(reg);
		var r = window.location.search.substr(1).match(reg);
		if (r != null)
			return unescape(r[2]);
		return null;
	}

	var pName = GetQueryString('pName') ? GetQueryString('pName') : localStorage.getItem('pName');

// 	if (!pName) {
// 		pName = localStorage.getItem('pName');
// 		var indexNum = pName.indexOf('&');
// 		if (indexNum > 0) {
// 			pName = pName.slice(0, indexNum);
// 		}
// 	}
// 
	if (pName) {
		console.log(pName);
// 		$('#pName').val(pname);;
// 		$('#pName').attr('disabled', 'disabled');
	}
	// 推荐人信息
	//var PName = "";
	$('#pName').on('blur', function() {
		pName = $('#pName').val();
		if ('' != pName) {
			if (!(
					/^134[0-8]\d{7}$|^13[^4]\d{8}$|^14[5-9]\d{8}$|^15[^4]\d{8}$|^16[6]\d{8}$|^17[0-8]\d{8}$|^18[\d]{9}$|^19[8,9]\d{8}$/
					.test(pName))) {
				mui.alert("手机号码有误,请重填!");
				return;
			}
			$('.pNameCode').show();

			mui('.row').on('tap', '#mobileCode1', function() {
				$(this).attr("disabled", true);
				JZL.ajax('http://t.ect99.com/app/users/getPhoneVerifyCode', {
					userPhone: pName
				}, function(data) {
					if (1 == data.status) {
						time()
					} else {
						mui.alert(data.msg);
					}
					$('#mobileCode1').removeAttr('disabled');

				})
			})



		} else {
			$('.pNameCode').hide();
		}

	})
	// JZL.ajax(qlgUrl('app/users/check_login_name'),{loginName:loginName},function (data) {
	// 	// console.log(data);
	// 
	// 	if (1 != data.status) {
	// 		mui.alert(data.msg)
	// 	}
	// })
	function time() {
		if (wait == 0) {
			$('#mobileCode').removeAttr("disabled");
			$('#mobileCode').val("重新发送");
			wait = 120;
		} else {
			$('#mobileCode').attr("disabled", true);
			$('#mobileCode').val("重新发送(" + wait + ")");
			wait--;
			setTimeout(function() {
					time()
				},
				1000)
		}
	}
	//获取验证码
	mui('.row').on('tap', '#mobileCode', function() {
		var loginName = $('#loginName').val();
		if (loginName == '') {
			mui.alert('手机号不能为空!');
			return;
		}
		// 		if (!(
		// 				/^134[0-8]\d{7}$|^13[^4]\d{8}$|^14[5-9]\d{8}$|^15[^4]\d{8}$|^16[6]\d{8}$|^17[0-8]\d{8}$|^18[\d]{9}$|^19[8,9]\d{8}$/
		// 				.test(loginName))) {
		// 			mui.alert("手机号码有误,请重填!");
		// 			return;
		// 		}
		$(this).attr("disabled", true);
		mui.ajax('http://t.ect99.com/app/users/getPhoneVerifyCode', {

			data: {
				userPhone: loginName
			},
			dataType: 'json', //服务器返回json格式数据
			type: 'post', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒
			success: function(data) {
				console.log(data);
				//服务器返回响应,根据响应结果,分析是否登录成功;
				if (data.status == 1) {
					time();
				} else {
					mui.alert(data.msg);
				}
				$('#mobileCode').removeAttr('disabled');
			},

			error: function(xhr, type, errorThrown) {
				//异常处理;
				mui.alert(type)
				//						mui.alert(type);      
			}
		});
	})
	//注册协议
	mui.ajax('http://t.ect99.com/app/Tags/articleDetail', {
		data: {
			articleId: 114
		},
		dataType: 'json', //服务器返回json格式数据
		type: 'post', //HTTP请求类型
		timeout: 10000, //超时时间设置为10秒;
		success: function(data) {
			console.log(data);
			// if(data.status==1){
			// console.log(1);
			var html1 = ''
			html1 = '<h3>' + data.articleContent + '</h3>'
			$('.zcxycontent').append(html1)
			// }
		},
		error: function(xhr, type, errorThrown) {

		}
	});
	//上传图片

	var files = []; //存储文件信息的数组
	var fname = ""; //表示文件名,例如  XXXX.jpg;
	var expire = 0;
	var pathName = '';
	var inpId = '';
	var keyname = '';
	var imgId = '';
	var isZip = 1;
	var qualityNum = 90;
	var response = ';'
	var UP = UP || {};
	UP.isBatch = 0;
	UP.init = function(inputId, path, imageId, isBatch, isZipImg, quality) {
		inpId = inputId;
		pathName = path;
		imgId = imageId;
		if (typeof(isBatch) != 'undefined') {
			UP.isBatch = isBatch;
		}
		if (typeof(isZipImg) != 'undefined') {
			// console.log(typeof(isZipImg));
			isZip = isZipImg;
		}
		if (typeof(quality) != 'undefined') {
			qualityNum = quality;
		}

	}

	function send_request() {
		var xmlhttp = null;
		if (window.XMLHttpRequest) {
			xmlhttp = new XMLHttpRequest();
		} else if (window.ActiveXObject) {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}

		if (xmlhttp != null) {
			//		console.log(dir)
			serverUrl = 'http://t.ect99.com/oss/get.php?dir=' + pathName;
			// serverUrl = 'https://img.zgqlg.com.cn/oss/get.php?dir=' + pathName;

			xmlhttp.open("GET", serverUrl, false);
			xmlhttp.send(null);
			return xmlhttp.responseText;
		} else {
			mui.alert("Your browser does not support XMLHTTP.");
		}

	}

	function get_signature() {
		//可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
		now = timestamp = Date.parse(new Date()) / 1000;
		if (expire < now + 3) {
			body = send_request()
			var obj = eval("(" + body + ")");
			response = obj;
			// console.log(obj);
		}
		return response;
	};
	// 上传文件
	function upload(callback) {
		// console.log(files);
		if (files.length <= 0) {
			mui.toast('没有添加上传文件');
			return;
		}
		var obj = get_signature();
		if (obj) {
			server = obj['host'];
			policyBase64 = obj['policy'];
			accessid = obj['accessid'];
			signature = obj['signature'];
			expire = parseInt(obj['expire']);
			callbackbody = obj['callback'];
			path = obj['dir'];

		} else {
			mui.toast('初始化失败');
			return;
		}

		var wt = plus.nativeUI.showWaiting();
		var task = plus.uploader.createUpload(server, {
			method: "POST"
		}, function(t, status) {
			//上传完成
			if (status == 200) {
				wt.close();
				if (1 == UP.isBatch) {
					callback(t, status, keyname, server + '/' + keyname);
				} else {
					document.getElementById(inpId).value = keyname;
					var ele = document.getElementById(imgId);
					ele.src = server + '/' + keyname;
					ele.setAttribute('data-src', keyname);
					mui.toast('上传成功');
					//至此上传成功,上传后的图片完整地址为server+testName
					//keyname
				}

			} else {
				wt.close();
				mui.toast('上传失败:' + status);
			}
		});
		var suffix1 = get_suffix(fname); //文件后缀  例如   .jpg
		keyname = path + new Date().getTime() + suffix1;
		task.addData("key", keyname);
		task.addData("policy", policyBase64);
		task.addData("OSSAccessKeyId", accessid);
		task.addData("success_action_status", "200");
		// task.addData("callback", callbackbody);
		task.addData("signature", signature);
		var f = files[files.length - 1];
		// console.log(f)

		task.addFile(f.path, {
			key: "file",
			name: "file",
			mime: "image/jpeg"
		});
		//files.length = 0;
		task.start();

	}

	//得到文件名的后缀
	function get_suffix(filename) {
		var pos = filename.lastIndexOf('.');
		var suffix = '';
		if (pos != -1) {
			suffix = filename.substring(pos)
		}
		return suffix;
	}
	// 拍照添加文件
	function appendByCamera(callback) {
		plus.camera.getCamera().captureImage(function(p) {
			uploadImg(p, callback);
		});
	}
	// 从相册添加文件
	function appendByGallery(callback) {
		plus.gallery.pick(function(p) {
			uploadImg(p, callback);
		});
	}

	// 添加文件
	var index = 1;

	function uploadImg(p, callback) {
		if (1 == isZip) {
			compressImg(p, callback);
		} else {
			appendFile(p, callback)
		}
	}

	function appendFile(p, callback) {
		// var fe = document.getElementById(fileId);
		var n = p.substr(p.lastIndexOf('/') + 1);
		// fname = n/////////;
		files.push({
			name: "uploadkey" + index,
			path: p
		});
		//console.log(3);
		// index++;
		upload(callback);
	}

	function compressImg(src, callback) {
		var filename = src.substring(src.lastIndexOf('/') + 1);
		var opions = {
			src: src,
			dst: '_doc/tmp/' + filename,
			overwrite: true,
			//width: '300px', //这里指定了宽度,同样可以修改
			format: 'jpg',
			quality: qualityNum //图片质量不再修改,以免失真
		};
		var successCB = function(evt) {
			// console.log(JSON.stringify(evt));
			fname = filename;
			// 		files[0]={
			// 			name: "uploadkey",
			// 			path: evt.target
			// 		};
			files.push({
				name: "uploadkey" + index,
				path: evt.target
			});
			// index++;
			//上传		
			upload(callback);
			//_this.avatar(evt.target);
		};
		var errorCB = function(err) {
			appendFile(src, callback);
			
			//console.log(JSON.stringify(err));
			//mui.toast("图片压缩失败");i m  
		};
		plus.zip.compressImage(opions, successCB, errorCB);
	};

	function openCamera(callback) {
		plus.nativeUI.actionSheet({
			cancel: "取消",
			buttons: [{
					title: "拍照"
				},
				{
					title: "从相册中选择"
				}
			]
		}, function(e) { //1 是拍照  2 从相册中选择
			switch (e.index) {
				case 1:
					appendByCamera(callback);
					break;
				case 2:
					appendByGallery(callback);
					break;
			}
		});
	}
	$(".photos").on("tap", '.regConfirm', function() {
		// UP.init("accountBookImg", "test", "accountBookImgTag")

		UP.init("regConfirmImg", "test", "regConfirmImg")
		openCamera()
	})


	mui('.down').on('tap', '.btn', function() {
		var loginName = $('#loginName').val();
		var mobileCode = $('.yzm').val();
		var loginPwd = $('#loginPwd').val();
		var reUserPwd = $('#reUserPwd').val();
		var mobileCode1 = $('#mobileCode1').val() ? $('#mobileCode1').val() : ""; //推荐人验证码


		pName = $('#pName').val();

		// var verifyCode = $('.tpyzm').val();
		var regConfirmImg = $('#regConfirmImg').val();
		if (loginName == '') {
			mui.alert('手机号不能为空!');
			return;
		}
		if (!(
				/^134[0-8]\d{7}$|^13[^4]\d{8}$|^14[5-9]\d{8}$|^15[^4]\d{8}$|^16[6]\d{8}$|^17[0-8]\d{8}$|^18[\d]{9}$|^19[8,9]\d{8}$/
				.test(loginName))) {
			mui.alert("手机号码有误,请重填!");
			return;
		}
		if (mobileCode == '') {
			mui.alert('验证码不能为空!');
			return;
		}
		if (loginPwd == '') {
			mui.alert('密码不能为空!');
			return;
		}
		if (reUserPwd == '') {
			mui.alert('确认密码不能为空!');
			return;
		}
		if (loginPwd.length < 6) {
			mui.alert('密码不能小于6位!');
			return;
		}
		if (!(loginPwd == reUserPwd)) {
			mui.alert('两次密码不一致!');
			return;
		}
		if (regConfirmImg == '') {
			mui.alert('请上传确认书照片');
			return;
		}
		if (pName != '') {
			if ('' == mobileCode1) {
				mui.alert('请输入推荐人验证码');
				return;
			}
		}
		$(this).attr("disabled", true);
		mui.ajax('http://t.ect99.com/app/users/register', {
			data: {
				loginName: loginName,
				mobileCode: mobileCode,
				loginPwd: loginPwd,
				reUserPwd: reUserPwd,
				pName: pName,
				nameType: 3,
				regConfirmImg: regConfirmImg,
				mobileCode1: mobileCode1
				// verifyCode: verifyCode
			},
			dataType: 'json', //服务器返回json格式数据
			type: 'post', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒
			success: function(data) {
				//服务器返回响应,根据响应结果,分析是否登录成功;
				mui.alert(data.msg);

				if (data.status == 1) {
					// mui.back();
					plus.runtime.open
				} else {
					// $('.yzmhh').attr('src', hyhUrl('mobile/users/getverify?rnd=' + Math.random()));
				}
				$('.btn').removeAttr('disabled');
			},

			error: function(xhr, type, errorThrown) {
				//异常处理;
				//						mui.alert(type);      
			}
		});

	})

})