var WEB_URL = "themes/meepo/assets/";
// var audio_Outride;
var Track={
    "tracklist_elm":null,
    "track_elm":null,
    "width":0,
    "height":0,
    "size":0,
    "init":function(){
        if(this.tracklist_elm==null){
            this.tracklist_elm=$(".Panel.Track .tracklist");
            this.track_elm=this.tracklist_elm.children();
        }
        this.height
            =THEME_INFO.themedata.ishorizontal==1?
            (this.tracklist_elm.height() / 10):(this.tracklist_elm.height());
        this.width=THEME_INFO.themedata.ishorizontal==1?(this.tracklist_elm.width()-this.height):(this.tracklist_elm.width()/10);
        this.size=this.height>this.width?this.width:this.height;
        
        //终点图片设置
        var endline_css=null;
        //起点图片设置
        var startline_css=null;
        var trackodd_css=null;
        if(THEME_INFO.themedata.ishorizontal==1){
            startline_css={'background':"url("+THEME_INFO.themedata.startline_path+") repeat-y left center","background-size":"10px auto"};
            endline_css={'background':"url("+THEME_INFO.themedata.endline_path+") repeat-y center center","background-size":"45px auto;"};
        }else{
            startline_css={'background':"url("+THEME_INFO.themedata.startline_path+") repeat-x left bottom"};
            endline_css={'background':"url("+THEME_INFO.themedata.endline_path+") repeat-x center center"};
        }
        trackodd_css={"background":"url("+THEME_INFO.themedata.trackodd_path+") repeat"};
        trackeven_css={"background":"url("+THEME_INFO.themedata.trackeven_path+") repeat"};
        $('.yyycj .paoma .xxx').css(startline_css);
        $('.yyycj .zd').css(endline_css);
        $('.yyycj ul li').css(trackodd_css);
        $('.yyycj ul li:nth-child(2n)').css(trackeven_css);
        


        //奇数跑道背景图
        //偶数跑道背景图
    },
    "resize":function(){
        this.init();
        var self=this;
        this.track_elm.each(function(){
            $(this).css({
                height: self.height,
                "line-height": self.size + "px",
                "font-size": self.size * 3 / 5 + "px"
            }).find('.ma').css({
                "width":THEME_INFO.themedata.ishorizontal==1?"0px":"100%",
                "height":THEME_INFO.themedata.ishorizontal==1?"100%":"0px",
            });
            $(this).find('.tutu').css({
                "width":THEME_INFO.themedata.ishorizontal==1?"0px":"100%",
                "height":THEME_INFO.themedata.ishorizontal==1?"100%":"0px",
            });
        });
    },
    "ph_arr":[],
    "showprogress":function (index,player){
        if(this.tracklist_elm==null){
            this.resize();
        }
        if(this.ph_arr[index]==undefined){
            this.ph_arr[index]=$("#ph"+index);
        }
        var ph=this.ph_arr[index];
        //赋值
        var nicheng=$("#nc"+index,ph);
        nicheng.html(player["nickname"]);
        var symbol=$('#symbol'+index,ph);
        symbol.attr('src',THEME_INFO.themedata['avatar_'+(index+1)+'_path']);
        var tx= $("#tx"+index,ph);
        if(index<3 && player['progress']>=100){
            tx.attr("src",WEB_URL+"images/shake/p"+index+".jpg");
        }else{
            tx.attr("src",player["avatar"]);
        }
        if(THEME_INFO.themedata.ishorizontal==1){
            //横向
            ph_css={"min-width":this.size+'px',"width":player["progress"]+"%","margin-top":"-"+this.size/2+"px"};
            symbol_css={"max-height":this.size+'px'};
        }else{
            //纵向
            ph_css={"min-height":this.size+'px',"height":player["progress"]+"%","margin-left":"-"+this.size/2+"px"};
            symbol_css={"max-width":this.size+'px',"left":((this.width-symbol.width())/2)+'px'}
        }
        symbol.css(symbol_css);
        var touxiang_shift=THEME_INFO.themedata.ishorizontal==1?(symbol.width()+4):(symbol.height()+4);
        var nicheng_shift=touxiang_shift+(THEME_INFO.themedata.ishorizontal==1?(tx.width()+4):(tx.height()+4));
        if(THEME_INFO.themedata.ishorizontal==1){
            tx.css({'right':touxiang_shift+'px'});
            nicheng.css({'right':nicheng_shift+'px'});
        }else{
            tx.css({'top':touxiang_shift+'px'});
            nicheng.css({'top':nicheng_shift+'px'});
        }
        ph.animate(ph_css,1000);
        $("#pxh"+index).animate(ph_css,1000);
    }
}

