//      //显示加载器
// function showLoader() {
//     //显示加载器.for jQuery Mobile 1.2.0
//     $.mobile.loading('show', {
//         text: '加载中...', //加载器中显示的文字
//         textVisible: true, //是否显示文字
//         theme: 'a',        //加载器主题样式a-e
//         textonly: false,   //是否只显示文字
//         html: ""           //要显示的html内容，如图片等
//     });
// }
// //隐藏加载器.for jQuery Mobile 1.2.0
// function hideLoader()
// {
//     //隐藏加载器
//     $.mobile.loading('hide');
// }
function doTestDebUi(msg)
{
    if(isString(msg))
    {
        myUIAlert("doTestDebUi:"+msg);
    }else{
        myUIAlert("doTestDebUi:"+JSON.stringify(msg));
    }

}
function doTestUILogerObj(obj,step)
{
    var msg=JSON.stringify(obj);
    doTestUILoger(step+":"+msg);
}
function doTestUILoger(msg)
{
   var old= jQuery("#ip_deb").val();
   jQuery("#ip_deb").val(old+";"+msg);
}
 var tPackage_id = jQuery.getUrlParam('package_id');
    var tUid = "";
    //全局缓存状态
    var gParticipants = new Array();
    //全局指针
    var source=undefined;
    //是否游戏结束了
    var gGameIsOver=false;
    function doTestUiLog(msg)
    {
        var oldStr=jQuery("#ip_err").val();
        jQuery("#ip_err").val(oldStr+";"+msg);
    }
    function doGetQqi(callback) {
        var get_user_qqi_url = "/game_server/get_user_qqi/";
        doServerGetOperWithJWT_PC(get_user_qqi_url, {}, function (data) {
            try{
                var resCode = data["ok"];
                if (resCode == true) {
                    var userMoney = parseInt(data["balance"]);
                    callback(userMoney);
                }
                else {
                    console.log(data);
                }
            }
            catch(e)
            {
                myClientLog("doGetQqi异常:"+JSON.stringify(e));
            }

        }, function (textStatus) {
            myClientLog(textStatus);
        }, function (error) {
            myClientLog(error);
        });
    }
    function doGet250Status(statecallback) {
        var get_user_qqi_url = mddBll.bll250.kURLStatus_250.format({ "package_id": tPackage_id });
        doServerGetOperWithJWT_PC(get_user_qqi_url, {"csrfmiddlewaretoken":  getCookie('csrftoken')}, function (data) {
            //myUIAlert(JSON.stringify(data));
            try{
                var resCode = data["ok"];
                if (resCode == true) {
                    var tStatusBean = new mddBll.bll250.bll250Status(data);
                    statecallback(tStatusBean);
                }
                else {
                     var tStatusBean = new mddBll.bll250.bll250BigErr(data);
                    statecallback(tStatusBean);
                }
            }catch(e)
            {
                myClientLog("状态获取失败:"+JSON.stringify(e));
                //doMddCloseClient();
            }

        }, function (textStatus) {
            myClientLog(textStatus);
        }, function (error) {
            myUIAlert("url:"+get_user_qqi_url+"err:"+JSON.stringify(error));
        });
    }
    /*
    页面刷新相关
    */
    function doInitIndex() {
        var timeOut = function () {  //超时函数
            $("#lotteryBtn").rotate({
                angle: 0,
                duration: 1000,
                animateTo: 2160, //这里是设置请求超时后返回的角度，所以应该还是回到最原始的位置，2160是因为我要让它转6圈，就是360*6得来的
                callback: function () {
                    alert('网络超时')
                }
            });
        };

        $("#lotteryBtn").rotate({
            bind:
              {
                  click: function () {
                      // var tStarArray = getFiveStarDivRect(225, 509, 50);
                      // for (var i = 0; i < tStarArray.length; i++) {
                      //     //console.log(tStarArray[i]);
                      // };
                      // var data = [1, 2, 3, 4, 5, 0]; //返回的数组
                      // data = GetRandomNum(1, 5);//data[Math.floor(Math.random()*data.length)];
                      // if (data == 1) {
                      //     rotateFunc(1, 0, '恭喜您1号获得250');
                      // }
                      // else if (data == 2) {
                      //     rotateFunc(2, 72, '恭喜您2号获得250');
                      // }
                      // else if (data == 3) {
                      //     rotateFunc(3, 144, '恭喜您3号获得250');
                      // }
                      // else if (data == 4) {
                      //     rotateFunc(3, 216, '恭喜您4号获得250');
                      // }
                      // else if (data == 5) {
                      //     rotateFunc(3, 288, '恭喜您5号获得250');
                      // }
                      // else {
                      //     var angle = [67, 112, 202, 292, 337];
                      //     angle = angle[Math.floor(Math.random() * angle.length)]
                      //     rotateFunc(0, angle, '很遗憾，这次您未抽中奖');
                      // }
                  }
              }

        });
        function doRefreshUi() {
            var padding = 0;
            var screen_with = $(".TopNavLine").width();//$(window).width();
            var screen_height = $(window).height();
            var CenterLenth = screen_with - 2 * padding;
            var baseWidth = 509;
            var baseHeight = 509;
            var baseCenterButonW = 214;
            var baseCenterButonTop = 150;
            var baseCenterButonLeft = 140;
            var baseCenterButonImgLeft = -107;
            $(".topBigDiv").css("width", "100%");
            $(".ly-plate").css("width", CenterLenth + "px");
            $(".ly-plate").css("height", CenterLenth + "px");
            $(".rotate-bg").css("width", CenterLenth + "px");
            $(".rotate-bg").css("height", CenterLenth + "px");
            $(".lottery-star").css("width", (CenterLenth * baseCenterButonW / baseWidth) + "px");
            $(".lottery-star").css("height", (CenterLenth * baseCenterButonW / baseWidth) + "px");
            $(".lottery-star").css("top", (CenterLenth * baseCenterButonTop / baseWidth) + "px");
            $(".lottery-star").css("left", (CenterLenth * baseCenterButonLeft / baseWidth) + "px");
            // $("#lotteryBtn").css("left",(CenterLenth*baseCenterButonImgLeft/baseWidth)+"px");
            doDelDivs();
            doAddDivs();
        }
        var ListenterChange = function () {
            //页面加载先来一下
            doRefreshUi();
            //控制logo的显示位置 Begin

            if (typeof document.addEventListener != "undefined") {
                //document.addEventListener("mousedown", _lhlclick, true);
                window.addEventListener("resize", function () {
                    // 得到屏幕尺寸 (内部/外部宽度，内部/外部高度)
                    doRefreshUi();
                }, false);
            } else {
                //document.attachEvent("onmousedown", _lhlclick);
                window.attachEvent("resize", function () {
                    // 得到屏幕尺寸 (内部/外部宽度，内部/外部高度)
                    doRefreshUi();
                }, false);
            }

        }
        //改变
        ListenterChange();
        doHidenAll();
    }
    function doInitSelectPage() {
        jQuery("#btn_start_pick").attr("disabled","disabled");
        doGetQqi(function (index_balance) {
            $("#lbl_qqzs").html("当前我的亲亲指数：" + index_balance);
            if (index_balance < 50) {
                myUIAlert("账户指数不足50，去打赏亲友的讨红包吧。");
            }else{
                jQuery("#btn_start_pick").removeAttr("disabled");
            }
        });
        //修改链接
        //btn_restart
        var tLink="./start.html";
            $('#btn_restart').attr("href",tLink);
            $("#btn_restart").attr("data-ajax",false);
            $("a").attr('data-ajax',false);
    }
    /*
    状态页面
    */
    //设置启动页面
    function doSetInitPage(pPageId, InitCallBack) {
        //所有page
        var pageArray = getPageArray();
        for (var i = 0; i < pageArray.length; i++) {
            jQuery("div" + pageArray[i]).removeClass("ui-page-active");
        }
        jQuery("div" + pPageId).addClass("ui-page-active");
        // doTestDebUi("doSetInitPage"+pPageId+",step6");
        InitCallBack(pPageId);
    }//end doSetInitPage
    function getPageArray()
    {
        return  ["#pageindex", "#pageSelect"];
    }//end getPageArray
    function getActivetyPage()
    {
        return jQuery("div.ui-page-active").attr("id");
    }//end getActivetyPage
    //刷新界面控件
    function doRefreshUiCom(pObj, pstatus, refreshCallBack,pEnd) {
    // doTestDebUi("doRefreshUiCom:"+JSON.stringify(pObj)+",pstatus:"+pstatus);
        doHidenAll();
        if (pstatus == mddBll.bll250_state.kState_available) {
            jQuery("#btn_join").css("display", "inline");
        } else {
            jQuery("#lbl_msg").css("display", "block");
            jQuery("#btn_restart").css("display", "block");
        }
        if(pEnd==true)
        {
            //不需要刷头像
        }else{
            //头像
            if (pObj != undefined && pObj.participants != undefined) {
                for (var i = 0; i < pObj.participants.length; i++) {
                    var tItem = pObj.participants[i];
                    try {
                        var tImgPath=getCovertImg(tItem.avatar);
                        if(tImgPath!="")
                        {
                            jQuery("#ly-plate-Icon" + tItem.seq).attr("src", tImgPath);
                            jQuery("#ly-plate-Icon" + tItem.seq).css("display", "inline");
                        }else{
                            jQuery("#ly-plate-Icon" + tItem.seq).css("display", "none");
                        }

                    } catch (e) {
                        console.log(e);
                    }
                }
            }
        }

        if (pstatus == mddBll.bll250_state.kState_has_picked) {
            console.log('已经选过数了，等着开奖');
            jQuery("#lbl_msg").css("display", "inline");
            jQuery("#lbl_msg").html("稍等片刻,结果马上揭晓.");
            jQuery("#btn_join").css("display", "none");
            jQuery("#btn_restart").css("display", "none");
            jQuery("#btn_exit").css("display", "none");
        } else if (pstatus == mddBll.bll250_state.kState_has_joined) {
            console.log('已经抢到座了，该选数去了');
            jQuery("#lbl_msg").css("display", "none");
            jQuery("#btn_join").css("display", "none");
            jQuery("#btn_restart").css("display", "none");
            jQuery("#btn_exit").css("display", "none");
            //转到另一个子页面
            doSetInitPage("#pageSelect", function InitCallBack(pPageId) {
                doInitSelectPage();
            });

        } else if (pstatus == mddBll.bll250_state.kState_timeout) {
            console.log('超时');
            jQuery("#lbl_msg").css("display", "inline");
            jQuery("#lbl_msg").html("请求超时,请稍后再试.");
            jQuery("#btn_join").css("display", "none");
            jQuery("#btn_restart").css("display", "block");
            jQuery("#btn_exit").css("display", "block");

        } else if (pstatus == mddBll.bll250_state.kState_not_join) {
            console.log('未加入');
            jQuery("#lbl_msg").css("display", "inline");
            jQuery("#lbl_msg").html("很遗憾,您未参加此次活动.");
            jQuery("#btn_join").css("display", "none");
            jQuery("#btn_restart").css("display", "block");
            jQuery("#btn_exit").css("display", "block");
        } else if (pstatus == mddBll.bll250_state.kState_available) {
            console.log('还有空座，可以去抢');
            jQuery("#lbl_msg").css("display", "none");
            jQuery("#btn_join").css("display", "inline");
            jQuery("#btn_restart").css("display", "none");
            jQuery("#btn_exit").css("display", "none");
        } else if (pstatus == mddBll.bll250_state.kState_fold) {
            console.log('时间到了，没凑够人');
            jQuery("#lbl_msg").css("display", "inline");
            jQuery("#lbl_msg").html("很遗憾,时间到了,人数不够.");
            jQuery("#btn_join").css("display", "none");
            jQuery("#btn_restart").css("display", "block");
            jQuery("#btn_exit").css("display", "block");

        } else if (pstatus == mddBll.bll250_state.kState_got_luck) {
            console.log('中大奖250');
            jQuery("#lbl_msg").css("display", "inline");
            //获取当前用户id
            tUid = getClientUserId();
            var tMsg = getRewardMsg(tUid, pObj.winner);
            jQuery("#lbl_msg").html(tMsg);
            jQuery("#btn_join").css("display", "none");
            jQuery("#btn_restart").css("display", "block");
            jQuery("#btn_exit").css("display", "block");
        } else if (pstatus == mddBll.bll250_state.kState_lose) {
            console.log('没中奖，白花50');
            jQuery("#lbl_msg").css("display", "inline");
            tUid = getClientUserId();
            var tMsg = getRewardMsg(tUid, pObj.winner);
            jQuery("#lbl_msg").html(tMsg);
            // jQuery("#lbl_msg").html("很遗憾，这次您未抽中奖.");
            jQuery("#btn_join").css("display", "none");
            jQuery("#btn_restart").css("display", "block");
            jQuery("#btn_exit").css("display", "block");
        } else if (pstatus == mddBll.bll250_state.kState_is_over) {
            console.log('结束了的（我没参加）');
            jQuery("#lbl_msg").css("display", "inline");
            jQuery("#lbl_msg").html("很遗憾,已结束,您未参加此次活动.");
            jQuery("#btn_join").css("display", "none");
            jQuery("#btn_restart").css("display", "block");
            jQuery("#btn_exit").css("display", "block");
        } else if (pstatus == mddBll.bll250_state.kState_other) {
            console.log('客户端自定义状态');
            jQuery("#lbl_msg").css("display", "none");
            jQuery("#btn_join").css("display", "none");
            jQuery("#btn_restart").css("display", "block");
            jQuery("#btn_exit").css("display", "block");
        }
    }//end doRefreshUiCom
    //隐藏控件
    function doHidenAll() {
        var disArray = ['#btn_join', "#lbl_msg", "#btn_restart",
        '#btn_exit'];
        for (var i = 0; i < disArray.length; i++) {
            $(disArray[i]).css("display", "none");
        }
    }//end doHidenAll
    function GetRandomNum(Min, Max) {
        var Range = Max - Min;
        var Rand = Math.random();
        return (Min + Math.round(Rand * Range));
    }
    //js 点
    function jsPoint(pX, pY) {
        this.pX = pX;
        this.pY = pY;
        return this;
    }
    //js 方形
    function jsRect(pLeftX, pTopY, pW, pH) {
        this.pLeftX = pLeftX;
        this.pTopY = pTopY;
        this.pW = pW;
        this.pH = pH;
        return this;
    }
    //js offset
    function jsOffset(pOffsetX, pOffsetY) {
        this.pOffsetX = pOffsetX;
        this.pOffsetY = pOffsetY;
        return this;
    }
    //获取五角星位置(正方形)(225/509)
    function getFiveStarArray(pRadus, pRangLenght) {
        var radius = pRadus;
        var angle = 4 * Math.PI / 5;
        var centerX = pRangLenght / 2;
        var centerY = pRangLenght / 2;
        var center = new jsPoint(centerX, centerY);
        var arrayM = new Array();
        for (var i = 0; i < 5; i++) {
            // cosf()返回参数的余弦值
            var x = Math.cos(i / 2 * angle - Math.PI) * radius;
            // sinf()返回参数的正弦值
            var y = Math.sin(i / 2 * angle - Math.PI) * radius;
            var point = new jsPoint(x + center.pX, y + center.pY);
            arrayM.push(point);
            //[arrayM addObject:[NSValue valueWithCGPoint:point]];
        }
        return arrayM;
    }
    //根据原点旋转角度获取新的位置(js x，y轴反过来，公式反过来套用)
    function getNewPostion(pXRaw, pYRaw, pAngle, pRx0, pRy0) {
        var rJsPos = new jsPoint(0, 0);
        pAngle = 2 * Math.PI / 360 * pAngle;//用的弧度
        // rJsPos.pX=(pXRaw-pRx0)*Math.cos(pAngle)-(pYRaw-pRy0)*Math.sin(pAngle)+pRx0;
        // rJsPos.pY=(pXRaw-pRx0)*Math.sin(pAngle)-(pYRaw-pRy0)*Math.cos(pAngle)+pRy0;
        rJsPos.pX = (pYRaw - pRy0) * Math.cos(pAngle) - (pXRaw - pRx0) * Math.sin(pAngle) + pRy0;
        rJsPos.pY = (pYRaw - pRy0) * Math.sin(pAngle) - (pXRaw - pRx0) * Math.cos(pAngle) + pRx0;
        //console.log("原始:"+pXRaw+","+pYRaw+",角度:"+pAngle+",原点:"+pRx0+","+pRy0+",转换后"+rJsPos.pX+","+rJsPos.pY);
        return rJsPos;
        /*
    公式
    假设对图片上任意点(x,y)，绕一个坐标点(rx0,ry0)逆时针旋转a角度后的新的坐标设为(x0, y0)，有公式：
        x0= (x - rx0)*cos(a) - (y - ry0)*sin(a) + rx0 ;
        y0= (x - rx0)*sin(a) + (y - ry0)*cos(a) + ry0 ;
        */
    }
    function getNewPostionNomal(pXRaw, pYRaw, pAngle, pRx0, pRy0) {
        var rJsPos = new jsPoint(0, 0);
        pAngle = 2 * Math.PI / 360 * pAngle;//用的弧度
        rJsPos.pX = (pXRaw - pRx0) * Math.cos(pAngle) - (pYRaw - pRy0) * Math.sin(pAngle) + pRx0;
        rJsPos.pY = (pXRaw - pRx0) * Math.sin(pAngle) - (pYRaw - pRy0) * Math.cos(pAngle) + pRy0;
        //console.log("原始:"+pXRaw+","+pYRaw+",角度:"+pAngle+",原点:"+pRx0+","+pRy0+",转换后"+rJsPos.pX+","+rJsPos.pY);
        return rJsPos;
        /*
    公式
    假设对图片上任意点(x,y)，绕一个坐标点(rx0,ry0)逆时针旋转a角度后的新的坐标设为(x0, y0)，有公式：
        x0= (x - rx0)*cos(a) - (y - ry0)*sin(a) + rx0 ;
        y0= (x - rx0)*sin(a) + (y - ry0)*cos(a) + ry0 ;
        */
    }
    //获取div位置
    function getFiveStarDivRect(pRadus, pRangLenght, pRectLength,pOffsetX,pOffsetY) {
        var tStarArray = getFiveStarArray(pRadus, pRangLenght);
        var rStarRectArray = new Array();
        for (var i = 0; i < tStarArray.length; i++) {
            var rect = new jsRect(tStarArray[i].pX - pRectLength / 2+pOffsetX, tStarArray[i].pY - pRectLength / 2+pOffsetY, pRectLength, pRectLength);
            rStarRectArray.push(rect);
            //			console.log(tStarArray[i]);
        };
        return rStarRectArray;
    }
    function copyIndex(Array1,indexOffSet)
    {
        console.log(Array1);
        if(typeof(indexOffSet)==undefined)
        {
            indexOffSet=0;
        }
        var rArr=new Array();
        for (var i = 0; i < Array1.length; i++) {
            var newIndex=(i+indexOffSet)%Array1.length;
            rArr[i]=Array1[newIndex];
        }
        console.log(rArr);
        return rArr;
    }
    function FixImage(pDom)
    {
        jQuery(pDom).css("display","none");
    }
    function doAddDivs() {
        var padding = 8;
        var screen_with = $(".TopNavLine").width();//$(window).width();
        var screen_height = $(window).height();
        var CenterLenth = screen_with - 2 * padding;
        var baseWidth = 509;//
        var baseHeight = 509;
        //直径
        var pRangLenght = 509;//437;//509;
        var tRadus = 222;
        var tIconW = 83;
        pRangLenght = (CenterLenth * pRangLenght / baseWidth);
        tRadus = (CenterLenth * tRadus / baseWidth);
        tIconW = (CenterLenth * tIconW / baseWidth);
        var tOffSetX=4;
        var tOffSetY=8;
        //旋转角度
        var tAngle = 0;
        var tStarArray = copyIndex(getFiveStarDivRect(tRadus, pRangLenght, tIconW,tOffSetX,tOffSetY),1);
        var tStarCenterArray =copyIndex(getFiveStarArray(tRadus, pRangLenght),1);
        var tOffSet = new jsOffset(10, 0);
        var centerX = pRangLenght / 2;
        var centerY = pRangLenght / 2;
        var center = new jsPoint(centerX, centerY);
        //放在正下方
        var tLabelOffSet = new jsOffset(20, 0);
        var totalSize=tStarArray.length;
        for (var i = 0; i < tStarArray.length; i++) {
            var innerIndex=(totalSize-i-1);
            var divItem = tStarArray[i];
            //console.log(divItem.pLeftX + ",:" + i);
            var parentdiv = jQuery('<div></div>');        //创建一个父div
            //parentdiv.attr('id','parent');        //给父div设置id
            jQuery(parentdiv).attr("id", 'ly-plate' + innerIndex);    //添加css样
            jQuery(parentdiv).attr("class", 'ly-plate-Img dyappend');    //添加css样式
            jQuery(parentdiv).css("width", divItem.pW);
            jQuery(parentdiv).css("height", divItem.pH);
            jQuery(parentdiv).css("top", divItem.pLeftX + tOffSet.pOffsetX);
            jQuery(parentdiv).css("left", divItem.pTopY + tOffSet.pOffsetY);
            jQuery(parentdiv).css("position", "absolute");
            //圆形头像
            jQuery(parentdiv).css("position", "absolute");
            var dymImage = jQuery('<img />');
            jQuery(parentdiv).append(dymImage);
            jQuery(dymImage).attr("id", 'ly-plate-Icon' + innerIndex);    //添加css样
            jQuery(dymImage).css("width", "80%");
            jQuery(dymImage).css("height", "80%");
            jQuery(dymImage).css("vertical-align","middle");
            jQuery(dymImage).css("text-align","center");
            jQuery(dymImage).css("border-radius", "50%");
            jQuery(dymImage).attr("src", '');//默认为空
            jQuery(dymImage).attr("onerror","javascript:FixImage(this);");
            jQuery(dymImage).css("display", 'none');
            //文字
            var dymLabel = jQuery('<Label></Label>');
            //先放在正下方
            jQuery(dymLabel).attr("id", 'ly-plate-Label' + (innerIndex+1)%totalSize);    //添加css样
            jQuery(dymLabel).attr("class", 'ly-plate-Label');    //添加css样式
            // jQuery(dymLabel).css("width",divItem.pW);
            // jQuery(dymLabel).css("height",divItem.pH);
            //获取旧的位置
            var startCenter = tStarCenterArray[i];
            //console.log("startCenter:" + startCenter + ",divItem:" + divItem);
            //js x，y好像相反
            var newPos = getNewPostion(startCenter.pX, startCenter.pY, tAngle, center.pX, center.pY);
            jQuery(dymLabel).css("top", newPos.pX);
            jQuery(dymLabel).css("left", newPos.pY);
            jQuery(dymLabel).css("position", "absolute");
            jQuery(dymLabel).css("color", "#000000");
            jQuery(dymLabel).css("font-size", "36px");
            jQuery(dymLabel).css("z-index", "100");
            // jQuery(dymLabel).html(i+1);//文字1-5
            jQuery(dymLabel).html();
            //放在大的
            jQuery('#star_bg').append(dymLabel);
            jQuery('#star_bg').append(parentdiv);            //将父div添加到body中

        }
    }//end doAddDivs
    //删除元素
    function doDelDivs() {
        jQuery(".dyappend").remove();
        jQuery(".ly-plate-Label").remove();
    }//end doDelDivs
    //重来
    function doRestartGame() {
        //特殊情况
        window.location.href = "./start.html";
        // doTestUILoger("doRestartGame,step7");
        // //调试信息
        // var deb = jQuery.getUrlParam("mydebug");
        // if (deb=="1") {
        //     var tAuto = jQuery.getUrlParam("Authorization");
        //     if (tAuto != "") {
        //         var tLink = jQuery.changeURLPar("./start.html?Authorization=" + tAuto);
        //         window.location.href = tLink;//"start.html";
        //     } else {
        //         window.location.href = "./start.html";
        //     }
        // }else{
        //     //特殊情况
        //      window.location.href = "./start.html";
        // }

    }//end doRestart
    //抢250
    function doJoin250() {
        var tUrl = mddBll.bll250.kURLJoin_250.format({ "package_id": tPackage_id });
        doServerOperWithJWT_PC(tUrl, { "csrfmiddlewaretoken": getCookie('csrftoken') }, function (data) {
            var resCode = data["ok"];
            try{
                if (resCode == true) {
                        var tStatusBean = new mddBll.bll250.bll250BigSuc(data);
                        //转到另一个子页面
                        doSetInitPage("#pageSelect", function InitCallBack(pPageId) {
                            doInitSelectPage();
                        });
                        //关闭客户端
                        //doMddCloseClient();
                    }
                    else {
                        var tStatusBean = new mddBll.bll250.bll250BigErr(data);
                        if(tStatusBean.error==mddBll.bll250_state.kState_has_joined)
                        {
                            //加过去选吧
                            doSetInitPage("#pageSelect", function InitCallBack(pPageId) {
                                doInitSelectPage();
                            });
                        }else{
                            myUIAlert("加入失败!");
                        }
                    }
            }catch(e){
                myClientLog("doJoin250请求异常:"+JSON.stringify(e));
            }

        }, function (textStatus) {
            myClientLog(textStatus);
        }, function (error) {
            myClientLog(error);
        });
    }//end doJoin250
    //根据编号找到用户
    function doFindObjByUid(pUid) {
        var rPartItem = new Object();
        if (pUid != undefined && pUid != "") {
            for (var i = 0; i < gParticipants.length; i++) {
                var tPartItem = gParticipants[i];
                if (tPartItem.uid == pUid) {
                    rPartItem = tPartItem;
                    break;
                }
            }
        } else {
            //没有找到
        }
        return rPartItem;
    }//end doFindObjByUid
    //获取提示文字
    function getRewardMsg(pUid, pWinnerId) {
        doTestUILoger("getRewardMsg>>pUid:"+pUid+"pWinnerId:"+pWinnerId);
        var rMsg = "";
        if (pUid != undefined) {
            if (pUid == pWinnerId) {
                rMsg = "恭喜你,获得了250指数!";
            } else {
                var tParticipant = doFindObjByUid(pWinnerId);
                if (tParticipant.user_name != "") {
                    rMsg = "恭喜{user_name},获得了250指数".format({ "user_name": tParticipant.user_name });
                } else {
                    //用户名是空的
                    rMsg = "恭喜{user_name},获得了250指数".format({ "user_name": tParticipant.user_name });
                }
            }
        }
        return rMsg;
    }//end getRewardMsg
    //开奖
    function doReward(pWinnerId, pObj, pstatus) {
        //找到编号
        var tParticipant = doFindObjByUid(pWinnerId);
        var resSeq = -1;
        var needPic=false;
        // myUIAlert("pWinnerId:"+pWinnerId+",pObj:"+JSON.stringify(pObj));
        if(pObj!=undefined&&pObj.participants!=undefined)
        {
            var toltalSetp=0;
            //获取step
            for(var i=0;i<pObj.participants.length;i++)
            {
                var tParticipantItem=pObj.participants[i];
                 jQuery("#ly-plate-Label"+i).html(tParticipantItem.step);
                // jQuery("#ly-plate-Label"+tParticipantItem.seq).html("seq:"+tParticipantItem.seq+","+tParticipantItem.user_name+","+tParticipantItem.step);
                toltalSetp+=tParticipantItem.step;
            }
            resSeq=toltalSetp;
            //最后一张
           if(jQuery("#ly-plate-Icon4").attr("src")=="")
           {
                //needPic=true;
           }
        }
        //旋转
        jQuery("#top_lbl").html("指针共转动{resSeq}下".format({"resSeq":resSeq}));
        //找到数字了,转一下
        if (resSeq != -1) {
            rotateFunc(resSeq, resSeq * 72, '', function rotateCallBack(text) {
                doRefreshUiCom(pObj, pstatus, function refreshCallBack() {
                    console.log('界面刷新结束..');
                },needPic);
            });
        } else {
            console.log('无效序列');
        }
        doCloseEventSource();
    }//doReward
    function rotateFunc(awards, angle, text, rotateCallBack) {  //awards:奖项，angle:奖项对应的角度
        $('#lotteryBtn').stopRotate();
        $("#lotteryBtn").rotate({
            angle: 0,
            duration: 5000,
            animateTo: angle + 1440, //angle是图片上各奖项对应的角度，1440是我要让指针旋转4圈。所以最后的结束的角度就是这样子^^
            callback: function () {
                console.log("awards:"+awards+",angle:"+angle+",text:"+text);
                if (rotateCallBack != undefined) {
                    rotateCallBack(text);
                }
            }
        });
    }//end rotateFunc
    //测试状态位
    function doTestState() {
        //var tJson = eval("(" + "{\"status\":\"got_luck\",\"participants\":[{\"user_name\":\"肖光\",\"uid\":\"77781\",\"seq\":0,\"avatar\":\"/img/male.png\"}],\"life_time\":0,\"winner\":\"77781\",\"ok\":true,\"package\":{\"remains\":4,\"create_at\":\"2016-11-07 01:29:34\",\"id\":2,\"owner_id\":\"77781\"}}" + ")");
        var tJson1={"ok":true,"status":"lose","life_time":160,"winner":"78456",'winner_position': 0,"package":{"id":137,"owner_id":"78478","remains":0,"create_at":"2016-11-09 10:41:52"},"participants":[{"uid":"78478","user_name":"侯洪兴","avatar":"test.engdd.com/img/male.png","seq":0,"step":4},{"uid":"413","user_name":"韩连宝","avatar":"/img/10e315f5-0f76-4db0-850d-957c524aed27.jpeg","seq":1,"step":3},{"uid":"78480","user_name":"高彪夫","avatar":"test.engdd.com/img/male.png","seq":2,"step":3},{"uid":"78468","user_name":"石海","avatar":"test.engdd.com/img/male.png","seq":3,"step":3},{"uid":"78456","user_name":"鲁荣庆","avatar":"test.engdd.com/img/male.png","seq":4,"step":3}]};
        var tStatusBean = new mddBll.bll250.bll250Status(tJson1);
        if (tStatusBean.participants != undefined) {
            //缓存
            gParticipants = tStatusBean.participants;
        }
        if (tStatusBean.ok == true) {
            if (tStatusBean.status == mddBll.bll250_state.kState_got_luck || tStatusBean.status == mddBll.bll250_state.kState_lose || tStatusBean.status == mddBll.bll250_state.kState_is_over) {
                doReward(tStatusBean.winner, tStatusBean, tStatusBean.status);
            } else {
                doRefreshUiCom(tStatusBean, tStatusBean.status, function refreshCallBack() {
                },false);
            }
        } else {
            var tStatusBean = new mddBll.bll250_state();
            doRefreshUiCom(tStatusBean, mddBll.bll250_state.kState_other, function refreshCallBack() {
            },false);
        }
    }//end doTestState
    /*选择模块 用户位置*/
    var userPlace = 0;
    function create(callback) {
        var create_package_url = "/game_server/index_250/create_package/";
        doServerGetOperWithJWT_PC(create_package_url, {}, function (data) {
            var resCode = data["ok"];
            if (resCode == true) {
                callback();
            }
            else {
                console.log(data);
            }
        }, function (textStatus) {
            //myClientLog(textStatus);
        }, function (error) {
            //myClientLog(error);
        });

    }//end create
    function doJumpToStart() {
        if(userPlace==0)
        {
            myUIAlert("自动随机选择数字!");
            randValue(function callback(){
                        jQuery("#btn_start_pick").attr("disabled","disabled");
                    try{
                        doPick250(function statecallback(pStatusBean) {
                        if (pStatusBean.ok == true) {
                            myUIAlert("选择成功!");
                            doJumpToStatus();
                        } else {
                            if (pStatusBean.error == mddBll.bll250_state.kState_has_picked) {
                                myUIAlert("已经选过数了，等着开奖");
                                doJumpToStatus();
                            } else if (pStatusBean.error == mddBll.bll250_state.kState_timeout) {
                                myUIAlert("超时,已经选过数了");
                                doJumpToStatus();
                            } else if (pStatusBean.error == mddBll.bll250_state.kState_not_join) {
                                myUIAlert("未加入");
                                doMddCloseClient();
                            } else {
                                myUIAlert("未知情况");
                                doMddCloseClient();
                            }
                        }
                        });
                    }catch(e)
                    {
                        myClientLog("选择错误:"+JSON.stringify(e));
                    }
            });
        }else{
            jQuery("#btn_start_pick").attr("disabled","disabled");
            try{
                doPick250(function statecallback(pStatusBean) {
                doTestUILogerObj(pStatusBean,"step8");
                if (pStatusBean.ok == true) {
                    myUIAlert("选择成功!");
                    doJumpToStatus();
                } else {
                    if (pStatusBean.error == mddBll.bll250_state.kState_has_picked) {
                        myUIAlert("已经选过数了，等着开奖");
                        doJumpToStatus();
                    } else if (pStatusBean.error == mddBll.bll250_state.kState_timeout) {
                        myUIAlert("超时,已经选过数了");
                        doJumpToStatus();
                    } else if (pStatusBean.error == mddBll.bll250_state.kState_not_join) {
                        myUIAlert("未加入");
                        doMddCloseClient();
                    } else {
                        myUIAlert("未知情况");
                        doMddCloseClient();
                    }
                }
                });
            }catch(e)
            {
                myClientLog("选择错误:"+JSON.stringify(e));
            }
        }


    }//end doJumpToStart
    function doJumpToStatus() {
        doSetInitPage("#pageindex", function InitCallBack(pPageId) {
            //页面
            doInitIndex();
            ////获取状态
            //加载推送
            initEventSource("", function afterCallBack(pState, pData) {

                            if (pState == 'delta') {
                                //刷新状态
                                doReciverPushState(pData, function refreshCallBack() {

                                });
                            }
            });
        //     doGet250Status(function statecallback(tStatusBean) {
        //     if (tStatusBean.participants != undefined) {
        //         //缓存
        //         gParticipants = tStatusBean.participants;
        //     }
        //     if (tStatusBean.ok == true) {
        //         if (tStatusBean.status == mddBll.bll250_state.kState_got_luck || tStatusBean.status == mddBll.bll250_state.kState_lose || tStatusBean.status == mddBll.bll250_state.kState_is_over) {
        //             doReward(tStatusBean.winner, tStatusBean, tStatusBean.status);
        //         } else {
        //             doCountDown(tStatusBean.life_time);
        //             doRefreshUiCom(tStatusBean, tStatusBean.status, function refreshCallBack() {
        //             });
        //             //加载推送
        //             initEventSource("", function afterCallBack(pState, pData) {
        //                 if (pState == 'delta') {
        //                     //刷新状态
        //                     doReciverPushState(pData, function refreshCallBack() {

        //                     });
        //                 }
        //             });
        //         }
        //     } else {
        //         var tStatusBean = new mddBll.bll250_state();
        //         doRefreshUiCom(tStatusBean, mddBll.bll250_state.kState_other, function refreshCallBack() {
        //         });
        //     }
        // });
        });
        //var tLink="./index.html?package_id="+tPackage_id;
        //window.location.href=tLink;
    }//end doJumpToStatus

    function doRadio(count) {
        var mCount = count * -1;
        jQuery("#lbl_zdmenoy").html(mCount);
    }//end doRadio
    function doSelectPosRand(pDom) {
        var maxlength = 5;
        userPlace = Math.floor(Math.random() * maxlength+1);
        if(userPlace>5)
            userPlace=5;
        //alert(userPlace);
        doChangeStyle(pDom);
    }//end doSelectPosRand
    function doSelectPos(pDom) {
        userPlace = jQuery(pDom).text();
        //alert(userPlace);
        doChangeStyle(pDom);
    }//end doSelectPos
    function randValue(callback)
    {
        var maxlength = 5;
        userPlace = Math.floor(Math.random() * maxlength+1);
        if(userPlace>5)
            userPlace=5;
        var tSelectObj=undefined;
        jQuery("a.SixButtonNum").each(function(){
           if($(this).html()==(userPlace+""))
           {
                tSelectObj=$(this);
           }
        });
        if(typeof(tSelectObj)!="undefined")
        {
            tSelectObj.click();
        }
        callback();
    }//end randValue
    function doChangeStyle(pDom) {
        //SixButtonRandA
        var parDiv = jQuery(pDom).parent();
        //清空
        jQuery(".SixButtonRandA").removeClass("SixButtonRandA");
        parDiv.addClass("SixButtonRandA");
        jQuery("#btn_start_pick").removeAttr("disabled");
    }//end doChangeStyle
    //选取250
    function doPick250(statecallback) {
        var tUrl = mddBll.bll250.kURLPick_250.format({ "package_id": tPackage_id });
        doServerOperWithJWT_PC(tUrl, { "step": userPlace, "csrfmiddlewaretoken": getCookie('csrftoken') }, function (data) {
            try{
                    if (data != undefined) {
                    var resCode = data["ok"];
                    if (resCode == true) {
                        var tStatusBean = new mddBll.bll250.bll250BigSuc(data);
                        statecallback(tStatusBean);
                    }
                    else {
                        var tStatusBean = new mddBll.bll250.bll250BigErr(data);
                        statecallback(tStatusBean);
                    }
                }else{
                    myUIAlert("选择失败");
                }
            }catch(e)
            {
                myClientLog("doPick250请求异常:"+JSON.stringify(e));
            }

        }, function (textStatus) {
            myClientLog(textStatus);
        }, function (error) {
            myClientLog(error);
        });
    }//end doPick250
