var userid = parseInt($('#userid').val());
var login_token = $('#login_token').val();
var table_id = parseInt($('#table_id').val());
var game_id = parseInt($('#game_id').val());
var account = $('#account').val();
var number_tab_id;
var ludan;
var isCBoot = false;
var isopentime = false;
var num = 0;
var card_info=[];
var isWin={
    win_player_1:null,
    win_player_2:null,
    win_player_3:null,
    text:[]
};

// 识别相关
var position = ['11', '12', '21', '22', '13', '23'];
var stopScan = false;
var scanTask = null;
var scanPosition = 1;
if (game_id == 4) {
    scanPosition = 21; // 定位牌
}

// NN识别相关
var scanDefaultPosition = 'P1'; // 默认定位区
var positionScanTask = null;
var isPositionScaned = false;
var positionCard = 0;
var isCardScaned = false;
var currentPositionToChange = -1;

// 百家乐修改相关
var manualStopAi = false;


var initScanParams = function() {
    clearInterval(scanTask);
    scanTask = null;
    stopScan = false;
    scanPosition = 1;
    if (game_id == 4) {
        scanPosition = 21;
    }
    scanDefaultPosition = 'P1';
    clearInterval(positionScanTask);
    positionScanTask = null;

    isPositionScaned = false;
    positionCard = 0;
    isCardScaned = false;
    currentPositionToChange = -1;

    manualStopAi = false;

    $(".countdown").css({"opacity":0,"display":"none"});
    $(".countdown .grab-count").removeClass("count-active");
}
// 百家乐修改牌
var openAllCardsPanel = function(dom) {
    var positionOfCard = parseInt($(dom).attr('data-position'));

    if (positionOfCard > 0) {
        if (manualStopAi) {
            // 11, 12, 21, 22, 13, 23
            currentPositionToChange = positionOfCard;
            if (currentPositionToChange == 23) {   // 庄补
                $('#change_cards').show();
            } else if (currentPositionToChange == 13) { // 第一张补牌
                if (card_info['banker_3'] == undefined || card_info['banker_3'] == '') {
                    $('#change_cards').show();
                } else {
                    layer.msg('庄已补，不能修改。');
                }
            } else { // 庄闲位置
                if ((card_info['player_3'] == undefined || card_info['player_3'] == '') && (card_info['banker_3'] == undefined || card_info['banker_3'] == '')) {
                    $('#change_cards').show();
                } else {
                    layer.msg('已补牌，不能修改。');
                }
            }
        } else {
            layer.msg('请先手动停止AI识别。');
        }
        
    } 
}
var changeErrSbCard = function() {
    var poker = $("input[name='cardToChanged']:checked").val();
    var positionNum = 0;
    
    layer.confirm(lang.confirm_to_change_card,{btn: [lang.confirm,lang.cancel],title:lang.message}, function(index){
        if (currentPositionToChange <= 0 ) {
            layer.msg('出错。请刷新重试。');
            $('#change_cards').hide();
            return false;
        }

        console.log('currentPositionToChange:' + currentPositionToChange);
        
        var query = new Object();

        query.card = poker;
        query.position = currentPositionToChange;
        query.change = 1;
        sendScanBaccarat(query, 1);
        $('input:checked').removeAttr('checked');
        $('#change_cards').hide();
        layer.close(index);
    });
}
var cancelChangeErrSbCard = function() {
    $('input:checked').removeAttr('checked');
    $('#change_cards').hide();
}
//

var websocket = io(websocketProtocol+"://"+websocketUrl+"/?table_id="+table_id+"&account="+account+"&connect=space&userid="+userid+"&login_token="+login_token,{transports: ['websocket']});
websocket.on('reconnecting', (timeout) => {
	//触发重连
	layer.msg('服务断开,正在重新连接...', {
		icon: 16,
		shade: 0.6,
		time:0,
	});
});
websocket.on('reconnect', (timeout) => {
	//重连成功
	layer.closeAll();
    layer.msg('服务重新连接成功');
});
//事件  发送*******************************************************************************************************************
var startBet = function(){
    sbSocket.emit("stop",{"tableCode":casinoTableId, "type":"SYS"});
	websocket.emit('startBet',{table_id : table_id, number_tab_id : number_tab_id});
};
var endBet = function (){
	websocket.emit('endBet',{table_id : table_id, number_tab_id : number_tab_id});
};
var startRob = function(){
	websocket.emit('startRob',{table_id : table_id, number_tab_id : number_tab_id});
};
var endRob = function(){
	websocket.emit('endRob',{table_id : table_id, number_tab_id : number_tab_id});
};

// 重新SB
var restartSB = function(){
    manualStopAi = false;
    //sbSocket.emit('start', {'tableCode': casinoTableId, 'type': 'SYS', 'biz': number_tab_id});
    sbSocket.emit("scanAllCards",{"tableCode":casinoTableId, "from":1, "count":6, "isEmptyAllowed":"Yes", 'type': 'SYS', "biz": number_tab_id});
};
var stopSB = function(){
    manualStopAi = true;
    sbSocket.emit("stop",{"tableCode":casinoTableId, "type":"SYS"});
};

var resetNumberTab = function(){
    isCBoot = true;
    var betStatus = $("#number_tab_status").val();
    if(betStatus == 1 || betStatus == 2){
        layer.confirm(lang.is_reset_number,{btn: [lang.confirm,lang.cancel],title:lang.message}, function(index){
            websocket.emit('resetNumberTab',{table_id : table_id});
            isCBoot = false;
            layer.close(index);
        },function(index){
            isCBoot = false;
        });
    }else{
        layer.msg(lang.reset_number_fail);
    }
};
var changeBoot = function(){
    isCBoot = true;
    var betStatus = $("#number_tab_status").val();
    if(betStatus == 0 || betStatus == 3){
        layer.confirm(lang.is_to_boot,{btn: [lang.confirm,lang.cancel],title:lang.message}, function(index){
			websocket.emit('changeBoot',{table_id : table_id});
            isCBoot = false;
            layer.close(index);
        },function(index){
            isCBoot = false;
        });
    }else{
        layer.msg(lang.change_boot_false);
    }
};
var resetBoot = function(){
    layer.confirm(lang.is_to_balance,{btn: [lang.confirm,lang.cancel],title:lang.message}, function(index){
		websocket.emit('resetBoot',{table_id : table_id});
        layer.close(index);
    });
};
var opening = function(){
    $('.control-box .btn-box2 span').removeClass('on');
    if(game_id == 1){
		websocket.emit('openingBaccarat',{table_id : table_id, number_tab_id : number_tab_id});
    }else if(game_id == 2){
		websocket.emit('openingDt',{table_id : table_id, number_tab_id : number_tab_id});
    }else if(game_id == 4){
		websocket.emit('openingNn',{table_id : table_id, number_tab_id : number_tab_id});
    }else if(game_id == 5){
		websocket.emit('openingTc',{table_id : table_id, number_tab_id : number_tab_id});
    }else if(game_id == 6){
        let result = parseInt($('#toning_result').val());
        if (result == 0 || result == 1 || result == 2 || result == 3 || result == 4){
            websocket.emit('openingToning',{table_id : table_id, number_tab_id : number_tab_id, result : result});
        }
    }else if(game_id == 7){
        let result = $('#dice_result').val();
        websocket.emit('openingDice',{table_id : table_id, number_tab_id : number_tab_id, result : result});
    }
};

// 百家乐发送数据
var sendScanBaccarat = function(data, isChange = 0) {
    if (isChange == 1) {
        websocket.emit('sendScanBaccarat',
            {table_id : table_id, number_tab_id : number_tab_id, card : data.card, position : data.position, change: data.change});
    } else {
        websocket.emit('sendScanBaccarat',
            {table_id : table_id, number_tab_id : number_tab_id, card : data.card, position : data.position});
    }
}

// 龙虎发送数据
var sendScanDt = function(data) {
    websocket.emit('sendScanDt',
            {table_id : table_id, number_tab_id : number_tab_id, card : data.card, position : data.position});
}

// 牛牛发送数据
var sendScanNn = function(data) {
    websocket.emit('sendScanNn',
            {table_id : table_id, number_tab_id : number_tab_id, card : data.card, position : data.position});
}

// 色碟显示
var showToningBox = function (){
    $('#toning_result_box').fadeIn();
}
var hideToningBox = function (){
    $('#toning_result_box').fadeOut();
}
// 骰宝显示
var showDiceBox = function (){
    $('#dice_box').fadeIn();
}
var hideDiceBox = function (){
    $('#dice_box').fadeOut();
}
//事件  发送*******************************************************************************************************************
//事件返回*********************************************************************************************************************
websocket.on('onlineLogin',function(data){
    if (data.table_id === table_id) {
        if(data.status === true){
            setNumberInfo(data.round);
            setBetStatus(data.round.number_tab_status)
            clearBetAmount();
            waybillFunc();
            if (data.round.number_tab_status.bet_status != undefined && data.round.number_tab_status.bet_status == 2){
                if(game_id == 4 || game_id == 5){
                    showCardNn(data.round.show_card);
                }else{
                    showCard(data.round.show_card);
                }
            }
        }else{
            layer.msg(lang[data.msg],{time:0});
        }
    }
	
});
websocket.on('RepeatedEntry',function(data){
	websocket.close();
	layer.msg(lang[data.msg]);
	setTimeout(function (){
		window.location.href='/login/logout';
	},2000);
});
websocket.on('startBet',function(data){
	if(data.status === true && data.table_id === table_id){
		mp3List = ['start.mp3'];
		audioMp3(mp3List).Play();
		setBetStatus(data.round.number_tab_status);
	}else{
        if (data.table_id != undefined && data.table_id == table_id) {
            layer.msg(lang[data.msg]);
        }
	}
});
websocket.on('startRob',function(data){
	if(data.status === true && data.table_id == table_id){
		mp3List = ['start_rob.mp3'];
        audioMp3(mp3List).Play();
        $("#number_rob_status").val(1);
	}else{
		if (data.table_id != undefined && data.table_id == table_id) {
            layer.msg(lang[data.msg]);
        }
	}
});
websocket.on('startRobCountDown',function(data){
	if(data.status === true && data.table_id == table_id && data.count_down >= 0){
		$('.nobegin-tip').html('抢庄中');
        countDownRob(data.count_down);
	}else{
		if (data.table_id != undefined && data.table_id == table_id) {
            layer.msg(lang[data.msg]);
        }
	}
});
websocket.on('endRob',function(data){
	$('.nobegin-tip').html('');
	if(data.status === true && data.table_id == table_id){
		$('#number_rob_status').val(2);
        startBet();
	}else{
		if (data.table_id != undefined && data.table_id == table_id) {
            layer.msg(lang[data.msg]);
        }
	}
});

websocket.on('sendScanChangeResult',function(data){
    if (game_id == 4 && data.status == false) {
        layer.msg(data.msg);
    }
});