var StartPage={
    "qrcode":'',
    "round_welcome_elm":null,
    "radar_timer":null,
    "getplayer_timer":null,
    "showusers":[],
    "userindex":0,
    "init":function(){
        var self=this;
        function initQrcode(){
            self.qrcode=$(window.top.document).find('.mp_account_codeimage.qrcode').attr('src');
            self.qrcode=self.qrcode.replace('./','/');
            self.round_welcome_elm=$('.round-welcome');
            self.round_welcome_elm.find('img.qr').attr("src",self.qrcode);
        }
        initQrcode();
        //初始化按钮 是否显示
        if(SHAKE_CONFIG.status==1){
            $('.button-restart').hide();
            $('.button-round-rank').hide();
        }
        if(SHAKE_CONFIG.status==2){
            $('.radar').hide();
            $('.round-label2').hide();
        }
        if(SHAKE_CONFIG.status==3){
            $('.button-start').hide();
            $('.radar').hide();
            $('.round-label2').hide();
        }

        if(SHAKE_CONFIG.previd==null){
            $('.button-round.round-prev').hide();
        }

        if(SHAKE_CONFIG.nextid==null){
            $('.button-round.round-next').hide();
        }

        $('.button-round-rank').on('click',function(){
            EndPage.showScore();
        });
        $('.button-restart').on('click',function(){
             resetgame();
        });
        //绑定按钮事件
        $('.button-round.round-next').on('click',function(){
            window.location.href="shake.php?id="+SHAKE_CONFIG.nextid;
        });
        $('.button-round.round-prev').on('click',function(){
            window.location.href="shake.php?id="+SHAKE_CONFIG.previd;
        });
        $('.button-start').on('click',function(){
            self.slideUp();
            countdown(3,startgame);
        });
        //初始化轮次标签
        $('.round-label').text('轮次编号：'+SHAKE_CONFIG.id);
        //加载雷达
        if(SHAKE_CONFIG.status==1){
            self.getplayers();
            self.showuser();
        }
    },
    "slideDown":function(func){
        if(this.qrcode==''){
            this.init();
        }
        $(window.top.document).find('#show_hide_nav img').trigger('click');
        this.round_welcome_elm.slideDown(func);
    },
    "slideUp":function(func){
        var self=this;
        if(this.qrcode==''){
            this.init();
        }
        $(window.top.document).find('#show_hide_nav img').trigger('click');
        clearTimeout(self.getplayer_timer);
        clearTimeout(self.radar_timer);
        this.round_welcome_elm.slideUp(func);
    },
    "getplayers":function(){
        var self=this;
        $.ajax({ 
          type: "post", 
          url : "ajax_act_shake.php?action=joinuser",
            dataType:'json', 
            success: function(json){
                $('.round-label2 span').html('<i>'+json.data.num+'</i>').find('i').toggleClass('animate-rotate2');
                if(json.data.players!=null && json.data.players.length>0){
                    self.showusers=self.showusers.concat(json.data.players);

                }
                self.getplayer_timer=setTimeout(function(){self.getplayers()},3000);
            }
         });
    },
    "showuser":function(){
        var self=this;
        if(self.showusers.length<=0){
            self.radar_timer=setTimeout(function(){self.showuser()},1000);
            return;
        }
        self.userindex++;
        var user=self.showusers.shift();
        $('#Audio_NewPlayer')[0].play();
        var n = '<div id="shake_user_' + self.userindex + '" class="user-item"><div class="user-img"><img src="' + user.avatar + '" /></div><p></p></div>';
        if($('.user-item').length>9){
        $('.user-item').eq(0).animate({opacity: 0},1000,function(){
          $(this).remove();
          $(n).appendTo(".users").animate({
            opacity: 0.7
          },
          500);
          console.log(2);
        });
        }else{
        $(n).appendTo(".users").animate({
            opacity: 0.7
          },
          500);
        }
        self.radar_timer=setTimeout(function(){self.showuser()},1000);
    }
}
var resizePart = window.WBActivity.resize = function() {
    if(THEME_INFO.themedata.ishorizontal==1){
        $('.tracklist').removeClass('vertical');
        $('.tracklist').addClass('horizontal');
    }else{
        $('.tracklist').removeClass('horizontal');
        $('.tracklist').addClass('vertical');
    }
    //赛道
    // Track.init();
    Track.resize();
};