//     //轮询
//     var source = (function(){
//     //单例模式
//     var unique;
//     function getInstance(){
//         if( unique === undefined ){
//             unique = new Construct();
//         }
//         return unique;
//     }
//     function Construct(){

//         // ... 生成单例的构造函数的代码
//         source = new EventSource("/game_server_sse/Index_250_package_{package_id}/".format({ "package_id": tPackage_id }));

//     }
//     return {

//         getInstance : getInstance

//     }

// })();
// var hasSource=false;
    //推送
    function initEventSource(conf, afterCallBack) {
        //游戏进行中
        if(!gGameIsOver)
        {
            if(typeof(source)!="undefined")
            {
                //第一次
                if(source.readyState==source.CLOSED)
                {
                    source = new EventSource("/game_server_sse/Index_250_package_{package_id}/".format({ "package_id": tPackage_id }));
                }
            }else{
                //后面的
                source = new EventSource("/game_server_sse/Index_250_package_{package_id}/".format({ "package_id": tPackage_id }));
            }
            //在判断
            if(typeof(source)=="undefined")
            {
                //后面的
                source = new EventSource("/game_server_sse/Index_250_package_{package_id}/".format({ "package_id": tPackage_id }));
            }
            source.addEventListener('init', function (e) {
            console.log("初始化:" + e);
            //afterCallBack("init",e.data);
            //app.trigger("model:init", e.data);
        }, false);
        source.addEventListener('end', function (e) {
            console.log("结束:" + e);
            source.close();
            //clear
            source = null;
            gGameIsOver=true;
            //afterCallBack("init",e.data);
            //app.trigger("model:init", e.data);
        }, false);
        source.addEventListener('delta', function (e) {
            doTestUILogerObj(e,"step5");
            console.log("delta" + e.data);
            afterCallBack("delta", e.data);
            //app.trigger("view:update", e.data);
        }, false);

        source.addEventListener('error', function (e) {
            if (e.readyState == EventSource.CLOSED) {
                console.log("close" + e);
                afterCallBack("close", e.data);
                // app.trigger("view:networkError");
            }
            else if (e.readyState == EventSource.OPEN) {
                console.log("open" + e);
                afterCallBack("open", e.data);
                // app.trigger("feedback:connecting");
            }
        }, false);
        }

    }//end initEventSource
    function doCloseEventSource()
    {
        if(typeof(source)!="undefined")
        {
            source.close();
            source=null;
        }
            // hasSource=true;
        // }
        //clear
        //source = null;
    }//end doCloseEventSource
    //半路隐藏
    function doReciverPushState(pObj, refreshCallBack) {
        //兼容处理
        if(isString(pObj))
        {
            pObj=eval("("+pObj+")");
        }
        //头像
        if (pObj != undefined && pObj.participants != undefined) {
            // myUIAlert("doReciverPushState:pObj:"+JSON.stringify(pObj));
            for (var i = 0; i < pObj.participants.length; i++) {
                var tItem = pObj.participants[i];
                try {
                    var tImagPath=getCovertImg(tItem.avatar);
                    if(tImagPath!="")
                    {
                        jQuery("#ly-plate-Icon" + tItem.seq).attr("src",tImagPath);
                        jQuery("#ly-plate-Icon" + tItem.seq).css("display","inline");
                    }else{
                        jQuery("#ly-plate-Icon" + tItem.seq).css("display","none");
                    }
                } catch (e) {
                    console.log(e);
                }
            }
        }
        refreshCallBack();
    }//end doReciverPushState
     var mdd_gb_jg = 1;//5秒来一次(默认最小值)
        var timer;//定时器
        var life_time;
        var timer_Flag=true;
        //倒计时
        function doCountDown(pMax) {
        	console.log('计时开始'+pMax);
                //兼容判断
                if(pMax<=0)
                {
                    pMax=0;
                }
                life_time = pMax;
                //单例
                if(timer_Flag)
                {
                    doMddTimeLoad();
                    timer_Flag=false;
                }


        }//end doCountDown
        function doMddTimeLoad() {
            //alert(cnt);
            if (life_time > 0) {
                life_time--;
                //every five seconds to repeat self
                timer = setTimeout("doMddTimeLoad()", 1000 * mdd_gb_jg);
                //timer
                jQuery("#lbl_countdown").html("{resttime}\"".format({"resttime":life_time}));
                //5秒轮询(调试30秒轮询)
                if(life_time%20==0)
                {
                  console.log("timer_Flag:"+timer_Flag+",life_time:"+life_time);
                 //获取状态
            doGet250Status(function statecallback(tStatusBean){
					if (tStatusBean.participants != undefined) {
	                //缓存
	                gParticipants = tStatusBean.participants;
	            	}
	            if (tStatusBean.ok == true) {
	                if (tStatusBean.status == mddBll.bll250_state.kState_got_luck || tStatusBean.status == mddBll.bll250_state.kState_lose || tStatusBean.status == mddBll.bll250_state.kState_is_over) {
	                    doReward(tStatusBean.winner, tStatusBean, tStatusBean.status);
	                } else {
	                    doRefreshUiCom(tStatusBean, tStatusBean.status, function refreshCallBack() {
	                    },false);
	                    //加载推送
	                    initEventSource("", function afterCallBack(pState, pData) {

                            if (pState == 'delta') {
	                            //刷新状态
	                            doReciverPushState(pData, function refreshCallBack() {

	                            });
	                        }
	                    });
	                }
	                //生存周期
	                if(tStatusBean.life_time!=undefined)
                        {
                         life_time = tStatusBean.life_time;
                        }
                        if(tStatusBean.package.remains==0)
                        {
                            life_time=0;
                            window.clearTimeout(timer);
                            //修改特效
                            //抢到钱
                            // doSpecail(-100);
                            doTimeFinish();
                            doCloseEventSource();
                        }
	            } else {
	                var tStatusBean = new mddBll.bll250_state();
	                doRefreshUiCom(tStatusBean, mddBll.bll250_state.kState_other, function refreshCallBack() {
	                },false);
	            }
            });

                }
                //留一个就好了
                //doCountDownUI(mdd_gb_cnt);
            } else {
                window.clearTimeout(timer);
                //修改特效
                //抢到钱
                // doSpecail(-100);
                doTimeFinish();
            }
        }//end doMddTimeLoad
        //结束执行事件
        function doTimeFinish()
        {
            gGameIsOver=true;
            //获取状态
            doGet250Status(function statecallback(tStatusBean){
					if (tStatusBean.participants != undefined) {
	                //缓存
	                gParticipants = tStatusBean.participants;
	            }
	            if (tStatusBean.ok == true) {
	                if (tStatusBean.status == mddBll.bll250_state.kState_got_luck || tStatusBean.status == mddBll.bll250_state.kState_lose || tStatusBean.status == mddBll.bll250_state.kState_is_over) {
	                    doReward(tStatusBean.winner, tStatusBean, tStatusBean.status);
	                } else {
	                    doRefreshUiCom(tStatusBean, tStatusBean.status, function refreshCallBack() {
	                    },false);
	                    //加载推送
	                    initEventSource("", function afterCallBack(pState, pData) {
	                        if (pState == 'delta') {
	                            //刷新状态
	                            doReciverPushState(pData, function refreshCallBack() {

	                            });
	                        }
	                    });
	                }
	            } else {
	                var tStatusBean = new mddBll.bll250_state();
	                doRefreshUiCom(tStatusBean, mddBll.bll250_state.kState_other, function refreshCallBack() {
	                },false);
	            }
            });
        }//end doTimeFinish
    //主函数
    $(document).bind("mobileinit", function () {
        $.extend($.mobile, {
            ajaxEnabled: false,
            activeBtnClass: "new-ui-btn-active"
        });
    });
    $(document).ready(function () {
        // doTestDebUi("ready index");
        //获取当前用户id
        tUid = getClientUserId();
        //第一次加载
        gGameIsOver=false;
        //重新获取package id
        tPackage_id = jQuery.getUrlParam('package_id');
        var initpageURL= jQuery.getUrlParam('initpage');
        var startPage="#pageindex";
        if(initpageURL!=undefined)
        {
            startPage=initpageURL;
        }
        doSetInitPage(startPage, function InitCallBack(pPageId) {
            //开始页面
            if (pPageId == "#pageindex") {
                doInitIndex();
            }
                //选择页面
            else if (pPageId == "#pageSelect") {
                doInitSelectPage();
            }
        });

        ////获取状态
        doGet250Status(function statecallback(tStatusBean) {
            if (tStatusBean.participants != undefined) {
                //缓存
                gParticipants = tStatusBean.participants;
            }
            if (tStatusBean.ok == true) {
                if (tStatusBean.status == mddBll.bll250_state.kState_got_luck || tStatusBean.status == mddBll.bll250_state.kState_lose || tStatusBean.status == mddBll.bll250_state.kState_is_over) {
                    //出结果了
                    gGameIsOver=true;
                    doReward(tStatusBean.winner, tStatusBean, tStatusBean.status);
                } else {
                    //如果在选择页面
                    var tActityPage=getActivetyPage();
                    //在选数字
                    if("#pageSelect"==tActityPage)
                    {

                    }
                	doCountDown(tStatusBean.life_time);
                    doRefreshUiCom(tStatusBean, tStatusBean.status, function refreshCallBack() {
                    },false);
                    //加载推送
                    initEventSource("", function afterCallBack(pState, pData) {
                        if (pState == 'delta') {
                            //刷新状态
                            doReciverPushState(pData, function refreshCallBack() {

                            });
                        }
                    });
                }
            } else {
                var tStatusBean = new mddBll.bll250_state();
                doRefreshUiCom(tStatusBean, mddBll.bll250_state.kState_other, function refreshCallBack() {
                },false);
            }
        });

        // doTestState();
    });
/*
,pstatus:lose
*/
