var shotTypesLabels = { 
    "jump-shot": "ג'אמפ שוט",
    "lay-up": 'לייאפ', 
    "dunk": 'הטבעה' , 
    "tap-in": 'Tap-in' , 
    "allyhoop" : 'אלי-הופ' , 
    "driving-lay-up": 'Driving-lay-up',
    "hook-shot" : 'Hook-shot',
    'putback' : "Putback",
    'free-throw' : "זריקת עונשין",
}; 
var foulTypesLabels = { 
    "personal": 'אישית',
    "technical": 'טכנית', 
    "unsportsmanlike": 'בלתי ספורטיבית' , 
    "disqualifying": 'הרחקה', 
};
var turnoverTypesLabels = {
    "out-of-bounds":"חוץ",
    "bad-pass":"מסירה גרועה",
    "travelling":"צעדים",
    "ball-handling":"כידרור",
    "3-seconds-violation":"הפרת 3 שניות",
    "5-seconds-violation":"הפרת 5 שניות",
    "8-seconds-violation":"הפרת 8 שניות",
    "24-seconds-violation":"הפרת 24 שניות",
    "backcourt-violation":"הפרת חצי",
    "other" : "אחר",
    "turnover_other" : "מעבירת תוקף"
} 
var postdataGetGameInfo = {
    "jsonrpc": "2.0",
    "id":"42",
    "method":"getgameinfo",
    "params":{
        //"token":token,
        "gameId":game_id
    }
}
var postdataGetActions = {
    "jsonrpc": "2.0",
    "id":"42",
    "method":"getActions",
    "params":{
        //"token":token,
        "gameId":game_id
    }
}
var postdataGetBoxScores = {
    "jsonrpc": "2.0",
    "id":"42",
    "method":"boxscore",
    "params":{
        //"token":token,
        "gameId":game_id
    }
}          
var actions_translate = { 
    "substitution in": 'נכנס למגרש',
    "substitution out": 'יצא מהמגרש',
    "made": 'קלע',
    "missed": 'החטיא', 
    "blocked": 'נחסם', 
    "assist": 'מסר אסיסט' , 
    "team assist": 'אסיסט קבוצתי' , 
    "team": 'קבוצתי' , 
    "Team": '' ,
    "start of game" : 'תחילת משחק' , 
    "end of game": 'סיום משחק',
    "Q" : 'רבע',
    "Quarter" : 'רבע',
    'start of' : "תחילת",
    'end of' : "סיום",
    'points' : "נקודות",
    'Defensive Rebound' : 'ריבאונד הגנה',
    'Offensive Rebound' : 'ריבאונד התקפה',
    'Team Defensive Rebound' : 'ריבאונד הגנה קבוצתי',
    'Team Offensive Rebound' : 'ריבאונד התקפה קבוצתי',
    'take' : '',
    'Steal' : 'חטיפה',
    'did' : '',
    'Block' : 'חסימה',
    'Foul'   : 'עבירה',
    "offensive_foul" : 'עבירת תוקף',
    "Foul Drawn Team" : 'סחיטת עבירה קבוצתית',
    "Foul Drawn" : 'סחט עבירה',
    "Team Turnover" : "איבוד כדור קבוצתי",
    "Turnover" : "איבוד כדור",
    "Timeout" : "פסק זמן",
    "Commercial Timeout" : "פסק זמן (פרסומות)",
    "free-throw": "עונשין",
    "Bench" : "ספסל",
    "Coach" : "מאמן",
    "Deflection" : "דיפלקשן",
}; 
var currentQuarterSelection = 1;
var last_shot_score = "";
var homeFouls = [0,0,0,0];
var awayFouls = [0,0,0,0];
var ActionNum = 0;
var currentQuarter = 0;
var dic = JSON.parse('{"he":{"quarter":"\u05e8\u05d1\u05e2","quarters":"\u05e8\u05d1\u05e2\u05d9\u05dd","head coach":"\u05de\u05d0\u05de\u05df \u05e8\u05d0\u05e9\u05d9","No.":"#","Name":"\u05e9\u05dd","PTS":"\u05e0\u05e7","Min":"\u05d3\u05e7\u05d5\u05ea","FG":"\u05de\u05d4\u05e9\u05d3\u05d4","2P":"2 \u05e0\u05e7","3P":"3 \u05e0\u05e7","FT":"\u05e2\u05d5\u05e0\u05e9\u05d9\u05df","REB":"\u05e8\u05d9\u05d1\u05d0\u05d5\u05e0\u05d3\u05d9\u05dd","AST":"\u05d0\u05e1","TO":"\u05d0\u05d9\u05d1","STL":"\u05d7\u05d8","BLK":"\u05d7\u05e1\u05d9\u05de\u05d5\u05ea","FOULS":"\u05e2\u05d1\u05d9\u05e8\u05d5\u05ea","+\/-":"+\/-","TSP":"TSP","PIR":"\u05de\u05d3\u05d3","M\/A":"\u05d6\/\u05e7","OFF":"\u05d4\u05ea","DEF":"\u05d4\u05d2","TOT":"\u05e1\u05d4\u05db","BS":"\u05e9\u05dc","BA":"\u05e2\u05dc","PF":"\u05e9\u05dc","FD":"\u05e2\u05dc","Team":"\u05e7\u05d1\u05d5\u05e6\u05ea\u05d9","Total":"\u05e1\u05d4\u05db"},"en":{"quarter":"Quarter","quarters":"Quarter","head coach":"Head Coach","No.":"No.","Name":"Name","PTS":"PTS","Min":"Min","FG":"FG","2P":"2P","3P":"3P","FT":"FT","REB":"REB","AST":"AST","TO":"TO","STL":"STL","BLK":"BLK","FOULS":"FOULS","+\/-":"+\/-","TSP":"TSP","PIR":"PIR","M\/A":"M\/A","OFF":"OFF","DEF":"DEF","TOT":"TOT","BS":"BS","BA":"BA","PF":"PF","FD":"FD","Team":"Team","Total":"Total"}}');
function translate(key, def_dic = 'he')
{
return (dic[def_dic] && dic[def_dic][key.toLowerCase()]) ? dic[def_dic][key.toLowerCase()] : key;};
function clean_eng(key)
{
  key = key.replaceAll("_", " "); 
  key = key.replaceAll("-", " "); 
  return key;
}
function actions_translate_local(key)
{
    if(lang == 'he')
        return actions_translate[key];
    return clean_eng(key);
}
function shotTypesLabels_local(key)
{
    if(lang == 'he')
        return shotTypesLabels[key];
        
    if(key == "allyhoop")
        return "ally-hoop";
        
    return clean_eng(key);
}
function foulTypesLabels_local(key)
{
     if(lang == 'he')
        return foulTypesLabels[key];
    return clean_eng(key);
}
function turnoverTypesLabels_local(key)
{
    if(lang == 'he')
        return turnoverTypesLabels[key];
    if(key == 'turnover_other')
        return 'other';
        
    return clean_eng(key);
}
function getFullPlayerName(player)
{
    if(!player || player == null)
        return "";
    
    if(lang == 'he')
        return player.firstNameLocal + ' ' + player.lastNameLocal;
    else
        return player.firstName + ' ' + player.lastName;
    return key;
}
function transalteScore(score)
{
    if(!score || score == null || score.indexOf("-") <= 0)
        return "";
    
    if(lang == 'he')
        return score;
     
    var sa = score.split('-');
    if(!sa || sa.length != 2)
        return score;
         
    return sa[1] + "-" + sa[0];     
}
$(document).ready(function(){
    autoRefreshGameActions();
    autoRefreshBoxScores();
    //scoreline area Quarter navs
    $('.time-periods-div > ul > li').click(function(e){
        if( $(targetEle).attr('targetq') == undefined ){
            var targetQuarter = $(this).children('a').attr('targetq');
            currentQuarterSelection = (targetQuarter);
        }else{
            var targetEle = e.target;
            var targetQuarter = $(targetEle).attr('targetq');
            currentQuarterSelection = (targetQuarter);
        }
        // console.log($(targetEle).attr('targetq'))
        // console.log($(currentTargetEle).attr('targetq'))
        toggleQuarterActions();
    });
    
    var language_direction="rtl";
    var lcal_dir=localStorage.getItem('direction');
    
    /*
    if(lcal_dir=="ltr"){
        $('#language_change').prop('checked', true);
        //$("html").children().css("direction","ltr");
    }else{
        $('#language_change').prop('checked', false);
        //$("html").children().css("direction","rtl");
    } */
    
    $('#language_change').prop('checked', true);
    $("#language_change").change(function() {
        if ($('#language_change').is(':checked')) {
           //$("html").children().css("direction","ltr");
           localStorage.setItem('direction', 'ltr');
           localStorage.setItem('lang', 'en');
        }else{
            $("html").children().css("direction","rtl");
            localStorage.setItem('direction', 'rtl');
            localStorage.setItem('lang', 'he');
        }
        var lcal_lang=localStorage.getItem('lang');
        if(!(lcal_lang == 'he' || lcal_lang == 'en'))
            lcal_lang = 'he';
        
        var url = window.location.pathname+"?"+"game_id="+ game_id + "&lang="+ lcal_lang;
        window.location.href = url;
    });
    
});
function toggleQuarterActions(){
    $('.time-periods-div>ul>li').each(function(){
        $(this).removeClass('active');
        if( $(this).children('a').attr('targetq') == currentQuarterSelection )
            $(this).addClass('active');
    })
    $('.action-quarter-0').hide();
    $('.action-quarter-1').hide();
    $('.action-quarter-2').hide();
    $('.action-quarter-3').hide();
    $('.action-quarter-4').hide();
    $('.action-quarter-5').hide();
    $('.action-quarter-6').hide();
    $('.action-quarter-7').hide();
    $('.action-quarter-8').hide();
    $('.action-quarter-'+currentQuarterSelection).show();
    if(currentQuarterSelection == 1)
        $('.action-quarter-'+(currentQuarterSelection - 1)).show();
}
function populateGameInfo(data){
    $('#team1logo').attr('src' , './images/'+ data.result.gameInfo.homeTeam.id +'.png')
    if($('#team1name').html() == "")
        $('#team1name').html(lang=="en" ? data.result.gameInfo.homeTeam.name : data.result.gameInfo.homeTeam.nameLocal)
    $('#team2logo').attr('src' , './images/'+ data.result.gameInfo.awayTeam.id +'.png')
    if($('#team2name').html() == "")
        $('#team2name').html(lang=="en" ? data.result.gameInfo.awayTeam.name : data.result.gameInfo.awayTeam.nameLocal)
    if($('#scoreBoxTeam1Logo').attr('src') == "")
        $('#scoreBoxTeam1Logo').attr('src' , './images/'+ data.result.gameInfo.homeTeam.id +'.png')
    if($('#scoreBoxTeam1Name').html() == "")
        $('#scoreBoxTeam1Name').html(lang=="en" ? data.result.gameInfo.homeTeam.name : data.result.gameInfo.homeTeam.nameLocal);
    if($('#scoreBoxTeam2Logo').attr('src') == "")
        $('#scoreBoxTeam2Logo').attr('src' , './images/'+ data.result.gameInfo.awayTeam.id +'.png')
    if($('#scoreBoxTeam2Name').html() == "")
        $('#scoreBoxTeam2Name').html(lang=="en" ? data.result.gameInfo.awayTeam.name : data.result.gameInfo.awayTeam.nameLocal);
	var comp_name = data.result.gameInfo.competition.name.replace(/ /g,'') + ".png"
    comp_name = comp_name.toLowerCase();
    if($('#comp_logo').attr('src') == "")
        $('#comp_logo').attr('src' , './images/'+ comp_name)
        
	$(".tounament-name").html(data.result.gameInfo.competition.name);
    
	foul_teama = GetFoulsCount(1);
	foul_teamb = GetFoulsCount(2);
	foulA_html = ''; foulB_html='';
	for (i=0;i<5;i++) {
		if(foul_teama>0) {
			foulA_html += '';
			foul_teama--;
		} else {
			foulA_html += '';
		}
	}
	for (i=0;i<5;i++) {
		if(foul_teamb>0) {
			foulB_html += '';
			foul_teamb--;
		} else {
			foulB_html += '';
		}
	}
	$('#foul_teamA').html(foulA_html);
	$('#foul_teamB').html(foulB_html);
}
function populateScoreBox(data){
    // $('.teamScore.teamA').html()
    var homeScore = 00;
    var awayScore = 00;
    var homeTimeout = 0;
    var awayTimeout = 0;
    var homeQuarterScores = 00;
    var awayQuarterScores = 00;
    currentQuarter = 0;
    var currentQuarterTime =  {
        "m": 00,
        "s": 00
    };
    if( data.result.success ){
        homeScore = data.result.boxscore.gameInfo.homeScore;
        awayScore = data.result.boxscore.gameInfo.awayScore;
        homeTimeout = data.result.boxscore.gameInfo.homeTimeout;
        awayTimeout = data.result.boxscore.gameInfo.awayTimeout;
        homeQuarterScores = data.result.boxscore.gameInfo.homeQuarterScores;
        awayQuarterScores = data.result.boxscore.gameInfo.awayQuarterScores;
        currentQuarter = data.result.boxscore.gameInfo.currentQuarter;
        currentQuarterTime = data.result.boxscore.gameInfo.currentQuarterTime;
    }else{
        console.log("No game data found");
    }
    
    $('#scorePanel > .teamA > .score').html(homeScore);
    $('#scorePanel > .teamB > .score').html(awayScore);
    $('#matchScore > #matchQuarter').html(translate('Quarter', lang) + " " + currentQuarter.toString());
    $('#matchScore > #matchQuarterTime').html(currentQuarterTime.m.toString().padStart(2, '0') + ":" + currentQuarterTime.s.toString().padStart(2, '0'));
    
    ShowQuatesTags(currentQuarter);
}
function generateActions(data , shotTypesLabels){
    var actionData = data.result.actions;
    var hometeam = data.result.gameInfo.homeTeam;
    var awayteam = data.result.gameInfo.awayTeam;
    var actionsHtml = "";
    var lastAction = null;
    homeFouls = [0,0,0,0];
    awayFouls = [0,0,0,0];
    ActionNum = 0;
    ActionNumAway = 0;
    if(actionData && actionData.length > 0){
        actionData.forEach(element => {
            if( element.type !== undefined && element.type == "game"){
                if(lastAction != null && lastAction.type == element.type) 
                    return;
                
                actionsHtml = generateGameAction(element) + actionsHtml;
            }
            else if( element.type !== undefined && element.type == "substitution"){
                actionsHtml = generatePlayerSubstitutionAction(element,hometeam,awayteam) + actionsHtml;
            }
            else if( element.type !== undefined && element.type == "shot"){
                actionsHtml = generatePlayerShotAction(element,hometeam,awayteam,shotTypesLabels) + actionsHtml;
            }
            else if( element.type !== undefined && element.type == "freeThrow"){
                actionsHtml = generatePlayerFreeThrowAction(element,hometeam,awayteam,shotTypesLabels) + actionsHtml;
            }
            else if( element.type !== undefined && element.type == "rebound"){
                actionsHtml = generatePlayerReboundAction(element,hometeam,awayteam) + actionsHtml;
            }
            else if( element.type !== undefined && element.type == "steal"){
                actionsHtml = generatePlayerStealAction(element,hometeam,awayteam) + actionsHtml;
            } 
            else if( element.type !== undefined && element.type == "deflection"){
                actionsHtml = generatePlayerDeflectionAction(element,hometeam,awayteam) + actionsHtml;
            } 
            else if( element.type !== undefined && element.type == "timeout"){
                actionsHtml = generateTimeoutAction(element,hometeam,awayteam) + actionsHtml;
            }
            else if( element.type !== undefined && element.type == "block"){
                actionsHtml = generatePlayerBlockAction(element,hometeam,awayteam) + actionsHtml;
            }
            else if( element.type !== undefined && element.type == "assist"){
                actionsHtml = generatePlayerAssistAction(element,hometeam,awayteam) + actionsHtml;
            }
			else if( element.type !== undefined && element.type == "foul"){
                actionsHtml = generatePlayerFoulAction(element,hometeam,awayteam,foulTypesLabels) + actionsHtml;
            }
            else if( element.type !== undefined && element.type == "foul-drawn"){
                actionsHtml = generatePlayerFoulDrawnAction(element,hometeam,awayteam,foulTypesLabels) + actionsHtml;
            }
            else if( element.type !== undefined && element.type == "turnover"){
                actionsHtml = generatePlayerTurnoverAction(element,hometeam,awayteam,turnoverTypesLabels) + actionsHtml;
            }
            else if( element.type !== undefined && element.type == "quarter"){
                actionsHtml = generateGameAction(element) + actionsHtml;
            }
            else if( element.type !== undefined && element.type == "clock"){
                // actionsHtml += generatePlayerAction();
            }
            
            lastAction = element;
        });
        $('#action-list-ul').html(actionsHtml);
    }
}
function generateGameAction(actionData){
    var actionType = actionData.type;
    var gameAction = actionData.parameters.type;
    var actionTime = actionData.quarterTime;
    var actionQuarter = actionData.quarter;
    if( actionType === "game" && gameAction === "start-of-game" ){
        var returnHtml = "";
        var actionLabel = actions_translate_local("start of game") ;
        returnHtml = '
';
        return returnHtml;
    }
    else if( actionType === "game" && gameAction === "end-of-game" ){
        var returnHtml = "";
        var actionLabel = actions_translate_local("end of game") ;
        returnHtml = '';
        return returnHtml;
    }
    else if( actionType === "quarter" && gameAction === "start-of-quarter" ){
        var returnHtml = "";
        if( actionQuarter > 0 ){
            ActionNum = 0;
            var actionLabel = actions_translate_local("start of") + " " + actions_translate_local("Q") + " " + actionQuarter + " " + actionTime ; 
            returnHtml += '';
            returnHtml += '\
            '+actionLabel+'
\
            ';
        }
        return returnHtml;
    }
    else if( actionType === "quarter" && gameAction === "end-of-quarter" ){
        var returnHtml = "";
        if( actionQuarter > 0 ){
            var actionLabel = actions_translate_local("end of") + " " + actions_translate_local("Q") + " " + actionQuarter + " " + actionTime ;
            returnHtml += '\
            '+actionLabel+'
\
            ';
        }
        return returnHtml;
    }
}
function generatePlayerShotAction(actionData , hometeam , awayteam , shotTypesLabels){
    var quarterTime = actionData.quarterTime;
    var actionQuarter = actionData.quarter;
    var score = (actionData.score) ? transalteScore(actionData.score): "";
    if(score != "") 
        last_shot_score = ""; 
    var team = actionData.parameters.team;
   // console.log(team)
    var playerJerseyNo = actionData.parameters.player;
    var shotPoints = actionData.parameters.points;
    var shotType = actionData.parameters.type;
    var shotSuccess = actionData.parameters.made;
    var playername = "";
    if( team == 1 ){
        var teamClass = 'action-teamA';
        var teamId = hometeam.id;
        var f = actions_translate_local(shotSuccess);
        if( actionData.parentActionId == 0)
            ActionNum = ActionNum + 1;
        hometeam.players.forEach(player => {
            if( player.jerseyNumber == playerJerseyNo ){
                playername = getFullPlayerName(player);
            }
        });
        return '\
            \
                

\
            
\
                
' + playerJerseyNo +' '+ playername + '
' +  actions_translate_local(shotSuccess) + " " + shotPoints + " " + actions_translate_local("points") +  " " + shotTypesLabels_local(shotType)  +'
\
                
'+ quarterTime + '
' + score +'
\
            
\
                
'+ quarterTime + '
' + score +'
\
                
' + playerJerseyNo +' '+ playername + '
' +  actions_translate_local(shotSuccess) + " " + shotPoints + " " + actions_translate_local("points") +  " " + shotTypesLabels_local(shotType)+'
\
            
\
                

\
            
\
                

\
            
\
                
' + playerJerseyNo +' '+ playername + '
' +  actions_translate_local(shotSuccess) + " " + shotTypesLabels_local(shotType) + " ("+freeThrowNumber + "/" + freeThrowsAwarded+")" +'
\
                
'+ quarterTime + '
' + score +'
\
            
\
                
'+ quarterTime + '
' + score +'
\
                
' + playerJerseyNo +' '+ playername + '
' +  actions_translate_local(shotSuccess) +  " " + shotTypesLabels_local(shotType) + " ("+freeThrowNumber + "/" + freeThrowsAwarded+")" +'
\
            
\
                

\
            
' + " " + actions_translate_local(reboundTypeLabel);
        }
        return '\
            \
                

\
            
\
                
'+ actionDetailsLabel +'
\
                
'+ quarterTime + '
' + score +'
\
            
' + " " + actions_translate_local(reboundTypeLabel);
        }
        
        return '\
            \
                