var start = window.WBActivity.start = function() {
    window.WBActivity.hideLoading();
    //超越时播放
    $(".Panel.Top").css({
        top: 0
    });
    $(".Panel.Bottom").css({
        bottom: 0
    });
    $(".Panel.Track").css({
        display: "block",
        opacity: 1
    });
    //重新计算各元素尺寸;
    resizePart();
    //初始化二维码
    window.setTimeout(function() {
        nextRound()
    },
    1000);
};
//倒计时函数
//避免重复点倒计时按钮
var startcountdown=false;
function countdown(time,callback_func){
    if(startcountdown==true)return;
    startcountdown=true;
    var lefttime=time;//倒数3秒
    var countdown_lb = $(".cutdown-start");
    countdown_lb.html(time).show().css({
        "margin-left": -countdown_lb.width() / 2 + "px",
        "margin-top": -countdown_lb.height() / 2 + "px",
        "font-size": countdown_lb.height() * 0.7 + "px",
        "line-height": countdown_lb.height() + "px"
    }).addClass("cutdownan-imation");
    var countdown_audio=$('#Audio_CutdownPlayer')[0];
    countdown_audio.play();
    lefthandler=setInterval(function(){
        lefttime=lefttime-1;
        countdown_audio.play();
        if(lefttime>0){
            countdown_lb.html(lefttime);
        }else{
            //倒计时结束
            countdown_lb.html('GO!!!');
            clearInterval(lefthandler);
            startcountdown=false;
            setTimeout(function(){
                countdown_lb.hide();
                callback_func();
            },1000);
        }
    },1000);
}

//游戏过程
function gameworking(){
    $.ajax({
        "url":"ajax_act_shake.php?action=working",
        "type":"get",
        "dataType":"json",
        "success":function(json){
            if(json.code>0){
                SHAKE_CONFIG.status=json.status;
                if(json.status==1){
                    clearTimeout(workingdata_timer);
                    Slogan.hide();
                    alert("游戏被重置了，5秒后将刷新页面，重新开始");
                    setTimeout(function(){
                        window.location.reload();
                    },5000);

                }
                if(json.status==2){
                    for(var i=0,l=json.data.length;i<l;i++){
                        Track.showprogress(i,json.data[i]);
                    }
                    Slogan.show();
                    workingdata_timer=setTimeout(function(){
                        gameworking();
                    },1000);
                }
                if(json.status==3){
                    TOPTEN=json.data;
                    for(var i=0,l=json.data.length;i<l;i++){
                        Track.showprogress(i,json.data[i]);
                    }
                    EndPage.show();
                    Slogan.hide();
                    clearTimeout(workingdata_timer);
                }
            }else{
                alert("数据可能出现错误，5秒后尝试刷新页面，重新开始");
                setTimeout(function(){
                    window.location.reload();
                },5000);
            }
        },
        "error":function(){
            alert("网络可能断了，5秒后尝试重新连接，请刷新重新开始");
            setTimeout(function(){
                window.location.reload();
            },5000);
            
        }
    });
}

