var gameInterval;
var msg_control = {
	ws:{},
	init:function(){
		this.ws = new WebSocket($socket_url);
		this.ws.onopen = this.ws_onopen;
		this.ws.onclose = this.ws_onclose;
		this.ws.onmessage = this.ws_onmessage;
	},
	ws_onopen:function(){
		console.log('connection...');
		var login_data = '{"type":"horse_login","client_name":"com","client_avatar":"com","rid":"'+scene_id+'","room_id":"horse_'+rotate_id+'","openid":"meepo_xianchang_horse","score":0}';
		msg_control.ws.send(login_data);
	},
	ws_onclose:function(e){
		layer.msg('链接失败了!',{time:5000});
		// window.location.reload();
	},
	ws_onmessage:function(e){
		var data =  $.parseJSON(e.data);
		switch(data.type){
			case 'ping':
				msg_control.ws.send('{"type":"pong"}');
				break;
			case 'error':
				window.close(alert(data.msg));
				break;
			case 'sendlink':
				alert(data.msg);
				break;
			case 'logout':
				//掉线后，修改在线人数
				if(data.status){
					msg_control.ws.send('{"type":"horse","ttype":"getuser","openid":"meepo_xianchang_horse"}');
					var total = parseInt($(".joinNum").text().replace(/[^0-9]/ig,""));
					$(".joinNum").text(total - 1 +'人');
					$('#' + data.from_client_id).attr('src',default_userimg).attr('id','');
				}
				break;
			case 'horse_users':
				if(game_end==0) show_gameuser(data.clients_list);
				break;
			case 'horse_getuser':
				if(data.errno == 0){
					$(".joinNum").text(data.total+'人');
					if(data.user != '') joinuser(data.user);
				}else{
					msg_control.ws.send('{"type":"horse","ttype":"getuser","openid":"meepo_xianchang_horse"}');
				}
				break;
			case 'horse_status':
				if(data.status == 'start'){
					if(data.errno == 0){
						$('.cutdown-start').html("GO!");
					}else if(data.errno == -2){
						$('.cutdown-start').hide();
						layer.msg("当前轮数无人参与、无法开始!");
						window.location.reload();
					}else{
						msg_control.ws.send('{"type":"horse","ttype":"gamereset","openid":"meepo_xianchang_horse"}');
						layer.msg("游戏初始参数错误！");
						window.location.reload();
					}
				}else if(data.status == 'reset'){
					var layer_i = layer.load(2, {shade: false});
					layer.close(layer_i);
					if(data.errno == 0){
						msg_control.ws.send('{"type":"horse","ttype":"gamereset","openid":"meepo_xianchang_horse"}');
						layer.msg('重置成功',{time:2000});
						window.location.reload();
					}else{
						layer.msg('网络错误、请稍后重试！',{time:2000});
					}
				}else if(data.status == 'stop'){
					var layer_i = layer.load(2, {shade: false});
					layer.close(layer_i);
					if(data.errno == 0){
						msg_control.ws.send('{"type":"horse","ttype":"gamereset","openid":"meepo_xianchang_horse"}');
						window.location.reload();
					}else{
						layer.msg('网络错误、请稍后重试！',{time:2000});
					}
				}
				break;
		}
	}
};
function joinuser(join_user){
	var num = join_user.length;
	for(var i = 0; i < 10; i++){
		if (!join_user.hasOwnProperty(i)) {
			$(".main_right .list img").eq(i).attr('src',default_userimg).attr('id','');
		} else {
			$(".main_right .list img").eq(i).addClass('flash animated infinite');
			$(".main_right .list img").eq(i).attr('src',join_user[i].avatar).attr('id',join_user[i].id);
			(function(i) {
				setTimeout(function() {
					$(".main_right .list img").eq(i).removeClass('flash animated infinite');
				}, 1000);
			})(i)
		}
	}
}
;(function(k, e) {
	var A = k.WBActivity.resize = function() {
		resize();
	};
	var c = k.WBActivity.start = function() {
		k.WBActivity.hideLoading();
		bingkjj();
		msg_control.init();
		if(rotate_id==0){
			layer.msg('3D赛马活动已经全部结束!');
			showScore();
			return;
		}else{
			initpage();
		}
		$('body').css({'background':"none"});
		$(".welcome_box").show(function(){//开页动效果
			$('.main_box').css('display','flex');
			$(this).find('.main_left').animateControl('rotateInDownLeft');
			$(this).find('.main_right').animateControl('rotateInDownRight');
		});
		$(".paiming").on('click',function(){//排行榜
			if(rotate_id!='0') showScore(rotate_id);
		});
		$(".startbtn").on('click',function(){//开始
			$(".welcome_box").animateControl('bounceOut',function(){ 
				$('.welcome_box').hide();
				var countbox = $('.cutdown-start');
				countbox.html(ready_time).show().css({
					"margin-left": -countbox.width() / 2 + "px",
					"margin-top": -countbox.height() / 2 + "px",
					"font-size": countbox.height() * 0.7 + "px",
					"line-height": countbox.height() + "px"
				});
				hideSlogan();
				msg_control.ws.send('{"type":"horse","ttype":"gamestart","openid":"meepo_xianchang_horse"}');
				countdown(ready_time,function(c){//返回倒计时时间
					if(!countbox.hasClass("cutdownan-imation")) countbox.addClass("cutdownan-imation");
					countbox.html(c);
				},function(){//倒计时结束
					clearInterval(user_interval);
					countbox.removeClass("cutdownan-imation").hide();
					$(".yyy3d_title_box .time-down").text(game_time);
					$(".yyy3d_title_box").show().animateControl('shake');
					if($("#carrun").length>0) $("#carrun")[0].play();
					$(".paomabeijing2,.paomabeijing,.tracklist").addClass('okplay');//开启移动效果
					gameInterval = setInterval(function(){
						msg_control.ws.send('{"type":"horse","ttype":"gameusers","openid":"meepo_xianchang_horse"}');
					},500);
					game_countdown(game_time,function(k){
						$(".yyy3d_title_box .time-down").text(k);
					},function(){
						var layer_i = layer.load(2, {shade: false});
						var Post_user = total_user.slice(0,post_persons);
						$.ajax({
							url: PATH_ACTIVITY + Path_url('horse_tstop'),
							timeout: 15000,
							type: 'POST',
							dataType: 'json',
							data: {rid: scene_id,rotate_id: rotate_id,user: Post_user},
							success: function (json) {
								layer.close(layer_i);
								if(json.errno==0){
									$("#Audio_Gameover")[0].play();
									show_gameresult(rankTopTen);
								}else{
									layer.msg("网络太差、数据存贮失败!");
								}
							}, 
							error: function(e) { 
								layer.msg("链接服务器失败了");
							} 
						});
					},function(){
						msg_control.ws.send('{"type":"horse","ttype":"gameend","openid":"meepo_xianchang_horse"}');
						$(".paomabeijing2,.paomabeijing,.tracklist").removeClass('okplay');
						$(".player .lunzia,.player .lunzib").removeClass('okplay');
						$(".yyy3d_title_box").html("游戏结束!");
						if($("#carrun").length>0) $("#carrun")[0].pause();
						clearInterval(gameInterval);
						game_end = 1;
					});
				},function(){//开始游戏
					msg_control.ws.send('{"type":"horse","ttype":"gamestatus","openid":"meepo_xianchang_horse","status":"start"}');
				});
			});
		});
		$(".nextbtn").on('click',function(){//下一轮
			msg_control.ws.send('{"type":"horse","ttype":"gamereset","openid":"meepo_xianchang_horse"}');
			window.location.reload();
		});
		$(".resetbtn").on('click',function(){//重玩
			layer.confirm('您确定重玩本轮游戏么吗？', {
				title:false,
				btn: ['确定', '取消'],
			}, function(index, layero){
				var layer_i = layer.load(2, {shade: false});
				msg_control.ws.send('{"type":"horse","ttype":"gamestatus","openid":"meepo_xianchang_horse","status":"reset"}');
			}, function(index){
				layer.close(index);
			});
		});
	}
})(window, jQuery);
var show_gameuser = function(list){
	list = transform(list);
	list = list.sort(function(a, b){
		return b.score - a.score;
	});
	total_user = list;
	if ($.isArray(list) && list.length>0) {
		rankTopTen = list.slice(0, 10);
		var $players = $(".player");
		$players.each(function(n) {
			var p = rankTopTen[n];
			if(p){
				if(p.score >= max_score) $(".yyy3d_title_box .time-down").text(0);
				var avatar = p.client_avatar;
				var nickname = p.client_name;
				var progress = (p.score/max_score)*100;
				$(this).css("left",progress+'%');
				$(this).find('.head').css({"background-image":"url("+avatar+")"});
				$(this).find('.nickname').text(nickname);
				$(this).show();
			}
		});
	}
}
var show_gameresult = function(rankTop){
	if ($.isArray(rankTop) && rankTop.length>0) {
		var rank_others = $('.rank_others li');
		$.each(rankTop,function(k,v) {
			var j = rankTop[k];
			if(j && k<3){
				if(k==0){
					$('.rank1').find('.avarta img').attr('src',j.client_avatar);
					$('.rank1').find('p').text(j.client_name);
				}else if(k==1){
					$('.rank2').find('.avarta img').attr('src',j.client_avatar);
					$('.rank2').find('p').text(j.client_name);
				}else{
					$('.rank3').find('.avarta img').attr('src',j.client_avatar);
					$('.rank3').find('p').text(j.client_name);
				}	
			}
			if(j && k>=3){
				var eq_index = k - 3;
				rank_others.eq(eq_index).find('.avarta').attr('src',j.client_avatar);
				rank_others.eq(eq_index).find('p').text(j.client_name);
			}
		});
	}
	$(".rank_box").show().animateControl('bounceIn');//显示排行榜
}
function showScore(b) {
	var a = PATH_ACTIVITY + Path_url('horse_result')+"&rid=" + scene_id;
	if (b != undefined) a += "&rotate_id=" + b;
	$.showPage(a)
}
function transform(obj){
	var arr = [];
	for(var item in obj){
		if(obj[item].client_openid!='meepo_xianchang_horse') arr.push(obj[item]);
	}
	return arr;
}
function countdown(c,d, a,f) {
	var b = setInterval(function() {
		c = c -1;
		if (c < 0) {
			clearInterval(b);
			if (a) a();
		}else if(c > 0){
			$("#Audio_count")[0].play();
			if (d) d(c);
		}else {
			if (f) f();
		}
	}, 1e3)
};
function game_countdown(c,d, a,f) {
	var b = setInterval(function() {
		c = c -1;
		var t = $(".yyy3d_title_box .time-down").text();
		if(t == 0) c = 0;
		if (c > 0) {
			if (d) d(c);
		}else {
			clearInterval(b);
			if (a) a();
			if (f) f();
		}
	}, 1e3)
};
function resize(){
	$(".trackline").css({
		"height":$(".tracklist").height()/10+'px',
		"line-height":$(".tracklist").height()/10+'px',
		"font-size":$(".tracklist").height()/20+'px',
	});
	$(".track-start").css({
		"height":$(".tracklist").height()/10+'px',
		"width":$(".tracklist").height()/10+'px',
	});
	$(".track-end").css({
		"height":$(".tracklist").height()/10+'px',
	});
	$(".player").css({
		"width":"11.9px",
		"height":$(".tracklist").height()/10+'px',
		"line-height":$(".tracklist").height()/10+'px',
		"font-size":$(".tracklist").height()/20+'px',
	});
	$(".player").each(function(key,ele) {
		var onePlayer = $(this);
		onePlayer.css({
			"top":($(".tracklist").height()/10*key+10)+'px',
		});
	});
}
var show_id = 0;
function snabbt_user(obj,n,src,id){
	var avarta = n.find("img")[0];
	var pobj = n.find("p")[0];
	snabbt.sequence([
		[n[0],
		{
			formScale: [.5, .5],
			rotation: [0, 0, 2 * -Math.PI],
			scale: [3, 3],
			easing: "easeOut",
			duration: 800
		}],
		[pobj,
		{
			delay: 1e3,
			scale: [0, 0],
			easing: "easeIn",
			duration: 400
		}],
		[avarta,
		{
			scale: [0, 0],
			easing: "easeOut",
			duration: 400,
			complete: function() {
				n.remove();
				obj.attr('src',src).attr('id',id);
				if (!$('.welcome_box').is(':hidden')) show_id++;
			}
		}]
	])
}
function initpage(){
	var html = '';
	for(var i=0;i<10;i++){
		var height = $(".tracklist").height()/10;
		html += '<div class="trackline leftfadein" style="display: block; height: '+height+'px; line-height: '+height+'px; font-size: '+height/2+'px;">';
		html += '<div class="track-start" style="width: '+height+'px; height: '+height+'px;">'+ (i +1 )+'</div>';
		html += '<div class="track-end" style="width:6px; height: '+height+'px;"></div>';
		html += '</div>';
	}
	$('.tracklist').append(html);
	var player = '';
	for(var i=0;i<10;i++){
		player += '<div class="player player'+i+'">';
		player += '<div class="yyytp">';
		player += '<div class="lunzia car'+i+' okplay"></div>';//后轮
		player += '<div class="lunzib car'+i+' okplay"></div>';//前轮
		player += '</div>';
		player += '<div class="pnctx">';
		player += "<div class='head shake' style='background-image: url("+default_userimg+")'></div>";
		player += '<div class="nickname">选手'+(i+1)+'号</div>';
		player += '</div>';
		player += '</div>';
	}
	$('.tracklist').append(player);
	$(".yyy3d").removeClass('page_hidden');
	$(".track-end").show();
	resize();
}

function hideSlogan() {
	$(".Panel.Top").css({top: "-" + $(".Panel.Top").height() + "px"});
	$(".Panel.Bottom").css({bottom: "-" + $(".Panel.Bottom").height() + "px"});
	$("#panel_status").val("0");
}
function showSlogan() {
	$(".Panel.Top").css({top: 0});
	$(".Panel.Bottom").css({bottom: 0})
	$("#panel_status").val("1");
};
;(function($) {
	$.fn.extend({
		animateControl: function (a,fn) {
			this.addClass('animated ' + a).one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
				if(fn) fn();
				$(this).removeClass('animated ' + a);
			});
			return this;
		}
	});
})(jQuery);