websocket.on('sendScanResult',function(data){
	if(data.status === true && data.table_id == table_id){
		if(game_id == 1 || game_id == 2){
			Flop(data);

            // 识别相关
            if (scanner_type == 2 && game_id == 1 && data.round != undefined && data.round.position != undefined){
                var _position = parseInt(data.round.position);
                switch(_position) {
                    case 11:
                        scanPosition = 2;
                        break;
                    case 12:
                        scanPosition = 3;
                        break;
                    case 21:
                        scanPosition = 4;
                        break;
                    case 22:
                        scanPosition = 5;
                        break;
                    case 13:
                        scanPosition = 6;
                        break;
                    case 23:
                        initScanParams();   
                        break;
                }
                if (scanPosition == 5) {
                    var info = isBopai(card_info);
                    if (info['is_bopai'] && info['player_3'] == 1) {
                        scanPosition = 5;
                    } else if (info['is_bopai'] && info['banker_3'] == 1) {
                        scanPosition = 6;
                    }
                }
/*
                if (scanPosition == 5 || scanPosition == 6) {
			        sbSocket.emit("stop",{"tableCode":casinoTableId, "type":"SYS"});
                    sbSocket.emit("scanCardWithIndex",{"tableCode": casinoTableId, "index":scanPosition, 'type': 'SYS', "biz": number_tab_id});
                }
*/
                //
            }
		}else if(game_id==4||game_id==5){
			if(data.round.position == 0){
				flop_position(data);
			}else{
                // 识别相关
                if (scanner_type == 2 && game_id == 4) {
                    if (data.round.position == 20) {
                        scanPosition = 21;
                        scanDefaultPosition = 'P1';
                        clearInterval(scanTask);
                        scanTask = null;

                        clearInterval(positionScanTask);
                        positionScanTask = null;

                        isPositionScaned = false;
                        isCardScaned = true;
                    } else {
                        var _position = data.round.position;

                        switch (scanDefaultPosition) {
                            case 'P2': 
                                if (_position < 15) {
                                    scanPosition = _position + 6;
                                } else {
                                    scanPosition = _position - 14;
                                }
                                break;
                            case 'P3':
                                if (_position < 10) {
                                    scanPosition = _position + 11;
                                } else {
                                    scanPosition = _position - 9;
                                }
                                break;
                            case 'B':
                                if (_position < 5) {
                                    scanPosition = _position + 16;
                                } else {
                                    scanPosition = _position -4;
                                }
                                break;
                            default:
                                scanPosition = _position + 1;
                        }

                        if (scanPosition > 20) {
                            scanPosition = 1;
                        }
                    }
                }
                //
				flop_card(data);
			}
		}
	}
    /*else{
		if (data.table_id != undefined && data.table_id == table_id) {
            layer.msg(lang[data.msg]);
        }
	}*/
});
websocket.on('resetNumberTab',function(data){
    if(data.status === true && data.table_id == table_id){
        setNumberInfo(data.round);
        setBetStatus(data.round.number_tab_status);
        clearBetAmount();
        
        // 识别相关
        if (scanner_type == 2) {
            initScanParams();
        }
        //
        
        $(".countdown").css({"opacity":0,"display":"none"});
        $(".countdown .grab-count").removeClass("count-active");
        $(".begincard .box").animate({"opacity":"0"},function(){
            $(".begincard").fadeOut();

            $(".table-info .nobegin-tip").fadeIn();
            $('.box1').css("background-color","rgba(0, 0, 0, 0.5)");
            $('.box2').css("background-color","rgba(0, 0, 0, 0.5)");
            $('.box3').css("background-color","rgba(0, 0, 0, 0.5)");
            $('.box4').css("background-color","rgba(0, 0, 0, 0.5)");
            $(".begincard .box .list .card").removeClass("begin")
            $(".begincard .card .topleft").html("")
            $(".begincard .card .bottomright").html("")
            $(".list .card .face").css("background-image","")
            $(".begincard .list .draw .rotate").css("display",'none');
        });
        card_info=[];
    }else{
        if (data.table_id != undefined && data.table_id == table_id) {
            layer.msg(lang[data.msg]);
        }
    }
});
websocket.on('changeBoot',function(data){
	if(data.status === true && data.table_id == table_id){
		setNumberInfo(data.round);
		setBetStatus(data.round.number_tab_status);
		clearBetAmount();
		waybillFunc();
        card_info = [];

        // 识别相关
        if (scanner_type == 2) {
            initScanParams();
        }
        //
        
	}else{
		if (data.table_id != undefined && data.table_id == table_id) {
            layer.msg(lang[data.msg]);
        }
	}
});
websocket.on('resetBoot',function(data){
	if(data.status === true && data.table_id == table_id){
		setNumberInfo(data.round);
		setBetStatus(data.round.number_tab_status);
		clearBetAmount();
		waybillFunc();
        card_info = [];

        // 识别相关
        if (scanner_type == 2) {
            initScanParams();
        }
        //
        
	}else{
		if (data.table_id != undefined && data.table_id == table_id) {
            layer.msg(lang[data.msg]);
        }
	}
});
websocket.on('startBetCountDown',function(data){
	if(data.status == true && data.table_id == table_id){
		countDown(data.count_down);
	}
});
websocket.on('endBet',function(data){
	if(data.status === true && data.table_id == table_id){
		$(".countdown").css({"opacity":0,"display":"none"});
		$(".countdown .grab-count").removeClass("count-active");
		mp3List = ['stop_2.mp3'];
		audioMp3(mp3List).Play();
		if(game_id == 4 || game_id == 5){
			$(".banker_result").html('');
			$(".player_1_result").html('');
			$(".player_2_result").html('');
			$(".player_3_result").html(''); 
		}
        if(game_id == 6){
            $('#toning_result').val('');
            $(".toning-result-num").removeClass("active");
        }
		$(".countdown").css({"opacity":0,"display":"none"});
		$(".countdown .grab-count").removeClass("count-active");
		setBetStatus(data.round.number_tab_status);

        // 识别相关
        if (scanner_type == 2 && game_id == 1) {
            //doScanCards();
            
            //sbSocket.emit('start', {'tableCode': casinoTableId, 'type': 'SYS', 'biz': number_tab_id});
            sbSocket.emit("scanCardWithIndex",{"tableCode": casinoTableId, "index":1, 'type': 'SYS', "biz": number_tab_id}); //  "index": scanPosition
            //sbSocket.emit("scanAllCards",{"tableCode":casinoTableId, "from":1, "count":4, "isEmptyAllowed":"Yes", 'type': 'SYS', "biz": number_tab_id});
            
        } else if (scanner_type == 2 && game_id == 2) {
            doDtScanCards();
        } else if (scanner_type == 2 && game_id == 4) {
            doNnScanPositionCard();
            doNnScanCards();
        }
        //

	}else{
		if (data.table_id != undefined && data.table_id == table_id) {
            layer.msg(lang[data.msg]);
        }
	}
});
websocket.on('openingBaccarat',function(data){
	if(data.status === true && data.table_id == table_id){
		showPng(data.round.opening,data.round.pair);
		gameResult(data);
		setNumberInfo(data.round);
		setBetStatus(data.round.number_tab_status);
		clearBetAmount();
		waybillFunc();
        sbCardsInfo = [[], [], [], [], [], []];
        //sbSocket.emit("stopData",{"tableCode":casinoTableId, "type":"SYS"});
        sbSocket.emit("stop",{"tableCode":casinoTableId, "type":"SYS"});
        // 识别相关
        if (scanner_type == 2) {
            initScanParams();
        }
        //
        
	}else{
		if (data.table_id != undefined && data.table_id == table_id) {
            layer.msg(lang[data.msg]);
        }
	}
});
websocket.on('openingDt',function(data){
	if(data.status === true && data.table_id == table_id){
		showPngDt(data.round.opening);
		gameResult(data);
		setNumberInfo(data.round);
		setBetStatus(data.round.number_tab_status);
		clearBetAmount();
		waybillFunc();

        // 识别相关
        if (scanner_type == 2) {
            initScanParams();
        }
        //
        
	}else{
		if (data.table_id != undefined && data.table_id == table_id) {
            layer.msg(lang[data.msg]);
        }
	}
});
websocket.on('openingNn',function(data){
	if(data.status === true && data.table_id == table_id){
		$('#number_tab_status').val(0);
		$('#number_rob_status').val(0);
		setNumberInfo(data.round);
		$('.box1').css("background-color","rgba(0, 0, 0, 0.5)");
		$('.box2').css("background-color","rgba(0, 0, 0, 0.5)");
		$('.box3').css("background-color","rgba(0, 0, 0, 0.5)");
		$('.box4').css("background-color","rgba(0, 0, 0, 0.5)");
		gameResultNn(data);
	}else{
		if (data.table_id != undefined && data.table_id == table_id) {
            layer.msg(lang[data.msg]);
        }
	}
});
websocket.on('openingTc',function(data){
	if(data.status === true && data.table_id == table_id){
		$('#number_tab_status').val(0);
		$('#number_rob_status').val(0);
		setNumberInfo(data.round);
		$('.box1').css("background-color","rgba(0, 0, 0, 0.5)");
		$('.box2').css("background-color","rgba(0, 0, 0, 0.5)");
		$('.box3').css("background-color","rgba(0, 0, 0, 0.5)");
		$('.box4').css("background-color","rgba(0, 0, 0, 0.5)");
		gameResultNn(data);
	}else{
		if (data.table_id != undefined && data.table_id == table_id) {
            layer.msg(lang[data.msg]);
        }
	}
});
websocket.on('openingToning',function(data){
    if(data.status === true && data.table_id == table_id){
        $('#toning_result').val("");
        $('.toning-result-num').removeClass("active");
        setNumberInfo(data.round);
        setBetStatus(data.round.number_tab_status);
        waybillFunc();
        hideToningBox();
    }else{
        if (data.table_id != undefined && data.table_id == table_id) {
            layer.msg(lang[data.msg]);
        }
    }
});
websocket.on('openingDice',function(data){
    if(data.status === true && data.table_id == table_id){
        $('#dice_result').val("");
        $('#dice_item_1 img').attr("src", '/static/handle/img/dice0.png');
        $('#dice_item_2 img').attr("src", '/static/handle/img/dice0.png');
        $('#dice_item_3 img').attr("src", '/static/handle/img/dice0.png');
        setNumberInfo(data.round);
        setBetStatus(data.round.number_tab_status);
        waybillFunc();
        hideDiceBox();
    }else{
        if (data.table_id != undefined && data.table_id == table_id) {
            layer.msg(lang[data.msg]);
        }
    }
});
//事件返回*********************************************************************************************************************

// 识别Socket
var sbSocket = io(localSbServer,{transports: ['websocket']});
sbSocket.on('reconnecting', (timeout) => {
	//触发重连
	layer.msg('服务断开,正在重新连接...', {
		icon: 16,
		shade: 0.6,
		time:0,
	});
});

sbSocket.on('reconnect', (timeout) => {
	//重连成功
	layer.closeAll();
    layer.msg('服务重新连接成功');
});

// 加入识别服务
sbSocket.on('joinEvent', function(data) {
    if (data.code == 200 && data.type == 'SYS' && data.tableCode == casinoTableId) {
        //layer.msg('Connect SB Server Success');
    } else {
        layer.msg('Connect Faild. Please double check the sb server');
    }
});

// 启动识别响应事件
sbSocket.on('startEvent', function(data) {
    // 200: 启动成功
    // 500: 设备离线
    // 501: 参数错误
    if (data.code != 200) {
        layer.msg(data.msg);
    }
    
});

// 停止识别响应事件
sbSocket.on('stopEvent', function(data) {
    // 200: 停止成功
    // 500: 设备离线
    // 501: 参数错误
    if (data.code != 200) {
        layer.msg(data.msg);
    }
});

var sbCardsInfo = [[], [], [], [], [], []];
var CONFIRM_TIMES = 1;

//CardsInfo[0]['card'] = '';
//sbCardsInfo[0]['tims'] = 0;

// 数据接收事件
sbSocket.on('dataEvent', function(data) {
    // tableType == 'ONE', 单张识别
    // count: 画框数，6
    // tableCode: casinoTableId
    if (data.tableType == 'ONE' && data.tableCode == casinoTableId && data.biz != undefined && data.biz == number_tab_id) {
        data.data.forEach(function(value, index) {
            if (value.card != 'None' && value.card != '') {
                var query = new Object();
                query.card = cardToServer(value.card);
                if (query.card != 'None') {
                    if (!('card' in sbCardsInfo[index]) || !('time' in sbCardsInfo[index])) {
                        sbCardsInfo[index]['card'] = query.card;
                        sbCardsInfo[index]['time'] = 1;
                    } else {
                        if (sbCardsInfo[index]['card'] == query.card && sbCardsInfo[index]['time'] >= CONFIRM_TIMES) {
                            if (index < 4) {
                                query.position = position[value.index - 1];
                                sendScanBaccarat(query);
                            } else {
                                var info = isBopai(card_info);
                                if (index == 4) {
                                    if (info['is_bopai'] && info['player_3'] == 1) {
                                        query.position = position[4];
                                        sendScanBaccarat(query);
                                    }
                                } else {
                                    if (info['is_bopai'] && info['banker_3'] == 1) {
                                        //if (info['player_3'] == 1) {
                                        if (card_info.length > 4) {
                                            query.position = position[5];
                                        } else {
                                            query.position = position[4];
                                        }
                                        sendScanBaccarat(query);
                                    }
                                }
                            }
                        } else {
                            if (sbCardsInfo[index]['card'] == query.card) {
                                sbCardsInfo[index]['time']++;
                            } else {
                                sbCardsInfo[index]['card'] = query.card;
                                sbCardsInfo[index]['time'] = 1;
                            }
                        }
                        
                    }
                    
                }
                
            }

        });
    }
});