function gameresult(func){
    $.ajax({
        "url":"ajax_act_shake.php?action=result",
        "type":"get",
        "dataType":"json",
        "success":function(json){
            if(json.code>0){
                if(json.status==3){
                    TOPTEN=json.data;
                    for(var i=0,l=json.data.length;i<l;i++){
                        Track.showprogress(i,json.data[i]);
                    }
                }
                func();
            }else{
                alert("数据可能出现错误，5秒后尝试刷新页面，重新开始");
                setTimeout(function(){
                    window.location.reload();
                },5000);
            }
        },
        "error":function(){
            alert("网络可能断了，5秒后尝试重新连接，请刷新重新开始");
            setTimeout(function(){
                window.location.reload();
            },5000);
            
        }
    });
}


var workingdata_timer=null;
function startgame(){
    $.ajax({
        "url":"ajax_act_shake.php?action=start",
        "type":"get",
        "dataType":"json",
        "success":function(json){
            if(json.code>0){
                //开始计算并显示跑道进度
                gameworking();
            }else{
                alert(json.message);
                window.location.reload();
            }
        },
        "error":function(){
            alert("网络可能断了，5秒后尝试重新连接，请刷新重新开始");
            setTimeout(function(){
                window.location.reload();
            },5000);
        }
    })
}

// function stopgame(){

// }

function resetgame(){
    $.ajax({
        "url":"ajax_act_shake.php?action=reset",
        "type":"get",
        "dataType":"json",
        "success":function(json){
            alert("重置成功，3秒后重新自动刷新页面");
            setTimeout(function(){
                window.location.reload();
            },3000);
        },
        "error":function(){
            alert("网络可能断了，5秒后尝试重新连接，请刷新重新开始");
            setTimeout(function(){
                window.location.reload();
            },5000);
        }
    });
}

var nextRound = function() {
    $(".result-layer").hide();
    if(SHAKE_CONFIG.id==undefined){
        alert("游戏不存在。");
        window.location.href='/wall/index.php';
    }
    if(SHAKE_CONFIG.status==1){
        StartPage.slideDown();
    }
    //轮次已经开始的
    if(SHAKE_CONFIG.status==2){
        StartPage.slideUp(function() {
            startgame();
        });
    }
    if(SHAKE_CONFIG.status==3){
        StartPage.slideDown();
    }
};
var EndPage={
    "result_layer":null,
    "result_label":null,
    "result_cap":null,
    "player_tp":$("<div class='player'><div class='head'></div><div class='nickname'></div></div>"),
    "showGameoverPage":function(){
        this.result_layer.show();
        this.result_label.show().addClass('pulse');
        this.result_cup.hide();
        $('#Audio_Gameover')[0].play();
    },
    "bindButtons":function(){
        var self=this;
        var result_btn=$('.allresult',this.result_layer);
        var prev_btn=$('.prevround',this.result_layer);
        var next_btn=$('.nexttound',this.result_layer);
        var reset_btn=$('.reset',this.result_layer);

        if(SHAKE_CONFIG.previd==null){
            prev_btn.hide();
        }else{
            prev_btn.on('click',function(){
                window.location.href='shake.php?id='+SHAKE_CONFIG.previd;
            });
        }
        if(SHAKE_CONFIG.nextid==null){
            next_btn.hide();
        }else{
            next_btn.on('click',function(){
                window.location.href='shake.php?id='+SHAKE_CONFIG.nextid;
            });
        }
        result_btn.on('click',function(){
            self.showScore();
        });
        reset_btn.on('click',function(){
            resetgame();
        });
    },
    "show":function(){
        var self=this;
        this.result_layer=$('.result-layer');
        this.result_label=$('.result-label',this.result_layer);
        this.result_cup=$('.result-cup',this.result_layer);
        winner_num=3;
        this.showGameoverPage();
        if(TOPTEN==null){
            gameresult(showrank);
        }else{
            showrank();
        }
        function showrank(){
            self.bindButtons();
            window.setTimeout(function() {
                self.result_label.fadeOut(function() {
                    self.result_cup.show(function() {
                        if (winner_num >= 1 && TOPTEN[0]) {
                            window.setTimeout(function() {
                                var e = self.player_tp.clone().addClass("result").css({
                                    left: "50%",
                                    "margin-left": "-65px",
                                    width: "160px",
                                    height: "160px",
                                    bottom: "150px"
                                });
                                e.find(".head").css({
                                    "background-image": "url(" + TOPTEN[0]["avatar"] + ")"
                                }).addClass("shake");
                                e.find(".nickname").html(TOPTEN[0]["nick_name"]);
                                e.appendTo(self.result_cup).addClass("bounce");
                                console.log('1');
                            },
                            800)
                        }
                        if (winner_num >= 2 && TOPTEN[1]) {
                            window.setTimeout(function() {
                                var e = self.player_tp.clone().addClass("result").css({
                                    left: "40px",
                                    width: "100px",
                                    height: "100px",
                                    bottom: "120px"
                                });
                                e.find(".head").css({
                                    "background-image": "url(" + TOPTEN[1]["avatar"] + ")"
                                }).addClass("shake");
                                e.find(".nickname").html(TOPTEN[1]["nick_name"]);
                                e.appendTo(self.result_cup).addClass("bounce")
                                console.log('2');
                            },
                            1800)
                        }
                        if (winner_num >= 3 && TOPTEN[2]) {
                            window.setTimeout(function() {
                                var e = self.player_tp.clone().addClass("result").css({
                                    right: "30px",
                                    width: "70px",
                                    height: "70px",
                                    bottom: "100px"
                                });
                                e.find(".head").css({
                                    "background-image": "url(" + TOPTEN[2]["avatar"] + ")"
                                }).addClass("shake");
                                e.find(".nickname").html(TOPTEN[2]["nick_name"]);
                                e.appendTo(self.result_cup).addClass("bounce")
                                console.log('3');
                            },
                            2800)
                        }

                        
                    })
                }).removeClass("pulse");
            },
            1000);
            
        }
    },
    'showScore':function(){
        var url = PATH_ACTIVITY + Path_url('shake_result.php');
        $.showPage(url);
    }
};