'+ quarterTime + '
' + score +'
\
                
'+ actionDetailsLabel +'
\
            
\
                

\
            
' + actions_translate_local(SubstitutionLabel + " out");
            
            element_out =  '\
            \
                

\
            
\
                
'+ actionDetailsLabel_out +'
\
                
'+ quarterTime + '
' + score +'
\
            
' + actions_translate_local(SubstitutionLabel + " in");
            
            element_in =  '\
            \
                

\
            
\
                
'+ actionDetailsLabel_in +'
\
                
'+ quarterTime + '
' + score +'
\
            
 " + actions_translate_local(SubstitutionLabel + " out");
            
            element_out =  '\
             \
                
'+ quarterTime + '
' + score +'
\
                
'+ actionDetailsLabel_out +'
\
            
\
                

\
            
 " + actions_translate_local(SubstitutionLabel + " in");
            
            element_in =  '\
            \
                
'+ quarterTime + '
' + score +'
\
                
'+ actionDetailsLabel_in +'
\
            
\
                

\
            
 " + " " + actions_translate_local(stealLabel);
        }
        return '\
            \
                

\
            
\
                
'+ actionDetailsLabel +'
\
                
'+ quarterTime + '
' + score +'
\
            
 "  + " " + actions_translate_local(stealLabel);
        }
        
        return '\
            \
                
