$(function () {
	function searchToObject() {
		var pairs = window.location.search.substring(1).split("&"),
			obj = {},
			pair,
			i;
		for ( i in pairs ) {
			if ( pairs[i] === "" ) continue;
			pair = pairs[i].split("=");
			obj[ decodeURIComponent( pair[0] ) ] = decodeURIComponent( pair[1] );
		}
		return obj;
	}
	var C = CanvasKit;
	var searchObject=searchToObject();
	var needGeneral=0;
	var appKey=searchObject.appKey;
	if(appKey=="87AAFCB871204540805E682FE08B652A"||appKey=="14C1858768944FDF93789B7A9DE0A2AD"){
        $("#nago").attr("href","https://t.51gjj.com/shebao/protocol")
    }
if(appKey=="3D6884E1400246CA9B8A4AF836DFB856"){
        $("#nago").attr("href","https://t.51gjj.com/shebao/protocol/njyhprotocol.html")
    }
	var userId=searchObject.userId||"";
	if(searchObject.hasOwnProperty("ID")&&searchObject.hasOwnProperty("name")&&searchObject.hasOwnProperty("phone")){
		needGeneral=1;
	}

	if (appKey === '4A93A53011C94291A6471EF0F744AC7E' || appKey === '58DFD97822914956A13623CD88F7B0D5'){
        $(".footer").addClass('display');
    }

    if (appKey == "751EB4B795134480800CAF76594ACB43" || appKey == "9B996FA4717D4D498B3E3463487623A8" || appKey == "EA8530A32D974F298B074ED7C42436CC" || appKey == "21DC4D1D87964763A97A5C0520E95B1C" || appKey == "AB9FA0941B3047678146F944039CF1BB" || appKey == "30F7FEE6B1C942A1A36C1D1F7D5A3CEC" || appKey == '9CF686A7AA5F4B2D8C9D4FBC577A1B52'|| appKey == '32242346263A4507AA2AA3FA63FFC4D0'|| appKey == '3891A0729ADD469EB1ABD2F10414928A'|| appKey == '3C3F9B6E408048E7B3BCF7EDE2D13388'|| appKey == 'E452F6C66CC443B8A48A2DFD8D3EF793'|| appKey == '7C2B3B9AFB7141AEAA48A1C68ABE64CE'){
        $(".footer").addClass("exit")
    }

  if(appKey=="2AA60979E996470BAB00133A878ECFBB"||appKey=="FAAC07AC633944BCA50AEB5C12D49243"){
        $(".btn.btn-default").css("border-radius","0.833333rem")
        $("#nago").attr("href","https://t.51gjj.com/gjj/gsprotocol")
  }
	function rewiteUrl(cid) {
		var url=window.location.href;
		if(url.match(/&cid=\d+/)){
			url=url.replace(/&cid=\d+/,"&cid="+cid);
		}else{
			url+="&cid="+cid;
		}
		history.replaceState("","",url);
	}
	function TimingAnimate(opt) {
		C.Animate.call(this, opt);
		this.shifting = 0;
		this.fn = opt.fn;
		this.initial_velocity = +(opt.velocity || opt.v || 0);
		this.max_velocity = +(opt.max_velocity || opt.max_v || 0);
		this.acceleration = +(opt.acceleration || opt.a || 0);
		this.velocity = this.initial_velocity;
	}

	C.extendClass(TimingAnimate, C.Animate, {
		_start: function () {
			this.shifting = 0;
			this.velocity = this.initial_velocity;
		},
		_update: function (interval, elapsedTime) {
			var t = elapsedTime / 1000, //总时间
				a = this.acceleration, //加速度
				t0 = (this.max_velocity - this.initial_velocity) / a,//达到最大速度时间点
				t1 = t < t0 ? t : t0,//匀加速时间
				t2 = t > t0 ? t - t0 : 0, //匀速时间
				v0 = this.initial_velocity, //初速度
				mv = this.max_velocity; //最大速度

			this.shifting = v0 * t1 + .5 * a * t1 * t1 + mv * t2;
			this.velocity = v0 + a * t1;
			for (var key in this.fn) {
				if ((key === "position" || key === "alpha" || key === "color") && typeof this.fn[key] === "function") {
					this.node[key] = this.fn[key].call(this, this.shifting);
				}
			}
		}
	});

	function Ball(radial_radius, radius, position, color) {
		C.Circle.call(this, radius, position, color);
		this.turning_velocity = 4;
		this.shadow.alpha = 1;
		this.status = "none";
		this.center = this.position;
		this.radial_radius = radial_radius;
		this.tube = radius * 2;
		this.radius = radius * 1.4;

		var scale = .85;

		this.points = {
			a: [this.center[0] - this.radial_radius * .40 * scale, this.center[1] - this.radial_radius * .10 * scale],
			b: [this.center[0] - this.radial_radius * .12 * scale, this.center[1] + this.radial_radius * .30 * scale],
			c: [this.center[0] + this.radial_radius * .57 * scale, this.center[1] - this.radial_radius * .31 * scale]
		};

		this.turning_angle = (function (points, o, r) {
			//ax + by + c = 0;
			var a = points.b[1] - points.a[1],
				b = points.a[0] - points.b[0],
				c = points.b[0] * points.a[1] - points.a[0] * points.b[1],
				d = Math.abs((a * o[0] + b * o[1] + c) / Math.sqrt(a * a + b * b));
			return Math.PI * 2 - Math.acos(d / r) - Math.atan(-a / b);
		})(this.points, this.center, this.radial_radius);
	}

	C.extendClass(Ball, C.Circle, {
		_draw: function (ctx) {
			switch (this.status) {
			case "none":
				this._draw_none(ctx);
				break;
			case "timer":
			case "timer+":
				this._draw_run_timer(ctx);
				break;
			case "-loader":
				this._draw_will_loader(ctx);
				break;
			case "loader":
				this._draw_run_loader(ctx);
				break;
			case "loaded":
				this._draw_will_do(ctx);
				break;
			case "doing":
				this._draw_run_doing(ctx);
				break;
			case "done":
				this._draw_run_done(ctx);
				break;
			default:

			}
		},
		_get_stretch_rate: function () {
			return Math.max(0, (this.animate.velocity - this.turning_velocity) / (this.animate.max_velocity - this.turning_velocity));
		},
		_get_I: function () {
			return Math.max(0, Math.PI * 2 * .05 * this._get_stretch_rate());
		},
		_get_point_angle: function (angle) {
			return this.animate.fn.position.call(this.animate, angle);
		},
		_play: function () {
			var fn = function (s) {
				return [this.node.center[0] + this.node.radial_radius * Math.sin(s),
					this.node.center[1] + this.node.radial_radius * Math.cos(s)];
			};
			this.animate = new TimingAnimate({
				node: this,
				v: 2,
				max_v: 10,
				a: .1,
				fn: {
					position: fn
				}
			});
			this.position = fn.bind(this.animate)(0);
			this.animate.play();
			this.status = "loader";
		},
		_draw_none: function (ctx) {

		},
		_draw_run_timer: function (ctx) {
			var elapsedTime = this.timer.elapsedTime,
				finishedTime = Math.round(this.time) * 1000,
				startAngle = -Math.PI / 2,
				angle = Math.PI * 2;
			if (finishedTime > elapsedTime) {
				var elapsedSec = Math.floor(elapsedTime / 1000) * 1000,
					elapsedMs = elapsedTime - elapsedSec,
					beatMs = 800;
				angle *= elapsedSec / finishedTime;
				if (elapsedMs > 1000 - beatMs) {
					angle += Math.PI * 2000 * C.Easing.Quadratic.InOut(C.mix(0, 1, (elapsedMs - (1000 - beatMs)) / beatMs)) / finishedTime;
				}
			} else {
				this.timer.stop();
				this.status = "timer+";
			}

			ctx.save();
			ctx.lineWidth = this.tube;
			ctx.strokeStyle = C.convertColor(this.color, this.alpha);
			ctx.beginPath();
			ctx.arc(this.center[0], this.center[1], this.radial_radius, startAngle, startAngle + angle, false);
			ctx.stroke();
			ctx.restore();
		},
		_draw_will_loader: function (ctx) {
			var elapsedTime = this.timer.elapsedTime,
				finishedTime = 400,
				startAngle = -Math.PI / 2,
				endAngle = startAngle + Math.PI * 2;
			if (finishedTime > elapsedTime) {
				var a = C.Easing.Quadratic.InOut(finishedTime > elapsedTime ? elapsedTime / finishedTime : 1);
				var b = Math.PI * a;
				startAngle += b;
				endAngle -= b;

				if (endAngle <= startAngle) {
					endAngle = startAngle;
				}

				ctx.save();
				ctx.lineCap = "round";
				ctx.lineWidth = C.mix(this.tube, this.radius * 2, a);
				ctx.strokeStyle = C.convertColor(this.color, this.alpha);
				ctx.beginPath();
				ctx.arc(this.center[0], this.center[1], this.radial_radius, startAngle, endAngle, false);
				ctx.stroke();
				ctx.restore();
			} else {
				this._play();
			}
		},
		_draw_run_loader: function (ctx) {
			var v = this.animate.velocity,
				stretch_rate = this._get_stretch_rate(),
				s = this.animate.shifting || 0;
			if (v > this.turning_velocity) {
				this.shadow.enabled = true;
				this.shadow.blur = Math.round(6 * stretch_rate);
				this.alpha = .4 + .6 * (1 - stretch_rate);
			} else {
				this.shadow.enabled = false;
				this.shadow.blur = 0;
				this.alpha = 1;
			}

			// C.Circle.prototype._draw.call(this,ctx);
			ctx.save();
			if (v <= this.turning_velocity) {
				ctx.fillStyle = C.convertColor(this.color, this.alpha);

				ctx.beginPath();
				ctx.arc(this.position[0], this.position[1], this.radius, 0, Math.PI * 2, true);
				ctx.closePath();
				ctx.fill();
			} else {
				var points = [],
					dI = this.radius / this.radial_radius / 3,
					I = this._get_I();
				this._draw_ring(ctx, s, this._get_I(), 0);

			}
			ctx.restore();
		},
		_draw_ring: function (ctx, start_angle, I, is_gradient) {
			var points = [],
				dI = this.radius / this.radial_radius / 3;

			for (var i = 0; i * dI <= I; i++) {
				points.push(this._get_point_angle(start_angle - i * dI));
			}
			is_gradient = !!is_gradient;

			var alpha = is_gradient ? 1 : this.alpha;

			ctx.strokeStyle = C.convertColor(this.color, alpha);
			ctx.fillStyle = ctx.strokeStyle;
			ctx.shadowOffsetX = this.shadow.offset.x;
			ctx.shadowOffsetY = this.shadow.offset.y;
			ctx.shadowBlur = this.shadow.blur;
			ctx.shadowColor = C.convertColor(this.color, 1); // 颜色

			var circle_start_angle = -start_angle + Math.PI * .5;
			ctx.beginPath();
			ctx.arc(points[0][0], points[0][1], this.radius, circle_start_angle, circle_start_angle + Math.PI, true);
			ctx.closePath();
			ctx.fill();

			var length = points.length, point = points.shift(), i = 0;

			if (points.length) {
				ctx.beginPath();
				ctx.moveTo(point[0], point[1]);
				while (points.length) {
					if (is_gradient) {
						alpha = C.mix(1, this.alpha, C.Easing.Cubic.Out(i / length));
						ctx.strokeStyle = C.convertColor(this.color, alpha);
						ctx.fillStyle = ctx.strokeStyle;
					}

					ctx.lineWidth = this.radius * 2;
					point = points.shift();
					ctx.lineTo(point[0], point[1]);
					ctx.closePath();
					ctx.stroke();
					ctx.beginPath();
					ctx.moveTo(point[0], point[1]);
					i++;
				}
			}


			ctx.beginPath();
			circle_start_angle = -(start_angle - (length - 1) * dI) - Math.PI * .5;
			ctx.arc(point[0], point[1], this.radius, circle_start_angle, circle_start_angle + Math.PI, true);
			ctx.closePath();
			ctx.fill();
		},
		_draw_will_do: function (ctx) {
			this._draw_run_loader(ctx);
			if ((this.animate.shifting || 0) >= this.turning_angle) {
				this.status = "doing";
				this.end_timer.start();
			}
		},
		_draw_run_done: function (ctx) {
			var points = [];
			points.push(this.points.a);
			points.push(this.points.b);
			points.push(this.points.c);
			for (var i = 0; i < points.length - 1; i++) {
				this._draw_lines(ctx, points[i], points[i + 1]);
			}
		},
		_draw_run_doing: function (ctx) {
			var elapsedTime = this.end_timer.elapsedTime;
			var points = [];
			if (elapsedTime > this.duration) {
				this.status = "done";
				this._draw_run_done(ctx);
				typeof this._fn == "function" && this._fn();
				delete this._fn;
				return;
			} else {
				var f = C.Easing.Back.Out(Math.min(elapsedTime / this.duration, 1));

				if (f < this.a_rate) {
					if (f < this.b_rate) {
						var I = this._get_I() - this.animate.velocity * elapsedTime / 1000;
						if (I > 0) {
							ctx.save();
							this._draw_ring(ctx, this.turning_angle, I, 1);
							ctx.restore();
						}
						points.push(this.turning_point);
					} else {
						points.push(C.mix(this.turning_point, this.points.a, (f - this.b_rate) / (1 - this.b_rate)));
					}
					points.push(C.mix(this.turning_point, this.points.b, f / this.a_rate));
				} else {
					points.push(C.mix(this.turning_point, this.points.a, (f - this.b_rate) / (1 - this.b_rate)));
					points.push(this.points.b);
					points.push(C.mix(this.points.b, this.points.c, (f - this.a_rate) / (1 - this.a_rate)));
				}
			}
			for (var i = 0; i < points.length - 1; i++) {
				this._draw_lines(ctx, points[i], points[i + 1]);
			}
		},
		_draw_lines: function (ctx, a, b) {
			ctx.save();
			ctx.beginPath();
			ctx.lineWidth = this.radius * 2;
			ctx.lineCap = "round";
			ctx.strokeStyle = C.convertColor(this.color, 1);
			ctx.moveTo(a[0], a[1]);
			ctx.lineTo(b[0], b[1]);
			ctx.stroke();
			ctx.restore();
		},
		_draw_circle: function (ctx, point) {
			ctx.save();
			ctx.fillStyle = C.convertColor(this.color, this.alpha);
			ctx.beginPath();
			ctx.arc(point[0], point[1], this.radius, 0, Math.PI * 2, true);
			ctx.closePath();
			ctx.fill();
			ctx.restore();
		},
		play: function () {
			if (this.timer) {
				this.timer.stop();
			}
			if (this.animate) {
				this.animate.pause();
			}
			if (this.status == "timer+" || this.status == "timer") {
				this.status = "-loader";
				this.timer = (new C.Timer()).start();
			} else {
				this._play();
			}
		},
		timing: function (time, fn) {
			if (this.timer) {
				this.timer.stop();
			}
			if (this.animate) {
				this.animate.pause();
			}
			this.status = "timer";
			this.alpha = 1;
			this.time = time;
			$(".canvas-dashboard .loader .sec").html(time);
			this.timer = (new C.Timer()).start().repeat(1000, function () {
				var second = time - Math.round(this.elapsedTime / 1000);
				fn(second);
			});

		},
		end: function (fn) {
			this.status == "loader" && (this.status = "loaded") && (function () {
				this.turning_angle = Math.ceil(((this.animate.shifting || 0) - this.turning_angle) / (Math.PI * 2)) * Math.PI * 2 + this.turning_angle;
				this.turning_point = this._get_point_angle(this.turning_angle);
				this.a_rate = 1 / (1 + C.distance(this.points.c, this.points.b) / C.distance(this.turning_point, this.points.b));
				this.b_rate = 1 / (1 + C.distance(this.turning_point, this.points.a) / (this._get_I() * this.radial_radius));
				this.end_timer = new C.Timer();
				this.duration = Math.round((C.distance(this.turning_point, this.points.b) + C.distance(this.points.b, this.points.c)) * (1.70158 + 3) * 1000 / (this.radial_radius * this.animate.velocity));
				this._fn = fn;
			}.bind(this))();
		}
	});


	function CanvasLoader() {
		this.loader = $(".canvas-dashboard");
		this.dashboard = $(".user-fields-dashboard");
		this._init = function () {
			var stage = new C.Stage(),
				width = stage.getWidth(),
				height = stage.getHeight(),
				radius = Math.min(width, height) / 2 * .9,
				tube = 3 * radius / 40,
				cirque = new C.Cirque(radius, tube, [width / 2, height / 2], Math.PI * 2);

			this.circle = new Ball(cirque.radius, tube * .5, cirque.position),
			this.renderer = new C.Renderer(stage);


			cirque.color = 0xf6f6f6;
			this.circle.shadow.enabled = true;
			this.circle.shadow.blur = 12;
			this.circle.color = 0x439df8;
			stage.add(cirque).add(this.circle);

			this.renderer.on("update", function (event, interval, elapsedTime) {
			});
		};

		this.init = function () {
			if (!this.renderer) {
				if (!$("canvas").is(":visible")) {
					this.dashboard.addClass("loader");
					this._init();
					this.dashboard.removeClass("loader");
				}
			}
		};

		this.play = function () {
			this.init();
			this.dashboard.addClass("loader");
			this.loader.removeClass("pause");
			this.renderer.run();
			if (this.circle.status == "loader") {
				return;
			}
			this.circle.play();
		};

		this.pause = function () {
			if (this.circle && this.circle.status == "loader") {
				this.circle.status = "none";
			}
			this.loader.addClass("pause");
		};

		this.setTag = function (tag) {
			if (this.circle && this.circle.status == "timer" || this.circle.status == "timer+") {
				return;
			}
			this.loader.find(".label").html(function () {
				switch (tag) {
				case "query":
					return "任务提交成功";
				case "logined":
					return "登录完成，等待授权";
				case "data":
					return "正在查询中...";
				case "refresh":
					return "正在刷新任务";
				case "success":
					return "认证完成";
				}
				return "";
			});
			this.loader.find(".loader>*").not("canvas").detach();
			if (this.text_timeout_timer) {
				clearTimeout(this.text_timeout_timer);
				delete this.text_timeout_timer;
			}
			if (this.text_interval_timer) {
				clearTimeout(this.text_interval_timer);
				delete this.text_interval_timer;
			}
			if (tag == "query") {
				this.loader.find(".loader").append($("<div>", {"class": "content"})
					.append($("<div>", {"class": "message"}).html("任务已经提交成功")));
				this.text_timeout_timer = setTimeout(function () {
					if (this.circle.status == "loader") {
						this.loader.find(".loader .message").html("当前查询较慢，可能还需要几秒");
					}
					delete this.text_timeout_timer;
				}.bind(this), 30 * 1000);
			} else if (tag == "data"||tag == "refresh") {
				var texts = ["认证时间较长，请耐心等待", "您可能需要等待几分钟"], i = 0;
				this.loader.find(".loader").append($("<div>", {"class": "content"})
					.append($("<div>", {"class": "message"}).html(texts[0])));
				this.text_interval_timer = setInterval(function () {
					if (this.circle.status == "loader") {
						this.loader.find(".loader .message").html(texts[(++i) % texts.length]);
					}
					delete this.text_interval_timer;
				}.bind(this), 10 * 1000);
			}
		};

		this.setText = function (text) {
			this.loader.find(".label").html(text);
		};

		this.timing = function (duration, fn) {
			this.init();
			this.dashboard.addClass("loader");
			this.loader.removeClass("pause");
			var self = this;
			this.renderer.run();
			this.loader.find(".loader >*").not("canvas").detach();
			this.loader.find(".loader").append($("<div>", {"class": "content"})
				.append($("<div>", {"class": "message"}).html("您可能需等待"))
				.append($("<div>", {"class": "sec"})));
			this.circle.timing(duration, function (second) {
				if (second == 0) {
					fn && fn.call(self);
				} else {
					if (second == 1) {
						setTimeout(function () {
							self.loader.find(".content").addClass("in");
						}, 800);
					}
					self.loader.find(".sec").html(second);
				}
			});
		};
		this.end = function (fn) {
			this.circle.end(function () {
				this.renderer.pause();
				fn && fn();
			}.bind(this));
			this.loader.find(".content").addClass("in");
		};
		this.stop = function () {
			this.renderer.pause();
			this.circle.status = "none";
			this.dashboard.removeClass("loader");
		};
	}

	function CSSLoader() {
		this.dashboard = $(".user-fields-dashboard");
		this.init=function () {
			this.dashboard.addClass("loader");
			$(".canvas-dashboard").hide();
			$(".css-loader-dash").show();
			$(".css-shadow").show();

		};
		this.play=function(){
			this.init();
		};
		this.pause=function(){
			this.dashboard.removeClass("loader");
			$(".css-loader-dash").hide();
			$(".css-shadow").hide();
		};
		this.setTag=function(){

		};
		this.setText=function(){

		};
		this.end=function (fn) {
			$("#load").html("认证完成，即将为您跳转");
			fn && fn();
		};
		this.stop=function(){
			this.dashboard.removeClass("loader");
			$(".css-loader-dash").hide();
			$(".css-shadow").hide();
		};
		this.timing=function(duration,fn){
			var self = this;
			fn && fn.call(self);
		};
	}

	var taskId = $("#form").attr("data-taskId")||"";
	var nextStepFlag = 0;
	var queryStatus="init";
	var orderSn=$("#form").attr("data-ordersn");
	var redirectUrl=$("#form").attr("data-redirectUrl");
	var orderStatus=$("#form").attr("data-status");
	function listen_ws_job(params, success, failed) {
		var url;
		if (window.location.protocol == "http:"){
			url= "ws://" + window.location.host + window.location.pathname + "ws?taskId=" + taskId+"&orderSn="+orderSn+"&cityName="+encodeURIComponent($(".gjj-center-pannel h1 label").text())+"&needGeneral="+needGeneral;
		}else{
			url= "wss://" + window.location.host + window.location.pathname + "ws?taskId=" + taskId+"&orderSn="+orderSn+"&cityName="+encodeURIComponent($(".gjj-center-pannel h1 label").text())+"&needGeneral="+needGeneral;
		}

		var ws = new WebSocket(url);
		var timer=setTimeout(function () {
			failed({msg:"任务超时"});
		},1000*60*10);
        ws.onerror=function (err) {
            failed("webSocketErr");
        }

		ws.onmessage = function (msg) {
			if (msg.data == "ok") {
				if(needGeneral){
					var generalParams={
						ID:searchObject.ID,
						name:searchObject.name,
						phone:searchObject.phone,
						taskId:taskId
					};
					ws.send(JSON.stringify(generalParams));
				}
			} else {
				clearTimeout(timer);
				msg = JSON.parse(msg.data);
				if (msg.errcode == 0) {
					if(msg.data.code!=1){
						ws.close();
					}
					success(msg.data);
				} else {
					ws.close();
					failed(msg.data);
				}
			}
		};


	}

	function listen_loop_job(params, success, failed) {
		params={taskId:taskId,orderSn:orderSn,cityName:$(".gjj-center-pannel h1 label").text()};
		return (new Scheduler({timeout: 10 * 60 * 1000})).begin(function () {
			var self = this;
			$.ajax({
				type: "POST",
				url: window.location.pathname + "ws/getJob",
				data: params,
				success: function (data) {
					var msg = JSON.parse(data);
					if (msg.errcode == 0) {
						if (msg.data.code == 2) {
							self.update();
						} else {
							self.end(msg);
						}
					} else {
						self.end(msg);
					}
				},
				error: function (xhr, type) {
					self.update();
				}
			});
		}, function (msg) {
			if (msg.errcode == 0) {
				success(msg.data);
			} else {
				failed(msg.data);
			}
		}, function (error) {
			var data = {msg: "任务超时"};
			failed(data);
		}
		);
	}

	function gjjJobV2() {
		var self = this, loader = new CanvasLoader();
		var userAgent = navigator.userAgent;
		var index = userAgent.indexOf("Android");
		if(index >= 0){
			var androidVersion = parseFloat(userAgent.slice(index+8));
			if(androidVersion<4.4){
				loader = new CSSLoader();
			}
		}
		window.loader = loader;
		this.loader = loader;
		this.expiration_time = 0;
	}

	gjjJobV2.prototype = {
		commitJob: function (params) {
			var self = this;
			loader.play();
			loader.setTag("data");
			params = {params: JSON.stringify(params),cid: $("#form").attr("data-cid"),orderSn:orderSn,appKey:appKey,userId:userId,taskId:taskId};
			var url = window.location.pathname + "ajax/commitParams";
			$.ajax({
				type: "POST",
				url: url,
				data: params,
				success: function (data) {
					if(data.code!=0){
						$.prompt(data.msg);
						self.failed();
						return;
					}
					taskId = data.data.taskId;
					if (!!window.WebSocket && window.WebSocket.prototype.send) {
                            listen_ws_job({}, function (data) {
                                if (data.code == 1) {
                                    switch (data.type) {
                                        case "text":
                                            nextStepFlag = 1;
                                            self.getNextInput(data);
                                            break;
                                        case "110":
                                            loader.setTag("query");
                                            break;
                                    }
                                } else {
                                    self.success();
                                }
                            }, function (data) {
                                if(data=='webSocketErr'){
                                    listen_loop_job({}, function (data) {
                                        if (data.code == 1) {
                                            switch (data.type) {
                                                case "text":
                                                    nextStepFlag = 1;
                                                    self.getNextInput(data);
                                                    break;
                                                case "110":
                                                    loader.setTag("query");
                                                    break;
                                            }
                                        } else {
                                            self.success();
                                        }
                                    }, function (data) {
                                        $.prompt(data.msg);
                                        self.failed();
                                    });
                                }else{
                                    $.prompt(data.msg);
                                    self.failed();
                                }

                            });}else{
						listen_loop_job({}, function (data) {
							if (data.code == 1) {
								switch (data.type) {
								case "text":
									nextStepFlag = 1;
									self.getNextInput(data);
									break;
								case "110":
									loader.setTag("query");
									break;
								}
							} else {
								self.success();
							}
						}, function (data) {
							$.prompt(data.msg);
							self.failed();
						});
					}
				},
				error: function (xhr, type) {
					if (xhr == 500) {
						$.prompt("程序员哥哥写错代码了！");
					} else if (xhr == 404) {
						$.prompt("接口文件不见了！");
					} else if (xhr == 0) {
						$.prompt("请确认设备已连接到网络！");
					} else {
						$.prompt("服务器好像挂了！");
					}

				}
			});
		},
		success: function () {
			loader.end(function () {
			    if(redirectUrl.length>11&&redirectUrl.substr(0,11)=="javascript:"){
                    $.ajax({
                        type: "POST",
                        url: window.location.pathname + "ajax/redirect",
                        data: {callback:redirectUrl},
                        success: function (data) {
                            window.location.href=redirectUrl;
                        },
                        error: function (xhr, type) {
                            window.location.href=redirectUrl;
                        }
                    });
                }else{
                    var redirectParams=(redirectUrl.indexOf("?")>-1?"&":"?")+"status=success&orderSn="+orderSn+"&timestamp="+new Date().getTime();
                    $.ajax({
                        type: "POST",
                        url: window.location.pathname + "ajax/redirect",
                        data: {callback:redirectUrl+redirectParams},
                        success: function (data) {
                            window.location.href=redirectUrl+redirectParams;
                        },
                        error: function (xhr, type) {
                            window.location.href=redirectUrl+redirectParams;
                        }
                    });
                }
			});
		},
		failed: function () {
			loader.stop();
			$("#tab-content  input[name=\"code\"]").val("");
			$("#tab-content  input[name=\"phoneCode\"]").val("");
			$("#submit").submitFields(".active .input-option,.checkbox .input-option");
			if (nextStepFlag) {
				var url = window.location.pathname + "/getCity";
				var params = {cid: $("#form").attr("data-cid")};
				doAjax("GET", url, params);
			} else {
				$(document).trigger("setup_task");
			}
		},
		getNextInput: function (data) {
			loader.stop();
			$("#form").html(data.html);
			$("#submit").attr("disabled", "disabled");
			$(".phoneCodeBtn").lock($(".phoneCodeBtn").data("cd"));
			$(".phoneCodeBtn").off("click").on("click",function (event) {
				var self=$(this);
				self.lock(self.data("cd"));
				var params = {taskId: taskId, type: "phone_code"};
				$.ajax({
					type: "POST",
					url: window.location.pathname + "ajax/getCode",
					data: params,
					success: function (data) {
						if(data.code=="0"){
							$.prompt("验证码发送成功，请注意查收");
						}else{
							$.prompt("验证码发送失败，请一分钟后再试");
						}
						// self.unlock()
					},
					error: function (xhr, type) {
						if (xhr == 500) {
							$.prompt("程序员哥哥写错代码了！");
						} else if (xhr == 404) {
							$.prompt("接口文件不见了！");
						} else if (xhr == 0) {
							$.prompt("请确认设备已连接到网络！");
						} else {
							$.prompt("服务器好像挂了！");
						}
					}
				});
			});
			if (checkImgCode()) {
				getCode("code");
			}
			$(".captcha-wrapper").off("click").on("click", function () {
				getCode("code");
			});
			$("#tab-content .active input").off("input change").on("input change", function () {
				checkParams() ? $("#submit").removeAttr("disabled") : $("#submit").attr("disabled", "disabled");
			});

		},
		refreshJob:function (params) {
			var self = this;
			loader.play();
			loader.setTag("refresh");
			queryStatus="query";
			var url = window.location.pathname + "ajax/refresh";
			$.ajax({
				type: "POST",
				url: url,
				data: params,
				success: function (data) {
					if(data.code!=0){
						$.prompt(data.msg);
						self.refreshEnd("failed","refresh");
						return;
					}
					taskId = data.data.taskId;
					if (!!window.WebSocket && window.WebSocket.prototype.send) {
						listen_ws_job({}, function (data) {
							if (data.code == 1) {
								if(data.type=="110"){
									loader.setTag("query");
								}else{
									$.prompt("任务刷新失败");
									self.refreshEnd("failed","refresh");
								}
							} else {
								self.refreshEnd("success","refresh");
							}
						}, function (data) {
							$.prompt(data.msg);
							self.refreshEnd("failed","refresh");
						});}else{
						listen_loop_job({}, function (data) {
							if (data.code == 1) {
								self.refreshEnd("failed","refresh");
							} else {
								self.refreshEnd("success","refresh");
							}
						}, function (data) {
							$.prompt(data.msg);
							self.refreshEnd("failed","refresh");
						});
					}
				},
				error: function (xhr, type) {
					if (xhr == 500) {
						$.prompt("程序员哥哥写错代码了！");
					} else if (xhr == 404) {
						$.prompt("接口文件不见了！");
					} else if (xhr == 0) {
						$.prompt("请确认设备已连接到网络！");
					} else {
						$.prompt("服务器好像挂了！");
					}

				}
			});
		},
		refreshEnd:function(status,type,msg){
			if(status==="failed"){
				loader.setText("任务刷新失败，即将为你跳转");
			}
			if(status==="success"){
				loader.setText("任务刷新成功，即将为你跳转");
			}
			var redirectParams=(redirectUrl.indexOf("?")>-1?"&":"?")+"status="+status+"&orderSn="+orderSn+"&timestamp="+new Date().getTime();
			if(type=="refresh"){
				redirectParams+="&type=refresh";
			}
			loader.end(function () {
				$.ajax({
					type: "POST",
					url: window.location.pathname + "ajax/redirect",
					data: {callback:redirectUrl+redirectParams},
					success: function (data) {
						window.location.href=redirectUrl+redirectParams;
					},
					error: function (xhr, type) {
						window.location.href=redirectUrl+redirectParams;
					}
				});

			});
		}
	};


	$(document).on("setup_task", function () {
		nextStepFlag = 0;
		queryStatus="init";
		var url = window.location.pathname + "ajax/createTask";
		var params = {cid: $("#form").attr("data-cid"),orderSn:orderSn,appKey:appKey,userId:userId};
		$.ajax({
			type: "POST",
			url: url,
			data: params,
			success: function (data) {
				taskId = data.data.taskId;
				if (checkImgCode()) {
					loader.pause();
					if(orderStatus==="refresh"){
						new Dialog({
							title:"验证码",
							html:"<div class=\"content\"><div class=\"refresh-code loading\"><img src=\"\"></div><label>看不清？点击图片更换验证码</label><div class=\"input\"><input name=\"code\" placeholder=\"请输入图示验证码\"  data-label=\"验证码\" id=\"inputRefresh\"></div></div>\n",
							buttons:[{
								title:"立即刷新",
								className:"btnRefresh",
								tap:function () {
									if($("#inputRefresh").val()==""){
										$.prompt("请输入验证码");
										return true;
									}else{
										var params={
											code:$("#inputRefresh").val(),
											taskId:taskId,
											hasCode:true,
											orderSn:orderSn
										};
										query.refreshJob(params);
									}
								}
							}]
						}).model({alert:true});
						getCode("code","refresh");
						$(".refresh-code").off("click").on("click", function () {
							if($(".refresh-code").hasClass("loading")){
								return;
							}
							$(".refresh-code").removeClass("failed").addClass("loading");
							getCode("code","refresh");
						});
					}else {
						getCode("code","normal");
						$(".captcha-wrapper").off("click").on("click", function () {
							if($(".captcha-wrapper").hasClass("loading")){
								return;
							}
							$(".captcha-wrapper").removeClass("failed").addClass("loading");
							getCode("code","normal");
						});
					}
				}

			},
			error: function (xhr, type) {
				if (xhr == 500) {
					$.prompt("程序员哥哥写错代码了！");
				} else if (xhr == 404) {
					$.prompt("接口文件不见了！");
				} else if (xhr == 0) {
					$.prompt("请确认设备已连接到网络！");
				} else {
					$.prompt("服务器好像挂了！");
				}
			}
		});
	}).on("mutation", function (event) {
		var query = new gjjJobV2();
		window.query = query;
		switch (orderStatus){
		case "query":
			loader.play();
			loader.setTag("query");
			if (!!window.WebSocket && window.WebSocket.prototype.send) {
				listen_ws_job({}, function (data) {
					query.success();
				}, function (data) {
					$.prompt(data.msg);
					query.failed();
				});}else{
				listen_loop_job({}, function (data) {
					query.success();
				}, function (data) {
					$.prompt(data.msg);
					query.failed();
				});
			}
			break;
		case "success":
			queryStatus="query";
			loader.play();
			loader.setTag("data");
			query.success();
			break;
		case "refresh":
			queryStatus="query";
			if (checkImgCode()){
				loader.play();
				loader.setTag("refresh");
				if($("#tab-content").length>0){
					$(document).trigger("setup_task");
				}
			}else{
				var params={
					hasCode:false,
					orderSn:orderSn,
					cid:$("#form").attr("data-cid")
				};
				query.refreshJob(params);
			}
			break;
		default:
			if($("#tab-content").length>0){
				$(document).trigger("setup_task");
			}
			break;
		}

		var $ul = $("#tab-content ul");
		$(".tab-control .tab-nav label").off("click").on("click", function () {
			var self = $(this);
			if (self.hasClass("active") || self.closest(".tab-nav").hasClass("disabled")) {
				return;
			}
			var index = self.index();
			var o = self.closest(".tab-nav").find(".active").removeClass("active");
			self.addClass("active");
			$ul.css("display", "none").removeClass("active");
			$ul.eq(index).css("display", "block").addClass("active");
			$("#submit").submitFields(".active .input-option,.checkbox .input-option");
		});
		$(".gjj-center-pannel").off("click").on("click", function (event) {
			if(queryStatus=="query"){
				return;
			}
			if ($(" #switcher-tpl").length > 0) {
				$("#main-tpl").addClass("out");
				$(".gjj-list-pannel").show();
				$(".gjj-filter-list-pannel").hide();
				$("#switcher-tpl").addClass("out");

				searchEvent();
			} else {
				$("section.gjj-center-pannel h1").addClass("loading");
				$.ajax({
					type: "GET",
					url: window.location.pathname + "cityList",
					success: function (data) {
						$("section.gjj-center-pannel h1").removeClass("loading");
						$("body .container").append(data);
						$("#switcher-tpl").addClass("out");
						$("#main-tpl").addClass("out");
						searchEvent();

					},
					error: function (xhr, type) {
						if (xhr == 500) {
							$.prompt("程序员哥哥写错代码了！");
						} else if (xhr == 404) {
							$.prompt("接口文件不见了！");
						} else if (xhr == 0) {
							$.prompt("请确认设备已连接到网络！");
						} else {
							$.prompt("服务器好像挂了！");
						}
					}
				});
			}


		});

		$("#submit").submitFields(".active .input-option,.checkbox .input-option").off("click").on("click", function () {
			if ($("#main-tpl").hasClass("loading")) {
				$("#main-tpl").removeClass("loading");
				$(document).trigger("mutation");
			} else {
				var params = $(".active input,.active select").valMap();
				if(checkLoginParams(params)){
					queryStatus="query";
					query.commitJob(params);
				}
			}
		});
		$(".header-notice").off("click").on("click", function () {
			$("#main-tpl").addClass("out");
			$(".helpPage").addClass("out");
		});
		$("#back").off("click").on("click", function () {
			$(".helpPage").removeClass("out");
			$("#main-tpl").removeClass("out");
		});


	}).trigger("mutation");
	function checkLoginParams(params){
		for(var item in params){
			if (item==="ID") {
				if(!/^\d{14}(\d{3})?[\dXx]$/.test(params[item])){
					$.prompt("身份证格式不对");
					return false;
				}
			}
			if (item==="phone") {
				if(!/^1\d{10}$/.test(params[item])){
					$.prompt("手机格式不正确");
					return false;
				}
			}
			if (item==="Email"||item==="email") {
				if (!/^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/.test(params[item])) {
					$.prompt("邮箱格式不正确");
					return false;
				}
			}
		}
		return true;

	}
	function searchEvent() {
		$(".search-bar input").val("");
		$(".gjj-list-pannel .open").removeClass("open");
		$(".gjj-list-pannel h5 ").off("click").on("click", function () {
			var self = $(this);
			if (self.hasClass("open")) {
				self.removeClass("open");
			} else {
				self.addClass("open");
			}
		});
		$(".gjj-list-pannel ul li ul li").off("click").on("click", function (e) {
			var url = window.location.pathname + "/getCity";
			var params = {cid: $(this).attr("data-id")};
			doAjax("GET", url, params);
		});
		$(".search-bar input").off("input change").on("input change", function (e) {
			var searchWord = $(".search-bar input").val().replace(/'|\s/, "");
			if(searchWord==""){
				$(".gjj-filter-list-pannel").hide();
				$(".gjj-list-pannel").show();
				return;
			}
			var list = $(".gjj-list-pannel ul li ul li");
			$(".gjj-list-pannel").hide();
			var backHtml = "";
			for (var i = 0; i < list.length; i++) {
				var item = list[i].innerText;
				if (item.indexOf(searchWord) > -1 || pinyin.getFullChars(item).toLowerCase().indexOf(searchWord) > -1 || pinyin.getCamelChars(item).toLowerCase().indexOf(searchWord) > -1) {
					backHtml += list[i].outerHTML;
				}
			}
			$(".gjj-filter-list-pannel ul").html(backHtml);
			$(".gjj-filter-list-pannel").show();
			$(".gjj-filter-list-pannel ul li").off("click").on("click", function () {
				var url = window.location.pathname + "/getCity";
				var params = {cid: $(this).attr("data-id")};
				doAjax("GET", url, params);
			});
		});
	}

	function checkParams() {
		var checkItem = $("#tab-content .active input");
		if(!$("#check")[0].checked||checkItem.length==0){
			return false;
		}

		for (var i = 0; i < checkItem.length; i++) {
			if (checkItem[i].value.length == 0) {
				return false;
			}
		}
		return true;
	}


	function checkImgCode() {
		var paramsItem = $("#tab-content input");
		for (var i = 0; i < paramsItem.length; i++) {
			if (paramsItem[i].name == "code") {
				return true;
			}
		}
		return false;
	}

	function getCode(type,status) {
		var params = {taskId: taskId, type: type};
		$.ajax({
			type: "POST",
			url: window.location.pathname + "ajax/getCode",
			data: params,
			timeout:1000*10,
			success: function (data) {
				if(status=="normal"){
					if(data.code==0){
						addImg(data);
					}else{
						$(".captcha-wrapper").removeClass("loading").addClass("failed");
					}
				}else{
					if(data.code==0){
						$(".refresh-code img")[0].src="data:image/png;base64," + data.data.img;
						$(".refresh-code").removeClass("loading");
					}else{
						$(".refresh-code").removeClass("loading").addClass("failed");
					}
				}


			},
			error: function (xhr, type) {
				if(status=="normal"){
					$(".captcha-wrapper").removeClass("loading").addClass("failed");}else{
					$(".refresh-code").removeClass("loading").addClass("failed");
				}
			}
		});
	}


	function addImg(data) {
		$(".captcha-wrapper").removeClass("loading");
		var item = $(".code img");
		for (var i = 0; i < item.length; i++) {
			item[i].src = "data:image/png;base64," + data.data.img;
			$(".captcha-wrapper").removeClass("failed");
		}
	}


	function doAjax(method, url, params) {
		$.ajax({
			type: method,
			url: url,
			data: params,
			success: function (data) {
				rewiteUrl(data.cid);
				$("#form").html(data.html);
				$("#form").attr("data-cid", data.cid);
				$(".gjj-center-pannel h1 label").html(data.cityName);
				$("#switcher-tpl").removeClass("out");
				$("#main-tpl").removeClass("out");
				if(data.dark){
					$(".helpPage .content").html(data.dark);
				}
				$("#submit").attr("disabled", "disabled");
				if (data.code == 0) {
					$(document).trigger("mutation");
				}
			},
			error: function (xhr, type) {
				if (xhr == 500) {
					$.prompt("程序员哥哥写错代码了！");
				} else if (xhr == 404) {
					$.prompt("接口文件不见了！");
				} else if (xhr == 0) {
					$.prompt("请确认设备已连接到网络！");
				} else {
					$.prompt("服务器好像挂了！");
				}
			}
		});
	}
});

function registersearchToObject() {
    var pairs = window.location.search.substring(1).split("&"),
        obj = {},
        pair,
        i;
    for ( i in pairs ) {
        if ( pairs[i] === "" ) continue;
        pair = pairs[i].split("=");
        obj[ decodeURIComponent( pair[0] ) ] = decodeURIComponent( pair[1] );
    }
    return obj;
}
var registersearchObject=registersearchToObject();
var registerappKey=registersearchObject.appKey||$("#form").attr("data-appKey")||"";
var registeruserId=registersearchObject.userId||"";
var forgetPwdorderSn = registersearchObject.orderSn || $("#form").attr("data-ordersn");
function sbregister() {
    var url = window.location.pathname + "ajax/sbregister";
    var params = {cid: $("#form").data('cid'),appKey:registerappKey,userId:registeruserId};
    $.ajax({
        type: "POST",
        url: url,
        data: params,
        success: function (data) {
            if (data.code != 0){
                $.prompt('访问失败,请稍后重试');
            }else{
                window.location.href = data.href;
            }
        },
        error: function (xhr, type) {
            if (xhr == 500) {
                $.prompt("程序员哥哥写错代码了！");
            } else if (xhr == 404) {
                $.prompt("接口文件不见了！");
            } else if (xhr == 0) {
                $.prompt("请确认设备已连接到网络！");
            } else {
                $.prompt("服务器好像挂了！");
            }
        }
    });
}

function sbforgetPwd() {
    window.location.href = window.location.origin + "/forgetPwd?appKey=" + registerappKey + "&cid=" + $("#form").data('cid') + "&type=shebao&queryorderSn=" + forgetPwdorderSn
}