var Slogan={
    'slogan_timer':null,
    "show":function(){
        var tips= ($.isArray(THEME_INFO.themedata.tips) && THEME_INFO.themedata.tips.length > 0) ? 
            THEME_INFO.themedata.tips: [
                "再大力！", "再大力,再大力！", "再大力,再大力,再大力！", "摇，大力摇", 
                "快点摇啊，别停！", "摇啊，摇啊，摇啊", "小心手机，别飞出去伤到花花草草", "看灰机～～～"
            ];
        var tips_len=tips.length;
        var sloganlist=$('.Panel.SloganList');
        sloganlist.css({top: "-15%"}).show();
        sloganlist.css({
            top: 0,
            "line-height": sloganlist.height() + "px"
        });
        if(this.slogan_timer==null){
            this.slogan_timer=setInterval(function(){
                sloganlist.html(tips[Math.floor(Math.random()*tips_len)]);
            },2000);
        }
    },
    "hide":function(){
        clearInterval(this.slogan_timer);
        $(".Panel.SloganList").hide();
    }
}
//加载背景内容
$(function(){
    if(THEME_INFO.themedata.bg_path!=''){
        var point = THEME_INFO.themedata.bg_path.lastIndexOf("."); 
        var type = THEME_INFO.themedata.bg_path.substr(point); 
        if(type=='.mp4'){
            $(window.top.document).find('iframe').css({"background-image":""});
            $(window.top.document).find('.bgvideo video').attr('src',THEME_INFO.themedata.bg_path);
        }else{
            $(window.top.document).find('.bgvideo video').attr('src','');
            $(window.top.document).find('iframe').css({"background-image":"url("+THEME_INFO.themedata.bg_path+")"});
        }
    }else{
        var bg=window.top.BACKGROUNDIMAGE['shake'];
        if(bg.bgtype==2){
            $(window.top.document).find('iframe').css({"background-image":""});
            $(window.top.document).find('.bgvideo video').attr('src',bg['path']);
        }else{
            $(window.top.document).find('.bgvideo video').attr('src','');
            $(window.top.document).find('iframe').css({"background-image":"url("+bg['path']+")"});
        }
        
    }
});