'+ quarterTime + '
' + score +'
\
                
'+ actionDetailsLabel +'
\
            
\
                

\
            
 " + " " + actions_translate_local(deflectionLabel);
        }
        return '\
            \
                

\
            
\
                
'+ actionDetailsLabel +'
\
                
'+ quarterTime + '
' + score +'
\
            
 "  + " " + actions_translate_local(deflectionLabel);
        }
        
        return '\
            \
                
'+ quarterTime + '
' + score +'
\
                
'+ actionDetailsLabel +'
\
            
\
                

\
            
 " + " " + actions_translate_local(foulLabel) + " (" + foulTypesLabels_local(foulType) + ")" + (foulKind  != "" ? " - " + foulKind : "");
        }
        //homeFouls[actionQuarter - 1] = homeFouls[actionQuarter - 1] + 1;
        if(!(foulType == "technical" && (isCoachFoul == 1 || isBenchFoul == 1 )))
            AddFoul(1, actionQuarter);
        return '\
            \
                

\
            
\
                
'+ actionDetailsLabel +'
\
                
'+ quarterTime + '
' + score +'
\
            
 " + " " + actions_translate_local(foulLabel) + " (" + foulTypesLabels_local(foulType) + ")" + (foulKind  != "" ? " - " + foulKind : "");
        }
        //awayFouls[actionQuarter - 1] = awayFouls[actionQuarter - 1] + 1;
        if(!(foulType == "technical" && (isCoachFoul == 1 || isBenchFoul == 1 )))
            AddFoul(2, actionQuarter);
        else
            playername = "";
            
        return '\
            \
                
