var resizePart = window.WBActivity.resize = function() {
	$(".shuqian_btn_groups").css({
		top: ($(window).height()-$(".shuqian_btn_groups").height())/2 +20,
		left:($(window).width()-$(".shuqian_btn_groups").width())/2,
		display:'block'
    });
};

var shuqian_data_time;
var tmr_cutdown_start;
var game_cutdown_start;
var game_check_join;
var start = window.WBActivity.start = function() {
    window.WBActivity.hideLoading();
    // msg_control.init();
	// bingkjj();
    $(".Panel.Top").css({
        top: 0
    });
    $(".Panel.Bottom").css({
        bottom: 0
    });
    $(".shu-money,.new_join_user").css({
        display: "block",
    });
    if(shuqian_config['status']==1){
    	$(".g-game-btn").css({
        	display: "block",
    	});
    }else{
    	$(".g-game-btn-restart,.g-game-btn-paiming").show();
    }
    if(shuqian_config['nextid']){
    	$(".g-game-btn-next").show();
    }
    if(shuqian_config['previd']){
    	$(".g-game-btn-prev").show();
    }

	resizePart();
	if(rotate_id=='0'){
         $(".shu-money,.btn-endgame,.new_join_user,.enlarge-qrcode").hide();
         showScore();
         $(".frame-dialog .closebutton").hide();
		 return;
	}else{
		$(".enlarge-qrcode").css({
			visibility: "visible",
		});
		$(".enlarge-qrcode div").addClass('animated rollIn');
	}
	game_check_join = window.setInterval(function() {
		 $.ajax({ 
			type: "post", 
			url : 'ajax_act_shuqian.php?action=shuqian_joinuser',//PATH_ACTIVITY + Path_url('shuqian_joinuser'),
			dataType:'json', 
			// data:{activityid: activityid},
			success: function(data){
				$('.new_join_user span').html('<i>'+data.message+'</i>').find('i').toggleClass('animate-rotate2');
			}
		 });
	},
    2000);
	$(".qr_close").on("click", 
    function() {
		$(".enlarge-qrcode div").attr('class','animated rollOut');
	    setTimeout(function(){
		   $(".enlarge-qrcode").hide();
		},1000);
    });
	$(".g-game-btn").on("click", function() {
		$(this).hide();
		$(".g-game-btn-prev,.g-game-btn-next,.g-game-btn-restart,.g-game-btn-paiming").hide();
		window.clearInterval(game_check_join);
		$('.new_join_user,.enlarge-qrcode').hide();
		$(".shu-num-box").html(ready_time);
		$(".shu-start-tooltip-box").show();
		cutdown_start();
    });
	$(".g-game-btn-restart").on("click", 
    function() {
		if (confirm("重玩本轮会导致本轮成绩作废并清空，您确定吗？")) {
            $.getJSON('ajax_act_shuqian.php?action=shuqian_reset', {
                // activityid: activityid,
                // type: "shuqian_reset"
            },
            function(c) {
			 if(c.code>0){
				// msg_control.ws.send('{"type":"shuqian","ttype":"reset","openid":"meepo_xinchang_shuqian"}');
                window.location.reload()
			 }else{
				layer.msg("重置失败啦");
                window.location.reload()
			 }
            })
        }
    });
	$(".btn-endgame").on("click", function() {
        if (confirm("确定强制结束本轮游戏么？")) {
				// msg_control.ws.send('{"type":"shuqian","ttype":"fast_end_shuqian","openid":"meepo_xinchang_shuqian"}');
				$.getJSON('ajax_act_shuqian.php?action=shuqian_stop', {},function(c) { 
					if(c.code>0){
						window.clearInterval(tmr_cutdown_start);
						window.clearInterval(shuqian_data_time);
						window.location.reload();
					}else{
						layer.msg("操作失败、请重试!");
						window.location.reload()	
					}
				})
		}
	});
	$(".g-game-btn-paiming").on("click", 
    function() {
		$(".shu-money").hide();
        showScore(rotate_id)
    });
	$(".g-game-btn-next").on("click", 
    function() {
		changecurrentconfig(shuqian_config['nextid']);
    });

    $(".g-game-btn-prev").on("click", 
    function() {
		changecurrentconfig(shuqian_config['previd']);
    });
    function changecurrentconfig(id){
    	$.getJSON('ajax_act_shuqian.php?action=changeconfig', {
			id:id
		},
		function(c) {
		 if(c.code>0){
			window.setTimeout(function() {
				window.location.reload()
			},
			500);
		 }else{
			layer.msg('没有更多的轮次了!');
		 }
		})
    };
	$(".game-winner-close").on("click", 
    function() {
		$(".game-winner").hide();
		show_game_start();
    });
	
};
function showScore(b) {
    a='/wall/shuqian_result.php'
    $.showPage(a);
}
var show_game_start = function(){
	resizePart();
	$(".shu-title").show();
};
var cutdown_start = function() {
	var _showtimeHTML = $(".shu-start-tooltip-box");
	var _gameTimeHtml = $(".cutdown-start");
	var _titleHtml = $(".shu-title");
	// msg_control.ws.send('{"type":"shuqian","ttype":"start_readytime","openid":"meepo_xinchang_shuqian"}');
    tmr_cutdown_start = window.setInterval(function() {
        ready_time--;
        if (ready_time == 0) {
			 $.getJSON('/wall/ajax_act_shuqian.php?action=shuqian_start', {},
            function(c) {
                if (c.code > 0) {
                    _showtimeHTML.find('.shu-num-box').html("GO")
                }else if(c.code==-2){
					_titleHtml.hide();
					layer.msg("当前轮数无人参与、无法开始!");
					setTimeout(function(){window.location.reload()},3000);
				} else {
                    layer.msg("游戏初始参数错误，请刷新重新开始");
                    setTimeout(function(){window.location.reload()},3000);
                    
                }
            }).fail(function() {
                layer.msg("无法连接游戏服务器，请刷新重新开始");
                setTimeout(function(){window.location.reload()},3000);
            })
        } else {
            if (ready_time > 0) {
				 $("#Audio_CutdownPlayer")[0].play();
                _showtimeHTML.find('.shu-num-box').html(ready_time);
            }else{
				_titleHtml.hide();
				_showtimeHTML.hide();
                window.clearInterval(tmr_cutdown_start);
				window.shuqian_data_time = setInterval(function(){
					//获取数据
					$.ajax({
						'url':"/wall/ajax_act_shuqian.php?action=working",
						"type":"get",
						"dataType":"json",
						"success":function(json){
							if(json.code>0){
								show_gameuser(json.data);
							}
						}
					})
				},1000);
				game_start();
			}
        }
    },
    1000)
};
var game_start = function() {
	var _gameTimeHtml = $(".cutdown-start");
    _gameTimeHtml.html("");
	_gameTimeHtml.css({
        "margin-left": -_gameTimeHtml.width() / 2 + "px",
        "margin-top": -_gameTimeHtml.height() / 2 + "px",
        "font-size": _gameTimeHtml.height() * 0.7 + "px",
        "line-height": _gameTimeHtml.height() + "px"
    });
	//_gameTimeHtml.addClass("cutdownan-imation");
	_gameTimeHtml.show();
	$(".btn-endgame").show();
	//msg_control.ws.send('{"type":"say","ttype":"start_game","openid":"meepo_xinchang"}');
    game_cutdown_start = window.setInterval(function() {
        game_time--;
        if (game_time == 0) {
			_gameTimeHtml.html(game_time);
        } else {
            if (game_time < 0) {
				//_gameTimeHtml.removeClass("cutdownan-imation");
				_gameTimeHtml.hide();
                window.clearInterval(game_cutdown_start);
                //游戏结束
                $.ajax({
                	"url":"/wall/ajax_act_shuqian.php?action=shuqian_stop",
                	"type":"post",
                	"dataType":"json",
                	"success":function(json){
                		window.clearInterval(shuqian_data_time);
						if(game_end==0){
							game_end = 1;
							$("#Audio_Gameover")[0].play();
							$("body").mLoading({
										text:"正在保存数据、请稍后...",
										icon:'themes/meepo/assets/template/resource/images/loading2.gif'
							});
							//保存数据
							$.ajax({
								"url":"/wall/ajax_act_shuqian.php?action=end",
								"type":"get",
								"dataType":"json",
								"success":function(json){
									$("body").mLoading('hide');
									if(json.code>0){
										console.log(d);
										window.setTimeout(function() {
											show_gameresult(json.data);
											if(shuqian_config['previd']){
										    	$(".g-game-btn-prev").show();
										    }
											if(shuqian_config['nextid']){
												$(".g-game-btn-next").show();
											}
											$(".g-game-btn-restart,.g-game-btn-paiming").show();
											$(".btn-endgame").hide();
										},
										660);
									}else{
										layer.msg("数据存贮失败!");
									}
								}
							});

						}
                	}
                })
            } else {
                _gameTimeHtml.html(game_time);
            }
        }
    },
    1000)
};

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)) {
				rankTopTen = list.slice(0, 10);
				var f = $(".shu-rank-item");
				f.each(function(n) {
					var j = list[n],
						i = " ",
						l = 0,
						o;
					if (j) {
						i = j.client_name;
						l = parseInt(j.score*100);
						o = j.client_avatar
					}
					var q = $(this);
					var m = q.find(".shu-rank-item-score");
					if (parseInt(m.text() > l)) {
						return
					}
					if (l > 0) {
						var p = Math.floor(l / 25000 * 400);
						p = p > 400 ? 400 : p;
						q.find(".shu-rank-item-body").css("height", p)
					} else {
						q.find(".shu-rank-item-body").css("height", 0)
					}
					q.find(".shu-rank-item-name").html(i);
					m.text(l);
					var r = q.find(".shu-rank-item-info > img");
					if (o) {
						r.css("visibility", "visible");
						r.attr("src", o)
					} else {
						r.css("visibility", "hidden")
					}
				});
			}
}
var show_gameresult = function(rankTop){
	if ($.isArray(rankTop)) {
				var f = $(".game-winner-item");
				f.each(function(n) {
					var j = rankTop[n],
						i = " ",
						l = 0,
						o;
					if (j) {
						i = j.client_name;
						l = parseInt(j.score*100);
						o = j.client_avatar;
						var q = $(this);
						var m = q.find(".gn-item-number");
						m.text("￥"+l);
						q.find(".gn-item-name").html(i);
						var r = q.find(".gn-item-head > img");
						r.attr("src", o);
						r.css({
							"display": 'block'
						});
					}
				});
				 if(rankTop.length>3){
					var f = $(".game_winner_other_box");
					f.each(function(n) {
						var j = rankTop[(n+3)],
							i = " ",
							l = 0,
							o;
						if (j) {
							i = j.client_name;
							l = parseInt(j.score*100);
							o = j.client_avatar;
							var q = $(this);
							var m = q.find(".winner_head_boxscore");
							m.text("￥"+l);
							q.find(".winner_head_box-name").html(i);
							var r = q.find(".winner_head_box > img");
							r.attr("src", o)
						}
						
					});
				 }
	}
	$(".game-winner").show();

}
function transform(obj){
    var arr = [];
    for(var item in obj){
	  if(obj[item].client_openid!='meepo_xinchang_shuqian'){
			arr.push(obj[item]);
	  }
    }
    return arr;
}
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");
   
};