// 收到指定下标数据
sbSocket.on('dataWithIndexEvent', function(data) {
    // tableType == 'ONE', 单张识别
    // count: 画框数，6
    // tableCode: casinoTableId
    if (data.tableType == 'ONE' && data.tableCode == casinoTableId && data.biz != undefined && data.biz == number_tab_id) {
        var query = new Object();
        query.card = cardToServer(data.data['card']);

        // For Confirm --------------------------------------------------------------------
        if (query.card != 'None') {
            var index = data.data['index'] - 1;
            
            if (!('card' in sbCardsInfo[index]) || !('time' in sbCardsInfo[index])) {
                sbCardsInfo[index]['card'] = query.card;
                sbCardsInfo[index]['time'] = 1;
            } else {
                if (sbCardsInfo[index]['card'] == query.card && sbCardsInfo[index]['time'] >= CONFIRM_TIMES) {

                    if (index < 4) {
                        query.position = position[index];
                        sendScanBaccarat(query);
                    } else {
                        var info = isBopai(card_info);
                        if (index == 4) {
                            if (info['is_bopai'] && info['player_3'] == 1) {
                                query.position = position[4];
                                sendScanBaccarat(query);
                            }
                        } else {
                            if (info['is_bopai'] && info['banker_3'] == 1) {
                                //if (info['player_3'] == 1) {
                                if (card_info.length > 4) {
                                    query.position = position[5];
                                } else {
                                    query.position = position[4];
                                }
                                sendScanBaccarat(query);
                            }
                        }
                    }

                } else {
                    if (sbCardsInfo[index]['card'] == query.card) {
                        sbCardsInfo[index]['time']++;
                    } else {
                        sbCardsInfo[index]['card'] = query.card;
                        sbCardsInfo[index]['time'] = 1;
                    }
                }
                
            }
            
        } /*else {
            sbSocket.emit("scanCardWithIndex",{"tableCode": casinoTableId, "index":scanPosition, 'type': 'SYS', "biz": number_tab_id});
        }*/
        // For Confirm ---------------------------------------------------------------------------------
        sbSocket.emit("scanCardWithIndex",{"tableCode": casinoTableId, "index":scanPosition, 'type': 'SYS', "biz": number_tab_id});
    }
});


// 收到范围下标数据
sbSocket.on('dataWithAllCardsEvent', function(data) {
    // tableType == 'ONE', 单张识别
    // count: 画框数，6
    // tableCode: casinoTableId
    if (data.tableType == 'ONE' && data.tableCode == casinoTableId && data.biz != undefined && data.biz == number_tab_id) {
        data.data.forEach(function(value, index) {
            if (value.card != 'None' && value.card != '') {
                var query = new Object();
                query.card = cardToServer(value.card);
                if (query.card != 'None') {
                    if (!('card' in sbCardsInfo[index]) || !('time' in sbCardsInfo[index])) {
                        sbCardsInfo[index]['card'] = query.card;
                        sbCardsInfo[index]['time'] = 1;
                    } else {
                        if (sbCardsInfo[index]['card'] == query.card && sbCardsInfo[index]['time'] >= CONFIRM_TIMES) {
                            if (index < 4) {
                                query.position = position[value.index - 1];
                                sendScanBaccarat(query);
                            } else {
                                var info = isBopai(card_info);
                                if (index == 4) {
                                    if (info['is_bopai'] && info['player_3'] == 1) {
                                        query.position = position[4];
                                        sendScanBaccarat(query);
                                    }
                                } else {
                                    if (info['is_bopai'] && info['banker_3'] == 1) {
                                        //if (info['player_3'] == 1) {
                                        if (card_info.length > 4) {
                                            query.position = position[5];
                                        } else {
                                            query.position = position[4];
                                        }
                                        sendScanBaccarat(query);
                                    }
                                }
                            }
                        } else {
                            if (sbCardsInfo[index]['card'] == query.card) {
                                sbCardsInfo[index]['time']++;
                            } else {
                                sbCardsInfo[index]['card'] = query.card;
                                sbCardsInfo[index]['time'] = 1;
                            }
                        }
                        
                    }
                    
                }
                
            }

        });
    }
});
/*
// 数据接收事件
sbSocket.on('dataWithAllCardsEvent', function(data) {
    // tableType == 'ONE', 单张识别
    // count: 画框数，6
    // tableCode: casinoTableId
    if (data.tableType == 'ONE' && data.tableCode == casinoTableId) {
        data.data.forEach(function(value) {
            if (value.card != 'None') {
                var query = new Object();
                query.card = cardToServer(value.card);
                query.position = position[value.index - 1];
                sendScanBaccarat(query);
            }

        });
    }
});
*/


sbSocket.emit('join', { 'tableCode':casinoTableId, 'type':'SYS'});



//启动执行
$(function(){
	getLang();
    //视频处理
    $("#video-iframe").attr("src",player+'?url='+flvUrl);
    $(document).keydown(function (e){
        if(e.keyCode == 13){

            var cookieValue = $.cookie("enter_time");
            if(!cookieValue){
                $.cookie("enter_time", 1, { expires: 1/86400*3 });
            }else{
                layer.msg('Please hold on');
                return false
            }

            if(isCBoot == true){
                $('.layui-layer-btn0').click();
                isCBoot = false;
            }else{
                //var keycode = $('#keycode').val();
                var numberTabStatus = $('#number_tab_status').val();
                //if(keycode == '6'){
                if (numberTabStatus == 0) {
                    if(!isopentime){
                        var is_rob = $('#is_rob').val();
                        if(is_rob == 1){
                            startRob();
                        }else{
                            startBet();
                        }
                         $('#keycode').val('');
                    }else{     
                      layer.msg("请稍等!");
                    }
                }else if (numberTabStatus == 2) {
                    opening();
                }
            }
        }
        //开局
        if(e.keyCode == 111){
            $('#keycode').val('6');
        }
        //修改当前状态
        if(e.keyCode == 109){
            $('#update_ludan').toggle();
        }
        //换靴
        if(e.keyCode == 107){
            changeBoot();
            $('#keycode').val('');
        }
        //退出登录
        if(e.keyCode == 106){
            if(table_type == 1){
                cutout();
                $('#keycode').val('');
            }else{
                if(bet_type == 2){
                    cutout();
                    $('#keycode').val('');
                }else{
                    loginout();
                    $('#keycode').val('');
                }
            }
        }
        //取消
        if(e.keyCode == 110){
            $('.layui-layer-btn1').click();
        }
        // 停止倒计时
        if(e.keyCode == 96){
            if(game_id == 5 || game_id == 4){
                var number_rob_status=$("#number_rob_status").val();
                var number_tab_status=$("#number_tab_status").val();
				if((number_rob_status==1&&number_tab_status==0)||(number_rob_status==2&&number_tab_status==0)){
					endRob();
				}else{
					endBet();
				}
            }else{
                endBet();
            }
        }
        if(game_id == 6){
            if (e.keyCode == 96 || e.keyCode == 97 || e.keyCode == 98 || e.keyCode == 99 || e.keyCode == 100){
                var result_num = -1;
                switch (e.keyCode){
                    case 96:
                        result_num = 0;
                        break;
                    case 97:
                        result_num = 1;
                        break;
                    case 98:
                        result_num = 2;
                        break;
                    case 99:
                        result_num = 3;
                        break;
                    case 100:
                        result_num = 4;
                        break;
                }
                if(result_num >= 0){
                    $('#toning_result').val(result_num);
                    $(".toning-result-" + result_num).addClass("active").siblings().removeClass("active");
                }
            }
        }
        // 骰宝结果选择
        if (game_id == 7){
            console.log(e.keyCode);
            if (e.keyCode == 97 || e.keyCode == 98 || e.keyCode == 99 || e.keyCode == 100 || e.keyCode == 101 || e.keyCode == 102){
                var num = 0;
                switch (e.keyCode){
                    case 97:
                        num = 1;
                        break;
                    case 98:
                        num = 2;
                        break;
                    case 99:
                        num = 3;
                        break;
                    case 100:
                        num = 4;
                        break;
                    case 101:
                        num = 5;
                        break;
                    case 102:
                        num = 6;
                        break;
                }
                if (num > 0){
                    var resultString = $('#dice_result').val();
                    var resultArray = [];
                    if (resultString != ''){
                        resultArray = resultString.split(",");
                    }
                    if (resultArray.length < 3){
                        resultArray.push(num);
                        if (resultArray.length == 1){
                            $('#dice_item_1 img').attr("src", '/static/handle/img/dice'+num+'.png');
                        } else if (resultArray.length == 2) {
                            $('#dice_item_2 img').attr("src", '/static/handle/img/dice'+num+'.png');
                        } else if (resultArray.length == 3){
                            $('#dice_item_3 img').attr("src", '/static/handle/img/dice'+num+'.png');
                        }
                        $('#dice_result').val(resultArray.join(","));
                    }
                }
            } else if (e.keyCode == 109){
                $('#dice_result').val('');
                $('#dice_item_1 img').attr("src", '/static/handle/img/dice0.png');
                $('#dice_item_2 img').attr("src", '/static/handle/img/dice0.png');
                $('#dice_item_3 img').attr("src", '/static/handle/img/dice0.png');
            }
        }
    })
    $(window).resize(function(){
        requestData(ludan);
    })
    audio.addEventListener("ended", nextAudio);
    getTime();
    // 日期
    setInterval(function(){
        getTime();
    }, 1000);
    // 侧栏控台
    $(".control-box").hover(function(){
        $(".control-box").stop().animate({right:"0"})
    },function(){
        $(".control-box").stop().animate({right:"-410px"})
    })
    // 多语言切换
    $('#language').change(function(){
        var language = $('#language').val();
        if(language == "cn" || language == "tw" || language == "en"){
            $.get("/index/lang?lang="+language,function(data){
                location.reload();
            })
        }
    });
    $("#confirm_update_ludan").click(function (){
        retreated();
    });
    $("#cancel_update_ludan").click(function (){
        $('#update_ludan').hide();
    });
    // 色碟方法
    $('.toning-result-num').click(function () {
        $('#toning_result').val(parseInt($(this).html()));
        $(this).addClass("active").siblings().removeClass("active");
    })

    // 牛牛识别
    if (scanner_type == 2) {
        $('.begincard .card').find(".face").on('click', function() {
            openAllCardsPanel(this);
        });
    }
    
})
function loginout(){
    isCBoot = true;
    layer.confirm(lang.is_to_logout,{btn: [lang.confirm,lang.cancel],title:lang.message}, function(index){
        window.location.href='/login/logout';
        isCBoot = false;
        layer.close(index);
    },function(index){
        isCBoot = false;
    });
};
function showPng(opening, pair){
    if(opening == 1 && pair == 0) {
        $('#openingPng').attr('src','/static/result_img/banker.png');
        mp3List = ['banker_win.mp3'];
    }
    if(opening == 1 && pair == 1) {
        $('#openingPng').attr('src','/static/result_img/banker_bpair.png');
        mp3List = ['banker_win.mp3','banker_pair.mp3'];
    }
    if(opening == 1 && pair == 2) {
        $('#openingPng').attr('src','/static/result_img/banker_ppair.png');
        mp3List = ['banker_win.mp3','player_pair.mp3'];
    }
    if(opening == 1 && pair == 3) {
        $('#openingPng').attr('src','/static/result_img/banker_bpair_ppair.png');
        mp3List = ['banker_win.mp3','banker_pair.mp3','player_pair.mp3'];
    }
    if(opening == 2 && pair == 0) {
        $('#openingPng').attr('src','/static/result_img/player.png');
        mp3List = ['player_win.mp3'];

    }
    if(opening == 2 && pair == 1) {
        $('#openingPng').attr('src','/static/result_img/player_bpair.png');
        mp3List = ['player_win.mp3','banker_pair.mp3'];
    }
    if(opening == 2 && pair == 2) {
        $('#openingPng').attr('src','/static/result_img/player_ppair.png');
        mp3List = ['player_win.mp3','player_pair.mp3'];
    }
    if(opening == 2 && pair == 3) {
        $('#openingPng').attr('src','/static/result_img/player_bpair_ppair.png');
        mp3List = ['player_win.mp3','banker_pair.mp3','player_pair.mp3'];
    }
    if(opening == 3 && pair == 0) {
        $('#openingPng').attr('src','/static/result_img/tie.png');
        mp3List = ['tie.mp3'];
    }
    if(opening == 3 && pair == 1) {
        $('#openingPng').attr('src','/static/result_img/tie_bpair.png');
        mp3List = ['tie.mp3','banker_pair.mp3'];
    }
    if(opening == 3 && pair == 2) {
        $('#openingPng').attr('src','/static/result_img/tie_ppair.png');
        mp3List = ['tie.mp3','player_pair.mp3'];
    }
    if(opening == 3 && pair == 3) {
        $('#openingPng').attr('src','/static/result_img/tie_bpair_ppair.png');
        mp3List = ['tie.mp3','banker_pair.mp3','player_pair.mp3'];
    }
    audioMp3(mp3List).Play();
}