'+ quarterTime + '
' + score +'
\
                
'+ actionDetailsLabel +'
\
            
\
                

\
            
 " + actions_translate_local(foulLabel);
        }
        return '\
            \
                

\
            
\
                
'+ actionDetailsLabel +'
\
                
'+ quarterTime + '
' + score +'
\
            
 " + actions_translate_local(foulLabel);
        }
        
        return '\
            \
                
'+ quarterTime + '
' + score +'
\
                
'+ actionDetailsLabel +'
\
            
\
                

\
            
 " + actions_translate_local(turnoverLabel) + " " + turnoverTypesLabels_local(turnoverType);
        }
       
        var f = actions_translate_local(turnoverLabel);
         return '\
            \
                

\
            
\
                
'+ actionDetailsLabel +'
\
                
'+ quarterTime + '
' + score +'
\
            
 " + actions_translate_local(turnoverLabel) + " " + turnoverTypesLabels_local(turnoverType);
        }
        var f = actions_translate_local(turnoverLabel);
        return '\
            \
                
'+ quarterTime + '
' + score +'
\
                
'+ actionDetailsLabel +'
\
            
\
                

\
            
 " + " " + actions_translate_local(blockLabel);
        }
        return '\
            \
                

\
            
\
                
'+ actionDetailsLabel +'
\
                
