$(function(){
    "use strict";
    var firstPage = $("#first");         // 第一张页面
    var secondPage = $("#second");       // 第二张页面

    /* 选择胜平负事件 */
    $(".btn.btn-radius-h").on("click", toggleRatioSeletect);

    /* 确定所选择 */
    // $("#showSelected").on("click", showSelectedDialog);
    $("#showSelected").on("click", function(){
        $.AuthDialog().show().afterLogin(function(result){
            console.log(result);
            // 登录成功可以关闭
            $.AuthDialog().hide();
        });
    });

    /* 清空用户所选 */
    $("#clearAll").on("click", clearAll);

    function toggleRatioSeletect(e){
        var btn = $(e.target);
        btn.toggleClass("red bg");
        btn.toggleClass("gray");

        // 检查选择场数
        var rows = $("#first .group.center");
        var size = 0;
        rows.each(function(){
            var selected = $(this).children(".btn.red.bg");
            if(0 < selected.size()){
                ++size;
            }
        });

        $("#amountSelected").html(size);
    }

    function showSelectedDialog(){
        var swap = [];                  // 第一页收集数据
        swap.teams = [];
        swap.rate1 = 1;
        swap.rate2 = 2;
        swap.result = 2;

        var rows = $("#first .group.center");
        rows.each(function(index){
            var children = $(this).children(".btn.btn-radius-h");
            var team = {};
            team.name = $(this).data("name");
            team.ctype = [];
            team.rate = [];
            team.title = $(this).siblings(".center.namevs").html();
            if(children.hasClass("red bg")){
                var el = $(children.get(0));
                if(el.hasClass("red bg")){
                    team.ctype.push(3);
                    team.rate.push(el.data("rate"));
                }
                el = $(children.get(1));
                if(el.hasClass("red bg")){
                    team.ctype.push(1);
                    team.rate.push(el.data("rate"));
                }
                el = $(children.get(2));
                if(el.hasClass("red bg")){
                    team.ctype.push(0);
                    team.rate.push(el.data("rate"));
                }
                swap.teams.push(team);
            }
        });
        // 第一页数据收集完毕，用于初始第二张页面。
        console.log(swap);
        // 一共选择的场数
        if(1 > swap.teams.length){
            alert("您未选满1场，请继续选择比赛");
            return false;
        }

        setDialog(swap);
        return true;
    }

    // 第二个页面
    function setDialog(swap){
        firstPage.hide();
        secondPage.show();

        var teams = swap.teams;
        var length = teams.length;
        var html = "";
        var container = $("#flat-list");
        for(var i = 0; i < length; ++i){
            var team = teams[i];
            var ctype = team.ctype;
            var index1 = ctype.indexOf(3);
            var index2 = ctype.indexOf(1);
            var index3 = ctype.indexOf(0);
            html += "" +
                "<div class='radius large'>" +
                    "<div class='rows noborder'>" +
                        "<div class='col grid2 noborder center'>" +
                            "<span class='fa-stack fa-lg red ball_remove'>" +
                                "<i class='fa fa-circle fa-stack-2x'></i>" +
                                "<i class='fa fa-fw fa-minus fa-stack-1x fa-inverse'></i>" +
                            "</span>" +
                        "</div>" +
                        "<div class='col grid10 noborder'>" +
                            "<div class='center'>" +
                                team.title +
                            "</div>" +
                            "<div class='group center my_selected' data-name='" + team.name + "'>" +
                                "<button class='btn btn-radius-h " + (-1 !== index1 ? " red bg " : " gray ") + "'" + 
                                    " data-rate='" + team.rate[index1] + "'" +
                                ">胜</button>" +
                                "<button class='btn btn-radius-h " + (-1 !== index2 ? " red bg " : " gray ") + "'" + 
                                    " data-rate='" + team.rate[index2] + "'" +
                                ">平</button>" +
                                "<button class='btn btn-radius-h " + (-1 !== index3 ? " red bg " : " gray ") + "'" +
                                    " data-rate='" + team.rate[index3] + "'" +
                                ">负</button>" +
                                "<button class='btn btn-radius-h gray bg'>胆</button>" +
                            "</div>" +
                        "</div>" +
                    "</div>" +
                "</div>";
        }
        html += "" +
            "<div class='large filled text-right'>" +
            "<span class='fa-stack fa-lg gray' id='clearQuene'>" +
            "<i class='fa fa-circle fa-stack-2x'></i>" +
            "<i class='fa fa-fw fa-trash-o fa-stack-1x fa-inverse'></i>" +
            "</span>" +
            "</div>";
        container.html(html);

        addEvents();
        buyAll();
    }

    function addEvents(){
        /* 返回继续选择比赛 */
        $("#back").on("click", getBack);

        /* 删除已选择比赛 */
        $(".ball_remove").on("click", removeCurRow);

        /* 提交购买 */
        $("#buy").on("click", sub);

        /* 用户倍数时时更新 */
        $("#bets").on("keyup", function(){
            buyAll();
        });

        /* 清空列表 */
        $("#clearQuene").on("click", clearQuene);

        /* 返回第一页 */
        $("#returnBack").on("click", getBack);
    }

    function removeEvents(){
        $("#back").off("click");
        $(".ball_remove").off("click");
        $("#buy").off("click");
        $("#bets").off("change");
        $("#clearQuene").off("click");
    }

    function getBack(){
        secondPage.hide();
        firstPage.show();

        removeEvents();
    }

    function removeCurRow(e){
        var rows = $("#flat-list .radius.large");
        if(1 >= rows.size()){
            alert("请至少保持1场，不能再少了");
            return ;
        }
        var i = $(e.target);
        var row = i.parent().parent().parent().parent();

        row.remove();
        $("#bets").val("");
        buyAll();
    }
    function clearQuene(){ getBack();
        clearAll();
    }

    function clearAll(){
        var rows = $("#first .group.center");
        rows.each(function(){
            var btns = $(this).children(".btn.btn-radius-h");
            btns.each(function(){
                btns.removeClass("red bg gray");
                btns.addClass("gray");
            });
        });
        $("#amountSelected").html(0);
    }

    function buyAll(){
        var rows = $("#second .my_selected");
        var data = {};          // 最后提交的数据保存在这里
        data.teams = [];
        data.rate1 = 1;
        data.rate2 = 0;
        data.result = 0;
        var total = 0;          // 一共选择的场数
        rows.each(function(){
            var children = $(this).children(".btn.btn-radius-h");
            var name = $(this).data("name");
            if(children.hasClass("red bg")){
                var el = $(children.get(0));

                if(el.hasClass("red bg")){
                    ++total;
                    data.teams.push({
                        ctype: 3,
                        rate: el.data("rate"),
                        name: name
                    });
                }
                el = $(children.get(1));
                if(el.hasClass("red bg")){
                    ++total;
                    data.teams.push({
                        ctype: 1,
                        rate: el.data("rate"),
                        name: name
                    });
                }
                el = $(children.get(2));
                if(el.hasClass("red bg")){
                    ++total;
                    data.teams.push({
                        ctype: 0,
                        rate: el.data("rate"),
                        name: name
                    });
                }
            }
        });

        var bet = $("#bets").val();
        data.rate2 = parseInt(bet) || 1;
        data.result = 2 * data.rate1 * parseFloat(data.rate2) * total;

        var rows = $("#second .my_selected");

        /* 在界面上将用户数据显示出来 */
        $("#userBets").html(data.rate2);
        $("#userTotal").html(total);
        $("#userRounds").html(rows.size());
        $("#userResult").html(data.result);

        /* 数据收集完毕 */
        return data;
    }

    /** 这里才是真正的提交事件 */
    function sub(){
        var data = buyAll();
        console.log(data);
        $.ajax({

            type: "POST",

            url: "jcsfc.htm",

            data: {jsonar:$.toJSON(data)},

            dataType: "json",

            success: function(data){
            			
            			if(data){
            				openDialog("#dialog");
            			}else{
            				openDialog("#dialog2");
            			}
                     }

        });
    }
});