function showPngDt (opening){
    if(opening == 1) {
        $('#openingPng').attr('src','/static/handle/img/dragon_win.png');
        mp3List = ['dragon_win.mp3'];
    }
    if(opening == 2) {
        $('#openingPng').attr('src','/static/handle/img/tiger_win.png');
        mp3List = ['tiger_win.mp3'];
    }
    if(opening == 3) {
        $('#openingPng').attr('src','/static/handle/img/tie.png');
        mp3List = ['tie.mp3'];
    }
    audioMp3(mp3List).Play();
}

function gameResult(data){
    var result_imgsrc='',Result='';
    switch(true){
        case data.round.opening==1:// 庄
            Result='banker';
            $(".begincard .card-box .banker-card").addClass("win").siblings().removeClass("win");
            break;
        case data.round.opening==2:// 闲
            Result='player';
            $(".begincard .card-box .player-card").addClass("win").siblings().removeClass("win");
            break;
        case data.round.opening==3:// 和
            Result='tie'
            break;
    }
    if(data.round.pair==1){
        result_imgsrc=Result+'_bpair'
    }else if(data.round.pair==2){
        result_imgsrc=Result+'_ppair'
    }else if(data.round.pair==3){
        result_imgsrc=Result+'_bpair_ppair'
    }else{
        result_imgsrc=Result
    }
    var src='/static/result_img/'+result_imgsrc+'.png'
    $(".begincard .player-card .draw .text ").html(lang.player_all+' '+data.round.player+' '+lang.point)
    $(".begincard .banker-card .draw .text ").html(lang.banker_all+' '+data.round.banker+' '+lang.point);
    $('#openingElement').show();
    $('#openingElement').addClass("blink");
    isopentime=true;
    setTimeout(function(){

        $('#openingElement').removeClass("blink");
        $('#openingElement').hide();
    },3000)
    // 清除状态
    card_info=[];///清除牌数据
     setTimeout(function(){
        $(".begincard .box").animate({"opacity":"0"},function(){
           $(".begincard .card-box .list").removeClass("win");
            $(".begincard").fadeOut(function(){ isopentime=false;});
           $(".begincard .list .draw .text").css("text-align","center")
            $(".begincard .box .list .card").removeClass("begin")
            $(".begincard .card .topleft").html("")
            $(".begincard .card .bottomright").html("");
            $(".begincard .box .list .card").find(".face").css("background-image","url('/static/handle/img/faces.png')")
            $(".begincard .box .list .draw .card").find(".face").css("background-image","url('/static/handle/img/faces1.png')")
            $(".begincard .list .draw .rotate").css("display",'none')
            $(".table-info .nobegin-tip").fadeIn();

        })
    },5000)
}
function gameResultNn(data){
    isWin.win_player_1=data.round.win_player_1;
    isWin.win_player_2=data.round.win_player_2;
    isWin.win_player_3=data.round.win_player_3;
    var newmp3List=[];
    if(data.round.win_player_1==1){
        newmp3List.push('nn_X1.wav');
        isWin.text.push("P1");
        $(".begincard .box2").addClass("win");
    }
    if(data.round.win_player_2==1){
        newmp3List.push('nn_X2.wav');
        isWin.text.push("P2");
        $(".begincard .box3").addClass("win");
    }
    if(data.round.win_player_3==1){
        newmp3List.push('nn_X3.wav');
        isWin.text.push("P3");
        $(".begincard .box4").addClass("win");
    }
    if(data.round.win_player_1==0&&data.round.win_player_2==0&&data.round.win_player_3==0){
        newmp3List.push('nn_Zwin.wav');
        isWin.text.push("B");
        $(".begincard .box1").addClass("win");
    }
    var str=isWin.text.length==0?'Banker':isWin.text.join('、')+" Win";
    $(".begincard .win-tip").html(str);
    $(".begincard .win-tip").addClass("show");
    let mp3List = newmp3List;
    audioMp3(mp3List).Play();

    isopentime=true;

    setTimeout(function(){
        $(".begincard .win-tip").removeClass("show");isWin.text=[];
    },3000);
    setTimeout(function(){
        $(".begincard").fadeOut(function(){
            isopentime=false;
            $(".begincard .box").animate({"opacity":"0"});
            $(".begincard .box1").animate({"top":"100%","opacity":"0"});
            $(".begincard .box2").animate({"top":"100%","opacity":"0"});
            $(".begincard .box3").animate({"top":"100%","opacity":"0"});
            $(".begincard .box4").animate({"top":"100%","opacity":"0"});
            setBetStatus(data.round.number_tab_status);
            waybillFunc();
            //清空牌数据
            $(".begincard div").removeClass("win");
            $(".list .card .face").css("background-image","");
        });
    },5000);
}
//获取当前语言包
function getLang(){
	$.ajax({
        url:"/index/get_lang",
        type:"POST",
        dataType:"JSON",
        async:false,
        success:function(data){
            if(data.status === 1){
                lang = data.lang;
            }
        }
    })
}
//倒计时
function countDown(time) {
    $(".countdown .num").html(time)
    $(".countdown").css({"opacity":1,"display":"block"});
    $(".countdown .grab-count").addClass("count-active");
    if(time == 10){
        mp3List = ['time_tip_10.mp3'];
        audioMp3(mp3List).Play();
    }
    if(time < 9 && time > 0){
        mp3List = ['time.mp3'];
        audioMp3(mp3List).Play();
    }
    if(time<=0){
        mp3List = ['stop_2.mp3'];
        audioMp3(mp3List).Play();
        $(".countdown").css({"opacity":0,"display":"none"});
        $(".countdown .grab-count").removeClass("count-active");
        return;
    }
}
//播放声音
function audioMp3(mp3List){
    var mp3=new Object();
    mp3.mp3List=mp3List;
    mp3.url="/static/handle/mp3/";
    mp3.auto_play=false;
    mp3.loop=false;
    mp3.Play=function(){
        audio.src=this.url+this.mp3List[0];
        audio.play();
    }
    mp3.Muted=function(){
        audio.muted ? audio.muted = false : audio.muted = true;
    }
    mp3.volumeAdd=function(){
        if(audio.volume.toFixed(1)>=1){
            audio.volume=1
        }else{
            audio.volume = audio.volume + 0.1;
        }
    }
    mp3.volumeMinus=function(){
        if(audio.volume.toFixed(1)<=0){
            audio.volume=0
        }else{
            audio.volume = audio.volume - 0.1;
        }
    }
    return mp3;
}
//显示牌面
var showCard = function(showCard){
    $(".begincard").fadeIn(function(){
        $(".begincard .box").animate({"opacity":"1"});
        $(".table-info .nobegin-tip").fadeOut();
    });
    $.each(showCard,function(i,v){
        if(v.number!=false){
            var _thisdata={"status":true,round:v}
            Flop(_thisdata);
        }
    })
}
//是否显示补牌
function isShowSupport(isSupport){
    if(isSupport.is_bopai){
        if(isSupport.player_3 == 1){
			$('.begincard .player-card .draw .rotate').css("display","inline-block")
		}
        if(isSupport.banker_3 == 1){
			$('.begincard .banker-card .draw .rotate').css("display","inline-block")
		}
    } else {
        if (card_info.length <= 4) {
            $('.begincard .player-card .draw .rotate').css("display","none");
        }
        
    }
}
function Flop(data){
    var whichpoker='',pokerindex='',pokercard='';
    if(data.status==true){
        var which = data.round.position;
        if(game_id == 1){
            switch(which){
                case 11:
                    whichpoker='player-card';
                    pokerindex=1;
                    card_info["player_2"]=data.round.number;
                    break;
                case 12:
                    whichpoker='player-card';
                    pokerindex=0;
                    card_info["player_1"]=data.round.number;
                    break;
                case 13:
                    whichpoker='player-card';
                    pokerindex=2;
                    card_info["player_3"]=data.round.number;
                    break;
                case 21:
                    whichpoker='banker-card';
                    pokerindex=1;
                    card_info["banker_2"]=data.round.number;
                    break;
                case 22:
                    whichpoker='banker-card';
                    pokerindex=0;
                    card_info["banker_1"]=data.round.number;
                    break;
                case 23:
                    whichpoker='banker-card';
                    card_info["banker_3"]=data.round.number;
                    pokerindex=2;
                    break;
            }
        }else{
            switch(which){
                case 11:
                    whichpoker='player-card';
                    pokerindex=0;
                    card_info["player_1"]=data.round.number;
                    break;
                case 21:
                    whichpoker='banker-card';
                    pokerindex=0;
                    card_info["banker_1"]=data.round.number;
                    break;
            }
        }

        if(game_id==1){
            let support = isBopai(card_info);
            isShowSupport(support);
        }
        pokercard = data.round.card;
        var $poker = $('.begincard '+'.'+ whichpoker+' .card');
        var pokersrc="/static/handle/faces/"+pokercard+".svg";
        if(pokercard<200){
            var color="#000"
        }else if(pokercard<300){
            var color="#f13b3d"
        }else if(pokercard<400){
            var color="#000"
        }else if(pokercard<500){
            var color="#f13b3d"
        }
        if(data.round.number == 1){
            data.round.number = "A";
        }
        if(data.round.number == 11){
            data.round.number = "J";
        }
        if(data.round.number == 12){
            data.round.number = "Q";
        }
        if(data.round.number == 13){
            data.round.number = "K";
        }
        $poker.eq(pokerindex).find(".topleft").html(data.round.number);
        $poker.eq(pokerindex).find(".bottomright").html(data.round.number);
        $poker.eq(pokerindex).find(".topleft").css("color",color);
        $poker.eq(pokerindex).find(".bottomright").css("color",color);

        if(pokerindex==2){
            $('.begincard '+'.'+ whichpoker +' .draw .rotate').css("display","inline-block");
            $poker.eq(pokerindex).addClass("begin");
            $poker.eq(pokerindex).find(".face").css("background-image","url("+pokersrc+")");
            $(".begincard .banker-card .draw .text").css("text-align","left");
            $(".begincard .player-card .draw .text").css("text-align","right");
        }else{
            $poker.eq(pokerindex).addClass("begin");
            $poker.eq(pokerindex).find(".face").css("background-image","url("+pokersrc+")");
        }
    }
}
//百家乐判断是否要博牌
function isBopai(card_info){
    card_info["length"]=0;
    for( var i in card_info) { card_info["length"]++; }
    var bopai_info = Array(3);
    if(card_info.length<4){
        bopai_info['is_bopai'] = false;
        bopai_info['banker_3'] = 0;
        bopai_info['player_3'] = 0;
        card_info=[];
        return bopai_info;
    }
    else {
        if (card_info['banker_1'] > 10) {
            card_info['banker_1'] = 10;
        }
        if (card_info['banker_2'] > 10) {
            card_info['banker_2'] = 10;
        }
        if (card_info['banker_3'] > 10) {
            card_info['banker_3'] = 10;
        }
        if (card_info['player_1'] > 10) {
            card_info['player_1'] = 10;
        }
        if (card_info['player_2'] > 10) {
            card_info['player_2'] = 10;
        }
        if (card_info['player_3'] > 10) {
            card_info['player_3'] = 10;
        }
        var card_length = card_info.length;
        var banker_result = (card_info['banker_1'] + card_info['banker_2']) % 10;
        var player_result = (card_info['player_1'] + card_info['player_2']) % 10;
        if (card_length == 4) {
            if (player_result == 8 || player_result == 9) {
                bopai_info['is_bopai'] = false;
                bopai_info['banker_3'] = 0;
                bopai_info['player_3'] = 0;

            }
            else if (banker_result == 8 || banker_result == 9) {
                bopai_info['is_bopai'] = false;
                bopai_info['banker_3'] = 0;
                bopai_info['player_3'] = 0;
            }
            else if (player_result == 0 || player_result == 1 || player_result == 2 || player_result == 3 || player_result == 4 || player_result == 5) {
                bopai_info['is_bopai'] = true;
                bopai_info['banker_3'] = 0;
                bopai_info['player_3'] = 1;

            }
            else if (banker_result == 0 || banker_result == 1 || banker_result == 2 || banker_result == 3 || banker_result == 4 || banker_result == 5) {
                bopai_info['is_bopai'] = true;
                bopai_info['banker_3'] = 1;
                bopai_info['player_3'] = 0;

            }
            else if (player_result == 6 || player_result == 7) {
                bopai_info['is_bopai'] = false;
                bopai_info['banker_3'] = 0;
                bopai_info['player_3'] = 0;

            }
        }
        else if (card_length == 5) {
            if (card_info['player_3'] > 0) {
                if (banker_result == 0 || banker_result == 1 || banker_result == 2) {
                    bopai_info['is_bopai'] = true;
                    bopai_info['banker_3'] = 1;
                    bopai_info['player_3'] = 0;
                }
                else if (banker_result == 3) {
                    if (card_info['player_3'] == 1 || card_info['player_3'] == 2 || card_info['player_3'] == 3 || card_info['player_3'] == 4 || card_info['player_3'] == 5 || card_info['player_3'] == 6 || card_info['player_3'] == 7 || card_info['player_3'] == 9 || card_info['player_3'] == 10) {
                        bopai_info['is_bopai'] = true;
                        bopai_info['banker_3'] = 1;
                        bopai_info['player_3'] = 0;
                    }
                    else if (card_info['player_3'] == 8) {
                        bopai_info['is_bopai'] = false;
                        bopai_info['banker_3'] = 0;
                        bopai_info['player_3'] = 0;
                    }
                }
                else if (banker_result == 4) {
                    if (card_info['player_3'] == 2 || card_info['player_3'] == 3 || card_info['player_3'] == 4 || card_info['player_3'] == 5 || card_info['player_3'] == 6 || card_info['player_3'] == 7) {
                        bopai_info['is_bopai'] = true;
                        bopai_info['banker_3'] = 1;
                        bopai_info['player_3'] = 0;
                    }
                    else if (card_info['player_3'] == 1 || card_info['player_3'] == 8 || card_info['player_3'] == 9 || card_info['player_3'] == 10) {
                        bopai_info['is_bopai'] = false;
                        bopai_info['banker_3'] = 0;
                        bopai_info['player_3'] = 0;
                    }
                }
                else if (banker_result == 5) {
                    if (card_info['player_3'] == 4 || card_info['player_3'] == 5 || card_info['player_3'] == 6 || card_info['player_3'] == 7) {
                        bopai_info['is_bopai'] = true;
                        bopai_info['banker_3'] = 1;
                        bopai_info['player_3'] = 0;

                    }
                    else  if (card_info['player_3'] == 1 || card_info['player_3'] == 2 || card_info['player_3'] == 3 || card_info['player_3'] == 8 || card_info['player_3'] == 9 || card_info['player_3'] == 10) {
                        bopai_info['is_bopai'] = false;
                        bopai_info['banker_3'] = 0;
                        bopai_info['player_3'] = 0;
                    }
                }
                else if (banker_result == 6) {
                    if (card_info['player_3'] == 6 || card_info['player_3'] == 7) {
                        bopai_info['is_bopai'] = true;
                        bopai_info['banker_3'] = 1;
                        bopai_info['player_3'] = 0;
                    }
                    else if (card_info['player_3'] == 1 || card_info['player_3'] == 2 || card_info['player_3'] == 3 || card_info['player_3'] == 4 || card_info['player_3'] == 5 || card_info['player_3'] == 8 || card_info['player_3'] == 9 || card_info['player_3'] == 10) {
                        bopai_info['is_bopai'] = false;
                        bopai_info['banker_3'] = 0;
                        bopai_info['player_3'] = 0;
                    }
                }
                else if (banker_result == 7) {
                    bopai_info['is_bopai'] = false;
                    bopai_info['banker_3'] = 0;
                    bopai_info['player_3'] = 0;
                }
            } else {
                bopai_info['is_bopai'] = false;
                bopai_info['banker_3'] = 0;
                bopai_info['player_3'] = 0;
            }
        }
        card_info=[];
        return bopai_info;
    }
}
var showCardNn = function(data){
	$(".begincard").fadeIn(function(){
		$(".begincard .box").animate({"opacity":"1"});
		$(".begincard .box1").animate({"top":"100%","opacity":"1"});
		$(".begincard .box2").animate({"top":"100%","opacity":"1"});
		$(".begincard .box3").animate({"top":"100%","opacity":"1"});
		$(".begincard .box4").animate({"top":"100%","opacity":"1"});
	});
	card_number_info = data;
	if(card_number_info.length > 0){
		for(var i=0;i<card_number_info.length;i++){
			if(card_number_info[i]['order_num'] == 0){
				pokercard=card_number_info[i]['card'];
				pokersrc="/static/poker/"+pokercard+".png";
				$('.begincard .position-card .card').css("opacity",1);
				$('.begincard .position-card .card').find(".face").css("background-image","url("+pokersrc+")");
			}else{
				pokercard=card_number_info[i]['card'];
				order_num = card_number_info[i]['order_num'];
				card_cow = card_number_info[i]['order_num'].substring(0,1);
				card_list = card_number_info[i]['order_num'].substring(1,2) - 1;
				if(card_cow == 1){
					box_name = 'player-1-card';
					if(card_number_info[i]['result']){
						$('.player_1_result').html(card_number_info[i]['result']);
					}
				}else if(card_cow == 2){
					box_name = 'player-2-card';
					if(card_number_info[i]['result']){
						$('.player_2_result').html(card_number_info[i]['result']);
					}
				}else if(card_cow == 3){
					box_name = 'player-3-card';
					if(card_number_info[i]['result']){
						$('.player_3_result').html(card_number_info[i]['result']);
					}
				}else if(card_cow == 4){
					box_name = 'banker-card';
					if(card_number_info[i]['result']){
						$('.banker_result').html(card_number_info[i]['result']);
					}
				}
				$poker=$('.begincard '+'.'+ box_name+' .card');
				pokersrc="/static/poker/"+pokercard+".png";
				$poker.eq(card_list).find(".face").css("background-image","url("+pokersrc+")")
				$('.begincard '+'.'+ box_name).find(".card").eq(card_list).css('opacity',1);
			}
		}
	}
}
 // 桌子状态