'+ quarterTime + '
' + score +'
\
            
 " + " " + actions_translate_local(blockLabel);
        }
        
        return '\
            \
                
'+ quarterTime + '
' + score +'
\
                
'+ actionDetailsLabel +'
\
            
\
                

\
            
 " + actions_translate_local(assistLabel);
        }
        return '\
            \
                

\
            
\
                
'+ actionDetailsLabel +'
\
                
'+ quarterTime + '
' + score +'
\
            
 " + actions_translate_local(assistLabel);
        }
        
        return '\
            \
                
'+ quarterTime + '
' + score +'
\
                
'+ actionDetailsLabel +'
\
            
\
                

\
            
\
                

\
            
\
                
'+ actionDetailsLabel +'
\
                
'+ quarterTime + '
' + score +'
\
            
\
                
'+ quarterTime + '
' + score +'
\
                
'+ actionDetailsLabel +'
\
            
\
                

\
            
\
                

\
            
'+ quarterTime + '
' + score +''+actionDetailsLabel+'\
            
\
            \
                

\
            
\
            

\
        
'+ playerno +' '+ playername +'
\
    ';
}
// API RESULT SUCCESS FAILURES
function generateFailureBox(){
    var actionLabel = "Game data not available."
    var returnHtml = '';
        $('#action-list-ul').html(returnHtml); 
}
// Auto-refresh / Interval API calls
function autoRefreshGameActions(){
    new Promise( (resolve,reject) => {
        $.ajax({
            url: 'get_team_action.php?game_id='+game_id,
            type: 'GET',
            headers: {
                "content-type": "application/json",
                "x-api-key": "segev32",
                "cache-control": "no-cache",
            },
            success: function(data) { 
                // alert('Success!');
                //console.log(data.jsonrpc);
                if(!data) 
                    return;
                data = JSON.parse(data);
                if(!data || !data.result) 
                    return;
                if( data.result.success ){
                    populateGameInfo(data);
                    generateActions(data , shotTypesLabels);
                    toggleQuarterActions();
                    resolve("API call success");
                }else{
                    generateFailureBox();
                    resolve("API call success but No game data");
                }
            },
            error: function(err){
                console.error(err);
                reject("API call Failed");
            }
        })
    }).then((responseData)=>{
        setTimeout(function(){
            autoRefreshGameActions();
        },15000);        
    })
}
function autoRefreshBoxScores(){
    new Promise( (resolve,reject) => {
        $.ajax({
             url: 'get_team_score.php?game_id='+game_id,
            type: 'GET',
            headers: {
                "content-type": "application/json",
                "x-api-key": "segev32",
                "cache-control": "no-cache",
            },
            success: function(data) { 
                // alert('Success!');
                data = JSON.parse(data);
                if( data.result.success ){
                    populateScoreBox(data);
                    resolve("API call success");
                }else{
                    resolve("API call success but No game data");
                }
            },
            error: function(err){
                console.error(err);
                reject("API call Failed");
            }
        })
    }).then((responseData)=>{
        setTimeout(function(){
            autoRefreshBoxScores();
        },15000);        
    })
}
function GetFoulsCount(teamId)
{
    var index = 0;
    if(currentQuarter > 4)
        index = 3;
    else if(currentQuarter < 0)
        index = 0;
    else
        index = currentQuarter - 1;
    if(teamId == 1)
        return homeFouls[index];
    else
        return awayFouls[index];
}
function AddFoul(team, quarter)
{
    var QuarterIndex = (quarter) ? quarter : 0;
    QuarterIndex = QuarterIndex >= 4 ? 3 : QuarterIndex - 1;
    QuarterIndex = Math.max(0, QuarterIndex);
    if(team == 1)
    {
        homeFouls[QuarterIndex] = homeFouls[QuarterIndex] + 1;
    }
    else
    {
        awayFouls[QuarterIndex] = awayFouls[QuarterIndex] + 1;
    }
} 
var last_selected_q = 1;
function ShowQuatesTags(quarter)
{
    var i = 1;
    for(i=1; i <= 8; i++)
    {
        if(quarter >= i)
        {
            $(".tab"+i).removeClass("hide");
        }
    }
    if(last_selected_q != quarter)
    { 
        last_selected_q = quarter; 
        $(".tab"+quarter).click();
    }
   
}