var setBetStatus = function (BetStatus){
    if(game_id == 5||game_id == 4){
        if(BetStatus.rob_status != undefined && BetStatus.rob_status>=0){
            $('#number_rob_status').val(BetStatus.rob_status);
        }
    }
    $('#number_tab_status').val(BetStatus.bet_status);
    if(BetStatus.bet_status==2){
        if (game_id == 6){
            $('.nobegin-tip').html("");
            $('#show-status-span').html("");
            showToningBox();
        } else if(game_id == 7){
            $('.nobegin-tip').html("");
            $('#show-status-span').html("");
            showDiceBox();
        } else {
            $(".begincard").fadeIn(function(){
                if(game_id==1||game_id==2){
                    $(".begincard .box").animate({"opacity":"1"});
                    $(".table-info .nobegin-tip").fadeOut();
                }else if(game_id==4||game_id==5){
                    $(".begincard .box").animate({"opacity":"1"});
                    $(".begincard .box1").animate({"top":"100%","opacity":"1"});
                    $(".begincard .box2").animate({"top":"100%","opacity":"1"});
                    $(".begincard .box3").animate({"top":"100%","opacity":"1"});
                    $(".begincard .box4").animate({"top":"100%","opacity":"1"});
                }
                $('.nobegin-tip').html("");
                $('#show-status-span').html(lang[BetStatus.bet_msg]);
            });
        }
    }else if(BetStatus.bet_status==1){
        $('.nobegin-tip').html(lang[BetStatus.bet_msg]);
        $('#show-status-span').html("");
    }else{
        $('.nobegin-tip').html(lang[BetStatus.bet_msg]);
        $('#show-status-span').html("");
        if(game_id == 5||game_id == 4){
            if(BetStatus.rob_status == 1){
               if(BetStatus.rob_status>=0){
                    $('#number_rob_status').val(BetStatus.rob_status);
                }
                $('.nobegin-tip').html('抢庄中');
            }else if(BetStatus.rob_status == 2){
                if(BetStatus.rob_status>=0){
                    $('#number_rob_status').val(BetStatus.rob_status);
                }
                $('.nobegin-tip').html('抢庄结束,开始下注');
            }
        }
    }
};
// 获取桌子数据
var setNumberInfo = function (round){
    number_tab_id = round.number_tab_id
    $('#boot_num').html(round.boot_num);
    $('#number').html(round.number_tab_number);
    $('#boot_id').val(round.boot_id);
};
// 重置下注数目
var clearBetAmount = function (){
    $('#banker_amount').html(0);
    $('#player_amount').html(0);
    $('#tie_amount').html(0);
    $('#banker_pair_amount').html(0);
    $('#player_pair_amount').html(0);
    $('#all_amount').html(0);
};
//修改或者删除录单后从新获取number
var getNumber = function (){
    var query = new Object();
    query.number_tab_id = number_tab_id;
    $.ajax({
        url:"/index/get_number",
        type:"POST",
        dataType:"JSON",
        data:query,
        async:false,
        success:function(data){
            if(data.status == 1){
                $('#number').html(data.data);
            }
        }
    })
};
function nextAudio(){
    num+=1
    if(num<mp3List.length){
        audio.src="/static/handle/mp3/"+mp3List[num];
        audio.play();
    }else{
        audio.pause();
        audio.currentTime = 0.0;
        num=0;
    }
}
function countDownRob(time) {
    var table_id = $('#table_id').val();
    $(".countdown .num").html(time);
    $(".countdown").css({"opacity":1,"display":"block"});
    $(".countdown .grab-count").addClass("count-active");
    //$(".countdown").fadeIn();
    if(time < 5 && time > 0){
        mp3List = ['time.mp3'];
        audioMp3(mp3List).Play();
    }
    if(time<=0){
       // mp3List = ['end_rob.mp3'];
       // audioMp3(mp3List).Play();
        $(".countdown").css({"opacity":0,"display":"none"});
        $(".countdown .grab-count").removeClass("count-active");
        webSocket.send('{"connect":"space","mode":"endRob","number_tab_id":"'+parseInt(number_tab_id)+'","table_id":"'+parseInt(table_id)+'"}');
        return;
    }
}
function getTime() {
    var today = new Date();
    var h = today.getHours();
    var minute = today.getMinutes()
    var s = today.getSeconds();
    if (h < 10) {
        h = "0" + h;
    }
    if (minute < 10) {
        minute = "0" + minute;
    }
    if (s < 10) {
        s = "0" + s;
    }
    if(lang.lang == 'en-us'){
        var strDate = new Date();
        strDate = strDate.toDateString()
        strDate += " " + h + ":" + minute + ":" + s;
    }else if(lang.lang == 'zh-cn'){
        var strDate = (" " + today.getFullYear() + "年" + (today.getMonth() + 1) + "月" + today.getDate() + "日" + h + ":" + minute + ":" + s);
    }else if(lang.lang == 'zh-tw'){
        var strDate = (" " + today.getFullYear() + "年" + (today.getMonth() + 1) + "月" + today.getDate() + "日" + h + ":" + minute + ":" + s);
    }
    var n_day = today.getDay();
    switch (n_day) {
        case 0:
            var week = lang.sunday;
            break;
        case 1:
            var week = lang.monday;
            break;
        case 2:
            var week = lang.tuesday;
            break;
        case 3:
            var week = lang.wednesday;
            break;
        case 4:
            var week = lang.thursday;
            break;
        case 5:
            var week = lang.friday;
            break;
        case 6:
            var week = lang.saturday;
            break;
        case 7:
            var week = lang.sunday;
            break;
    }
    $('.date .weekend').html(week);
    $('.date .time').html(strDate);
}
// 请求所有路单数据，执行画布刷新
function waybillFunc(){
    var data = new Object;
    data.boot_id = $('#boot_id').val();
    data.game_id = game_id;
    var url=""
    if(game_id==1||game_id==2){url="/index/waybill"}
    else if(game_id==4||game_id==5){url="/index/waybill_nn"}
    else if(game_id==6){url="/index/waybill_toning"}
    $.ajax({
        url:url,
        type:"POST",
        dataType:"JSON",
        data:data,
        success:function(data){
            ludan = data;
            requestData(ludan);
        }
    });
}
function title(ctb,unit,x,y,type){
    ctb.beginPath();
    ctb.lineWidth = 0.5;
    ctb.strokeStyle = "#000";
    var radius=unit/2||0;
    if(type==1){
        fonts= 'Banker';
        var font_color = '#b20a00';
    }else if(type==2){
        fonts= 'P1';
        var font_color = '#0543bc';
    }else if(type==3){
        fonts= 'P2';
        var font_color = '#0543bc';
    }else if(type==4){
        fonts= 'P3';
        var font_color = '#0543bc';
    }
    if(type == 1){
        var color = '#ffad97';
    }else{
        var color = '#73d8f7';
    }
    //背景色
    ctb.fillStyle = color ; // 颜色
    ctb.fillRect(x,(y-1)*unit,unit*2-1,unit-0.5);
    ctb.fill();
    //文字
    ctb.font=unit*0.5+"px Arial";//字的大小
    ctb.fillStyle = font_color ; // 颜色
    ctb.textAlign = 'center'; //字的位置
    ctb.textBaseline = 'middle';
    ctb.fillText(fonts,radius+unit*(x/2),radius+unit*(y-1));
    ctb.stroke();
}
function requestData(data,ask,askroad){
    var ask=ask||false;
    var askroad=askroad||{
            "askshowroad":false,
            "askbigRoad":false,
            "askbigEyeRoad":false,
            "askpathway":false,
            "askroach":false,
        };
    bigH=$(".canvas-box.big").height();
    bigW=$(".canvas-box.big").width();
    // 计算单位
    unitbig=bigH/6;
    // 计算列个数
    colbig=Math.floor(bigW/unitbig);
    if(game_id==1){ CanvasTable("#canvas3",unitbig,6,colbig,data,ask,askroad);}
    else if(game_id==2){CanvasTableDt("#canvas3",unitbig,6,colbig,data,ask,askroad);}
    else if(game_id==4||game_id==5){
        unitbig=bigH/8;
        colbig=Math.floor(bigW/unitbig);
        if(colbig%2 == 1){
            colbig = colbig - 1;
        }
        CanvasTableNn("#canvas3",unitbig,8,colbig,data);
    }else if(game_id==6){CanvasTableToning("#canvas3",unitbig,6,colbig,data,ask,askroad);}
}
/////百家乐珠路
function CanvasTable(Id,unit,rows,cols,data,ask,askroad){
    var width=unit*cols,
        height=unit*rows;

    $(Id).attr("width",width)
    $(Id).attr("height",height)
    var canvasId=$(Id);
    var ctb=canvasId[0].getContext('2d');
    ctb.lineWidth = 1;//线条宽度
    ctb.strokeStyle = "#919191";//线条颜色
    ctb.beginPath();
    ctb.moveTo(0, 0.5);
    ctb.lineTo(width, 0.5);
    for (var i = 0; i <= rows; i++) {
        ctb.moveTo(0, unit*i);
        ctb.lineTo(width, unit*i);
    }
    ctb.closePath()
    ctb.stroke();
    ctb.beginPath();
    ctb.moveTo(0.5, 0);
    ctb.lineTo(0.5, height);
    for (var j = 1; j <= cols; j++) {
        ctb.moveTo(unit*j,0);
        ctb.lineTo(unit*j,height);
    }
    ctb.closePath()
    ctb.stroke();
    if(data.status){
        switch(true){
            // 判断是否滚动
            case Id=="#canvas3":
                var showRoad=data.waybill.showRoad;
                if(showRoad!=''){
                    var roadType="showWay"
                    cutRoad(roadType,ctb,unit,showRoad,cols,ask,askroad.askshowroad);

                }
                break;
        }
    }
}
//龙虎珠路
function CanvasTableDt(Id,unit,rows,cols,data,ask,askroad){
    var width=unit*cols,
        height=unit*rows;

    $(Id).attr("width",width)
    $(Id).attr("height",height)
    var canvasId=$(Id);
    var ctb=canvasId[0].getContext('2d');
    ctb.lineWidth = 1;//线条宽度
    ctb.strokeStyle = "#919191";//线条颜色
    ctb.beginPath();
    ctb.moveTo(0, 0.5);
    ctb.lineTo(width, 0.5);
    for (var i = 0; i <= rows; i++) {
        ctb.moveTo(0, unit*i);
        ctb.lineTo(width, unit*i);
    }
    ctb.closePath()
    ctb.stroke();
    ctb.beginPath();
    ctb.moveTo(0.5, 0);
    ctb.lineTo(0.5, height);
    for (var j = 1; j <= cols; j++) {
        ctb.moveTo(unit*j,0);
        ctb.lineTo(unit*j,height);
    }
    ctb.closePath()
    ctb.stroke();
    if(data.status){
        switch(true){
            // 判断是否滚动
            case Id=="#canvas3":
                var showRoad=data.waybill.showRoad;
                if(showRoad!=''){
                    var roadType="showWay"
                    cutRoad(roadType,ctb,unit,showRoad,cols,ask,askroad.askshowroad);

                }
                break;
        }
    }
}
//色碟露珠
function CanvasTableToning(Id,unit,rows,cols,data,ask,askroad){
    var width=unit*cols,
        height=unit*rows;

    $(Id).attr("width",width)
    $(Id).attr("height",height)
    var canvasId=$(Id);
    var ctb=canvasId[0].getContext('2d');
    ctb.lineWidth = 1;//线条宽度
    ctb.strokeStyle = "#919191";//线条颜色
    ctb.beginPath();
    ctb.moveTo(0, 0.5);
    ctb.lineTo(width, 0.5);
    for (var i = 0; i <= rows; i++) {
        ctb.moveTo(0, unit*i);
        ctb.lineTo(width, unit*i);
    }
    ctb.closePath()
    ctb.stroke();
    ctb.beginPath();
    ctb.moveTo(0.5, 0);
    ctb.lineTo(0.5, height);
    for (var j = 1; j <= cols; j++) {
        ctb.moveTo(unit*j,0);
        ctb.lineTo(unit*j,height);
    }
    ctb.closePath()
    ctb.stroke();
    if(data.status){
        switch(true){
            // 判断是否滚动
            case Id=="#canvas3":
                var showRoad=data.waybill;
                if(showRoad!=''){
                    var roadType="showWay"
                    cutRoad(roadType,ctb,unit,showRoad,cols,ask,askroad.askshowroad);
                }
                break;
        }
    }
}
//牛牛珠路
function CanvasTableNn(Id,unit,rows,cols,data){

    var width=unit*cols,
        height=unit*rows;
    $(Id).attr("width",width)
    $(Id).attr("height",height)
    var canvasId=$(Id);
    var ctb=canvasId[0].getContext('2d');
    ctb.lineWidth = 1;//线条宽度
    ctb.strokeStyle = "#919191";//线条颜色
    ctb.beginPath();
    ctb.moveTo(0, 0.5);
    ctb.lineTo(width, 0.5);
    for (var i = 0; i <= rows; i++) {
        ctb.moveTo(0, unit*i);
        ctb.lineTo(width, unit*i);
    }
    ctb.closePath()
    ctb.stroke();
    ctb.beginPath();
    ctb.moveTo(0.5, 0);
    ctb.lineTo(0.5, height);
    for (var j = 1; j <= cols; j++) {
        ctb.moveTo(unit*j*2,0);
        ctb.lineTo(unit*j*2,height);
    }
    ctb.closePath()
    ctb.stroke();

    ctb.beginPath();
    ctb.lineWidth = 1.5;//线条宽度
    ctb.strokeStyle = "#000";//线条颜色
    ctb.moveTo(0, unit*4);
    ctb.lineTo(width, unit*4);
    ctb.moveTo(0, unit*8);
    ctb.lineTo(width, unit*8);
    ctb.closePath()
    ctb.stroke();
    title(ctb,unit,1,1,1);
    title(ctb,unit,1,2,2);
    title(ctb,unit,1,3,3);
    title(ctb,unit,1,4,4);
    title(ctb,unit,1,5,1);
    title(ctb,unit,1,6,2);
    title(ctb,unit,1,7,3);
    title(ctb,unit,1,8,4);
    // title(ctb,unit,1,9,1);
    // title(ctb,unit,1,10,2);
    // title(ctb,unit,1,11,3);
    // title(ctb,unit,1,12,4);
    cutRoadNn(ctb,unit,data.waybill,cols);
}
// 前端路单数据截取
function cutRoad(roadType,ctb,unit,roadData,cols,ask,askroad){
    var L=roadData.length;
    var new_roadData=[];
    var Tab=0
    if(roadType=="showWay"||roadType=="bigWay"){
        if(ask&&askroad){
            Tab=cols;
        }else{
            Tab=cols-1;
        }
    }else{
        if(ask&&askroad){
            Tab=cols-1;
        }else{
            Tab=cols-2;
        }
    }
    var start_x=cols/2+0.25;
    if(L>=1){
        var last_x=roadData[L-1].show_x
        if(last_x>Tab){
            var cut=last_x-Tab
            $.each(roadData,function(i,v){
                if(v.show_x>cut){
                    new_roadData.push(v)
                }
            })
        }else{
            new_roadData=roadData;
            cut=0;
        }
    }else{
        new_roadData=roadData;
        cut=0;
    }
    $.each(new_roadData,function(i,v){
        if(roadType=="showWay"){
            SoloPath(ctb,unit,v.show_x-cut,v.show_y,v.result,v.pair)
        }
    })
}
////nn 前端路单数据截取
function cutRoadNn(ctb,unit,data,cols){
    var L=data.length/4;
    var new_roadData=[];
    var Tab=0;
    last_x = (cols/2-1)*2-1;
    if(L > (cols/2-1)*2-1){
        var cut = L - last_x;
        $.each(data,function(i,v){
            if(v.show_x>cut){
                new_roadData.push(v)
            }
        })
        $.each(new_roadData,function(i,v){
            v.show_x = v.show_x - cut;
            if(v.show_x<=(cols/2-1)){
                if(game_id == 4){
                    showPath(ctb,unit,v.show_x,v.show_y,v.type,v.result,v.is_win);
                }else if(game_id == 5){
                    showPath_tc(ctb,unit,v.show_x,v.show_y,v.type,v.result,v.is_win);
                }
            }else if(v.show_x<=cols-2){
                if(game_id == 4){
                    showPath(ctb,unit,v.show_x-(cols/2)+1,v.show_y+4,v.type,v.result,v.is_win);
                }else if(game_id == 5){
                    showPath_tc(ctb,unit,v.show_x-(cols/2)+1,v.show_y+4,v.type,v.result,v.is_win);
                }   
            }
        })
    }else{
        if(data){
            $.each(data,function(i,v){
                if(v.show_x<=(cols/2-1)){
                    if(game_id == 4){
                        showPath(ctb,unit,v.show_x,v.show_y,v.type,v.result,v.is_win);
                    }else if(game_id == 5){
                        showPath_tc(ctb,unit,v.show_x,v.show_y,v.type,v.result,v.is_win);
                    }
                }else if(v.show_x<=cols-2){
                    if(game_id == 4){
                        showPath(ctb,unit,v.show_x-(cols/2)+1,v.show_y+4,v.type,v.result,v.is_win);
                    }else if(game_id == 5){
                        showPath_tc(ctb,unit,v.show_x-(cols/2)+1,v.show_y+4,v.type,v.result,v.is_win);
                    }   
                }
            })
        }
    }
}
// 局数 数，文字X坐标，文字Y坐标，文字大小风格
function Font_tie(ctb,num,Font_x,Font_y,fontsize){
    if(num!==undefined){
        ctb.beginPath();
        ctb.font=fontsize;
        ctb.textAlign = 'center';
        ctb.textBaseline = 'middle';
        ctb.fillStyle ="#242424";
        ctb.fillText(num,Font_x,Font_y);
        ctb.stroke();
    }
}
function SoloPath(ctb,unit,x,y,type,corners){
    ctb.beginPath();
    ctb.lineWidth = 0.5;
    ctb.strokeStyle = "#000";
    var radius=unit/2||0;
    if (game_id == 6){
        if(type==0){
            var color='#5A5A5A';
            var fonts="0";
            ctb.strokeStyle = "#5A5A5A";
        }else if(type==1){
            var color='#5495F4';
            var fonts="1";
            ctb.strokeStyle = "#5495F4";
        }else if(type==2){
            var color='#70B252';
            var fonts="2";
            ctb.strokeStyle = "#70B252";
        }else if(type==3){
            var color='#F4BB4C';
            var fonts="3";
            ctb.strokeStyle = "#F4BB4C";
        }else if(type==4){
            var color='#E35C4C';
            var fonts="4";
            ctb.strokeStyle = "#E35C4C";
        }
    } else {
        if(type==1){
            var color='#ff002a';
            var fonts="";
            if(game_id==1){fonts=lang.banker;}
            else if(game_id==2){  fonts=lang.dragon;}
            ctb.strokeStyle = "#ff4a68";
        }else if(type==2){
            var color='#3a38f0';
            var fonts="";
            if(game_id==1){fonts=lang.player;}
            else if(game_id==2){  fonts=lang.tiger;}
            ctb.strokeStyle = "#7e7df6";
        }else if(type==3){
            var color='#44d024';
            var fonts="";
            if(game_id==1){fonts=lang.tie;}
            else if(game_id==2){  fonts=lang.tie;}
            ctb.strokeStyle = "#71df57";
        }
    }

    ctb.arc(radius+unit*(x-1), radius+unit*(y-1), unit*0.45, 0, Math.PI * 2);
    ctb.fillStyle=color;
    ctb.fill();
    ctb.font=unit*0.6+"px Arial";
    ctb.fillStyle ="#fff" ; // 颜色
    ctb.textAlign = 'center';
    ctb.textBaseline = 'middle';
    ctb.fillText(fonts,radius+unit*(x-1),radius+unit*(y-1));
    ctb.stroke();
    var corner_xy=unit/3.5
    if(corners==1){
        corner(ctb,unit,x,y,corner_xy,'#ff2202');
    }else if(corners==2){
        corner(ctb,unit,x,y,-corner_xy,'#0337ff');
    }else if(corners==3){
        corner(ctb,unit,x,y,corner_xy,'#ff2202');
        corner(ctb,unit,x,y,-corner_xy,'#0337ff');
    }
}
//角标
function corner(ctb,unit,x,y,corner_xy,corner_color){
    var radius=unit/2
    ctb.beginPath();
    ctb.lineWidth = 0.5;
    ctb.strokeStyle = "#fff";
    ctb.arc(radius+unit*(x-1)-corner_xy, radius+unit*(y-1)-corner_xy, unit*0.13, 0, Math.PI * 2);
    ctb.fillStyle=corner_color;
    ctb.fill();
    ctb.stroke();
}
/*牛牛*/
function showPath(ctb,unit,x,y,type,result,is_win){
    ctb.beginPath();
    ctb.lineWidth = 0.5;
    ctb.strokeStyle = "#000";
    var radius=unit/2||0;
    if(type==1){
        var font_color = '#b20a00';
    }else{
        var font_color = '#1e14d3';
    }
    if(result == 0){
        var fonts = 'N0';
    }else if(result == 1){
        var fonts = 'N1';
    }else if(result == 2){
        var fonts = 'N2';
    }else if(result == 3){
        var fonts = 'N3';
    }else if(result == 4){
        var fonts = 'N4';
    }else if(result == 5){
        var fonts = 'N5';
    }else if(result == 6){
        var fonts = 'N6';
    }else if(result == 7){
        var fonts = 'N7';
    }else if(result == 8){
        var fonts = 'N8';
    }else if(result == 9){
        var fonts = 'N9';
    }else if(result == 10){
        var fonts = 'NN';
    }else if(result == 11){
        var fonts = 'WG';
    }
    //背景色
    if(is_win == 1){
        if(type == 1){
            ctb.fillStyle = '#b20a00' ; // 颜色
        }else{
            ctb.fillStyle = '#1e14d3' ; // 颜色
        }
        ctb.fillRect(unit*x*2,unit*(y-0.25),unit*2,unit*0.25);
        ctb.fill();
        win(ctb,unit,x,y);
    }
    //文字
    ctb.font=unit*0.45+"px Arial";//字的大小
    ctb.fillStyle = font_color ; // 颜色
    ctb.textAlign = 'center'; //字的位置
    ctb.textBaseline = 'middle';
    ctb.fillText(fonts,2*x*unit+unit,radius+unit*(y-1));
    ctb.stroke();
}
/*三卡牛牛*/
function showPath_tc(ctb,unit,x,y,type,result,is_win){
    ctb.beginPath();
    ctb.lineWidth = 0.5;
    ctb.strokeStyle = "#000";
    var radius=unit/2||0;
    if(type==1){
        var font_color = '#b20a00';
    }else{
        var font_color = '#1e14d3';
    }
    if(result == 1){
        var fonts = '牛1';
    }else if(result == 2){
        var fonts = '牛2';
    }else if(result == 3){
        var fonts = '牛3';
    }else if(result == 4){
        var fonts = '牛4';
    }else if(result == 5){
        var fonts = '牛5';
    }else if(result == 6){
        var fonts = '牛6';
    }else if(result == 7){
        var fonts = '牛7';
    }else if(result == 8){
        var fonts = '牛8';
    }else if(result == 9){
        var fonts = '牛9';
    }else if(result == 10){
        var fonts = '牛牛';
    }else if(result == 11){
        var fonts = '豹子';
    }else if(result == 12){
        var fonts = '同花顺';
    }else if(result == 13){
        var fonts = '皇家同花顺';
    }
    //背景色
    if(is_win == 1){
        if(type == 1){
            ctb.fillStyle = '#b20a00' ; // 颜色
        }else{
            ctb.fillStyle = '#1e14d3' ; // 颜色
        }
        ctb.fillRect(unit*x*2,unit*(y-0.25),unit*2,unit*0.25);
        ctb.fill();
        win(ctb,unit,x,y);
    }
    //文字
    if(result == 13){
        ctb.font=unit*0.38+"px Arial";//字的大小
    }else{
        ctb.font=unit*0.45+"px Arial";//字的大小
    }
    
    ctb.fillStyle = font_color ; // 颜色
    ctb.textAlign = 'center'; //字的位置
    ctb.textBaseline = 'middle';
    ctb.fillText(fonts,2*x*unit+unit,radius+unit*(y-1));
    ctb.stroke();
}
function win(ctb,unit,x,y){
    ctb.beginPath();
    ctb.lineWidth = 0.5;
    ctb.strokeStyle = "#000";
    var radius=unit/2||0;
    fonts = 'WIN';
    ctb.font=unit*0.25+"px Arial";//字的大小
    ctb.fillStyle = '#fff' ; // 颜色
    ctb.textAlign = 'center'; //字的位置
    ctb.textBaseline = 'middle';
    ctb.fillText(fonts,2*x*unit+unit,unit*(y-0.11));
    ctb.stroke();
}
function flop_position(data){
    pokercard=data.round.card;
    pokersrc="/static/poker/"+pokercard+".png";
    $('.begincard .position-card .card').css("opacity",1);
    $('.begincard .position-card .card').find(".face").css("background-image","url("+pokersrc+")");
    pokercard = parseInt(pokercard);
    var _position = (pokercard % 100) % 4;
    switch (_position) {
        case 0: 
            $('.box1').css("background-color","rgba(226, 212, 71, 0.5)");
            $('.box2').css("background-color","rgba(0, 0, 0, 0.5)");
            $('.box3').css("background-color","rgba(0, 0, 0, 0.5)");
            $('.box4').css("background-color","rgba(0, 0, 0, 0.5)");
            break;
        case 1:
            $('.box2').css("background-color","rgba(226, 212, 71, 0.5)");
            $('.box1').css("background-color","rgba(0, 0, 0, 0.5)");
            $('.box3').css("background-color","rgba(0, 0, 0, 0.5)");
            $('.box4').css("background-color","rgba(0, 0, 0, 0.5)");
            break;
        case 2: 
            $('.box3').css("background-color","rgba(226, 212, 71, 0.5)");
            $('.box1').css("background-color","rgba(0, 0, 0, 0.5)");
            $('.box2').css("background-color","rgba(0, 0, 0, 0.5)");
            $('.box4').css("background-color","rgba(0, 0, 0, 0.5)");
            break;
        case 3: 
            $('.box4').css("background-color","rgba(226, 212, 71, 0.5)");
            $('.box1').css("background-color","rgba(0, 0, 0, 0.5)");
            $('.box2').css("background-color","rgba(0, 0, 0, 0.5)");
            $('.box3').css("background-color","rgba(0, 0, 0, 0.5)");
            break;
    }
}
function flop_card(data){
    order_num = data.round.order_num;
    card_cow = order_num.substring(0,1);
    card_list = order_num.substring(1,2) - 1;
    if(card_cow == 1){
        box_name = 'player-1-card';
        if(data.round.result){
            $('.player_1_result').html(data.round.result);
        }
    }else if(card_cow == 2){
        box_name = 'player-2-card';
        if(data.round.result){
            $('.player_2_result').html(data.round.result);
        }
    }else if(card_cow == 3){
        box_name = 'player-3-card';
        if(data.round.result){
            $('.player_3_result').html(data.round.result);
        }
    }else if(card_cow == 4){
        box_name = 'banker-card';
        if(data.round.result){
            $('.banker_result').html(data.round.result);
        }
    }
    if(40<order_num){
        $('.box1').css("background-color","rgba(226, 212, 71, 0.5)");
        $('.box2').css("background-color","rgba(0, 0, 0, 0.5)");
        $('.box3').css("background-color","rgba(0, 0, 0, 0.5)");
        $('.box4').css("background-color","rgba(0, 0, 0, 0.5)");
    }
    if(10<order_num && order_num<20){
        $('.box2').css("background-color","rgba(226, 212, 71, 0.5)");
        $('.box1').css("background-color","rgba(0, 0, 0, 0.5)");
        $('.box3').css("background-color","rgba(0, 0, 0, 0.5)");
        $('.box4').css("background-color","rgba(0, 0, 0, 0.5)");
    }
    if(20<order_num && order_num<30){
        $('.box3').css("background-color","rgba(226, 212, 71, 0.5)");
        $('.box1').css("background-color","rgba(0, 0, 0, 0.5)");
        $('.box2').css("background-color","rgba(0, 0, 0, 0.5)");
        $('.box4').css("background-color","rgba(0, 0, 0, 0.5)");
    }
    if(30<order_num && order_num<40){
        $('.box4').css("background-color","rgba(226, 212, 71, 0.5)");
        $('.box1').css("background-color","rgba(0, 0, 0, 0.5)");
        $('.box2').css("background-color","rgba(0, 0, 0, 0.5)");
        $('.box3').css("background-color","rgba(0, 0, 0, 0.5)");
    }
    pokercard=data.round.card;
    $poker=$('.begincard '+'.'+ box_name+' .card');
    pokersrc="/static/poker/"+pokercard+".png";
    $poker.eq(card_list).find(".face").css("background-image","url("+pokersrc+")")
    $('.begincard '+'.'+ box_name).find(".card").eq(card_list).css('opacity',1);
}

// 识别相关
function doScanCards() {
    var card = new Object();
    card.casinoTableId = casinoTableId;
    
    // 用局部变量
    var cardScanRecord = new Array();
    //var scanPosition = 1;
    
    //card.count = 6;
    
    var api = '/recognition';

    scanTask = setInterval(function() {
        console.log('scan cards start...' + scanPosition);
        card.index = scanPosition;

        //if(!stopScan){
            $.ajax({
                url: localSbServer + api,
                type: 'POST',
                dataType: 'JSON',
                data: JSON.stringify(card),
                success: function(data) {
                    if (data.code == '2000') {
                        console.log(data.poker);
                        var query = new Object();

                        if (!data.poker.includes('n')) {
                            var poker = formatCardData(data.poker);
                                
                            if (cardScanRecord[card.index] === undefined) {
                                var _cardRecord = new Object();
                                _cardRecord['card'] = poker;
                                _cardRecord['time'] = 1;
                                cardScanRecord[card.index] = _cardRecord;
                            } else {
                                _cardRecord = cardScanRecord[card.index];
                                if (_cardRecord['card'] == poker && _cardRecord['time'] >= 2) {
                                    query.card = poker; 
                                    query.position = position[card.index - 1];
                                    
                                    sendScanBaccarat(query);

                                } else {
                                    if (_cardRecord['card'] != poker) {
                                        _cardRecord['card'] = poker;
                                        _cardRecord['time'] = 1;
                                    } else {
                                         _cardRecord['time']++;
                                    }
                                    cardScanRecord[card.index] = _cardRecord;
                                }
                            }
                        }
                    }
                
                }
            });
        //}

    }, 250);

    console.log('scan cards stop...');
}

function doDtScanCards() {
    var card = new Object();
    card.casinoTableId = casinoTableId;
    
    // 用局部变量
    var cardScanRecord = new Array();
    //var scanPosition = 1;
    
    var dtPosition = [21, 11];
    
    card.count = 2;
    
    var api = '/recognition_multi';

    scanTask = setInterval(function() {
        console.log('scan cards start...');
        
        //if(!stopScan){
            $.ajax({
                url: localSbServer + api,
                type: 'POST',
                dataType: 'JSON',
                data: JSON.stringify(card),
                success: function(data) {
                    if (data.code == '2000') {
                        console.log(data.poker);
                        
                        // Dragon: 21
                        // Tiger: 11
                        
                        var cards = spCard(data.poker);
                        cards.forEach(function (v, k) {
                            var query = new Object();

                            if (!v.includes('n')) {
                                if (cardScanRecord[k] === undefined) {
                                    var _cardRecord = new Object();
                                    _cardRecord['card'] = v;
                                    _cardRecord['time'] = 1;
                                    cardScanRecord[k] = _cardRecord;
                                }  else {
                                    _cardRecord = cardScanRecord[k];
                                    if (_cardRecord['card'] == v && _cardRecord['time'] >= 2) {
                                        query.card = v; 
                                        query.position = dtPosition[k];
                                        
                                        sendScanDt(query);

                                    } else {
                                        if (_cardRecord['card'] != v) {
                                            _cardRecord['card'] = v;
                                            _cardRecord['time'] = 1;
                                        } else {
                                             _cardRecord['time']++;
                                        }
                                        cardScanRecord[k] = _cardRecord;
                                    }
                                }
                            }

                        });
                        
                    }
                
                }
            });
        //}

    }, 200);

    console.log('scan cards stop...');
}

function doNnScanPositionCard() {
    var card = new Object();
    card.casinoTableId = casinoTableId;
    card.index = 21; //先扫定位牌
    var cardScanRecord = new Array();

    var api = '/recognition';

    positionScanTask = setInterval(function() {
        console.log('scan postion[21] card start...postion:' + scanPosition);
        $.ajax({
            url: localSbServer + api,
            type: 'POST',
            dataType: 'JSON',
            data: JSON.stringify(card),
            success: function(data) {
                
                if (data.code == '2000') {
                    console.log(data.poker);
                    if (!data.poker.includes('n')) {
                        var poker = formatCardData(data.poker);
                        var query = new Object();
                        query.card = poker;
                        if (cardScanRecord[card.index] === undefined) {
                            var _cardRecord = new Object();
                            _cardRecord['card'] = poker;
                            _cardRecord['time'] = 1;
                            cardScanRecord[card.index] = _cardRecord;
                        } else {
                            _cardRecord = cardScanRecord[card.index];
                            if (_cardRecord['card'] == poker && _cardRecord['time'] >= 3) {
                            //if (true) {
                                if (scanPosition == 21) {
                                    query.position = 0;
                                    sendScanNn(query);

                                    positionCard = parseInt(poker);
                                    scanPosition = (positionCard % 100) % 4;
                                    switch (scanPosition) {
                                        case 2: 
                                            scanPosition = 6; 
                                            scanDefaultPosition = 'P2'; 
                                            $('.box3').css("background-color","rgba(226, 212, 71, 0.5)");
                                            break;
                                        case 3: 
                                            scanPosition = 11; 
                                            scanDefaultPosition = 'P3'; 
                                            $('.box4').css("background-color","rgba(226, 212, 71, 0.5)");
                                            break;
                                        case 0: 
                                            scanPosition = 16; 
                                            scanDefaultPosition = 'B'; 
                                            $('.box1').css("background-color","rgba(226, 212, 71, 0.5)");
                                            break;
                                        default: 
                                            scanPosition = 1; 
                                            scanDefaultPosition = 'P1'; 
                                            $('.box2').css("background-color","rgba(226, 212, 71, 0.5)");
                                            break;
                                    }

                                    isPositionScaned = true;

                                    console.log('scan postion[21] card end and sent ' + poker);
                                    clearInterval(positionScanTask);
                                    positionScanTask = null;
                                }
                            } else {
                                if (_cardRecord['card'] != poker) {
                                    _cardRecord['card'] = poker;
                                    _cardRecord['time'] = 1;
                                } else {
                                    _cardRecord['time']++;
                                }
                                cardScanRecord[card.index] = _cardRecord;
                            }
                        }

                    }
                }
            }
        });

    }, 100);
}

function doNnScanCards() {

    //var position = ['11', '12', '21', '22', '13', '23'];
    var card = new Object();
    card.casinoTableId = casinoTableId;
    //card.index = 21; //先扫定位牌

    var cardScanRecord = new Array();

    var api = '/recognition';

    scanTask = setInterval(function() {
        console.log('scan cards start...postion:' + scanPosition);

        if (!isPositionScaned || positionScanTask != null || scanPosition == 0) {
            console.log('定位牌未扫描。');
            return false;
        }
        card.index = scanPosition;

        $.ajax({
            url: localSbServer + api,
            type: 'POST',
            dataType: 'JSON',
            data: JSON.stringify(card),
            success: function(data) {
                if (data.code == '2000') {
                    console.log(data.poker);
                    if (!data.poker.includes('n')) {
                        var poker = formatCardData(data.poker);
                        var query = new Object();
                        query.card = poker; 

                        if (cardScanRecord[card.index] === undefined) {
                            var _cardRecord = new Object();
                            _cardRecord['card'] = poker;
                            _cardRecord['time'] = 1;
                            cardScanRecord[card.index] = _cardRecord; 
                        } else {
                            _cardRecord = cardScanRecord[card.index];
                            if (_cardRecord['card'] == poker && _cardRecord['time'] >= 3) {
                            //if (true) {
                                if (scanPosition == 21) {
                                    query.position = 0;
                                }
                                sendScanNn(query);
                            } else {
                                if (_cardRecord['card'] != poker) {
                                    _cardRecord['card'] = poker;
                                    _cardRecord['time'] = 1;
                                } else {
                                    _cardRecord['time']++;
                                }
                                cardScanRecord[card.index] = _cardRecord;
                            }
                        }
                        
                    }
                }
            }
        });
    }, 200);
    console.log('scan cards stop...');
}


function spCard(data) {
    var cc = data.split('_');
    cc.forEach(function (v, k) {
        if (!v.includes('n')) {
            cc[k] = formatCardData(v);
        }   
    });
    return cc;
}
function formatCardData(card) {
    // card: b-1
    var s = card.substr(0, 1);
    var c = card.substr(2, 1);
    var h = '';
    var n = '';
    switch(s) {
        case 'b':h = '1';break;
        case 'r':h = '2';break;
        case 'm':h = '3';break;
        default:h = '4';break;
    }
    switch(c) {
        case '1': n = '01'; break;
        case '2': n = '02'; break;
        case '3': n = '03'; break;
        case '4': n = '04'; break;
        case '5': n = '05'; break;
        case '6': n = '06'; break;
        case '7': n = '07'; break;
        case '8': n = '08'; break;
        case '9': n = '09'; break;
        case '0': n = '10'; break;
        case 'j': n = '11'; break;
        case 'q': n = '12'; break;
        default : n = '13'; break;
    }
    var result = h + n;
    return result;
}
function cardToServer(card) {
    // card: 3d

    if (card == '' || (card == undefined && card.length != 2)) {
        return 'None';
    }

    var s = card.substr(0, 1);
    s = s.toLowerCase();
    var c = card.substr(1, 1);
    var h = '';
    var n = ''; 
    switch(c) {
        case 's': h = '1'; break;
        case 'h': h = '2'; break;
        case 'c': h = '3'; break;
        default:  h = '4'; break;
    }
    switch(s) {
        case '1': n = '01'; break;
        case '2': n = '02'; break;
        case '3': n = '03'; break;
        case '4': n = '04'; break;
        case '5': n = '05'; break;
        case '6': n = '06'; break;
        case '7': n = '07'; break;
        case '8': n = '08'; break;
        case '9': n = '09'; break;
        case 't': n = '10'; break;
        case 'j': n = '11'; break;
        case 'q': n = '12'; break;
        case 'a': n = '01'; break;
        default : n = '13'; break;
    }

    var result = h + n;
    return result;
}
