/*
* Darts Live Score javascript stuff.
*/

var DartsLiveScore = function() {
    // store recent json in variable when re-rendering stats
    var mostRecentlyRetrievedJson = {}
    
    var radioManuallySelected = false;
    
    var selectorsSpec= {
        'player_1_score':               '#player-1-score',
        'player_1_score_in_legs':       '#player-1-score-in-legs',
        'player_2_score':               '#player-2-score',
        'player_2_score_in_legs':       '#player-2-score-in-legs',
        'player_1_to_throw':           '#player-1-throwing',
        'player_2_to_throw':           '#player-2-throwing',
        'p1_average':                   '#p1-3-dart-average',
        'p2_average':                   '#p2-3-dart-average',
        'p1_9_dart_average':            '#p1-9-dart-average',
        'p2_9_dart_average':            '#p2-9-dart-average',
        'p1_180s':                      '#p1-180s',
        'p1_140s':                      '#p1-140s',
        'p1_100s':                      '#p1-100s',
        'p2_180s':                      '#p2-180s',
        'p2_140s':                      '#p2-140s',
        'p2_100s':                      '#p2-100s',
        'p1_doubles':                   '#p1-doubles',
        'p2_doubles':                   '#p2-doubles',
        'p1_checkouts':                 '#p1-checkouts',
        'p2_checkouts':                 '#p2-checkouts',
        'p1_biggest_checkout':          '#p1-biggest-checkout',
        'p2_biggest_checkout':          '#p2-biggest-checkout',
        'p1_lwat':                      '#p1-lwat',
        'p2_lwat':                      '#p2-lwat',
        'player_throwing_desc':         '#player-throwing-desc',
        'bet_buttons':                  '.bet-button',
        'match_stats_radio':            "#match-stats-radio"
    };
    
    var selectors = {};
    
    // Replace the css selector values in the selectors object with
    // a reference to a jQuery object.
    var recompileSelectors = function() {
        selectors = {};
        for (var key in selectorsSpec) { 
            selectors[key] = $(selectorsSpec[key]); 
        }
    };

    // Abstraction for updating data from an array (e.g. goals, yellow cards).
    var updateEnumerable = function(element, array, formatter) {
        var result = '';
        
        for (var i=0; i < array.length; i++) { result += formatter(array[i]); }
        
        updateHTMLIfChanged(element, result);
    };
    
    // Update the HTML of the given element, but only if it will be changed.
    var updateHTMLIfChanged = function(element, html, symbol, flash) {
        if (symbol != null) {
            if (html+"" == "0") { 
                updateElement(element,'0',false);
                  }
            else if (html == null ) { updateElement(element,'',false);  }
            else if (html != null && (element.html() != (html + symbol))) {
                updateElement(element,(html + symbol),flash); 
                }
        }
        else {
            if (html == 0 ) { updateElement(element,'0',false);  }
            else if (html == null ) { updateElement(element,'',false);  }
            else if (element.html() != html ) { updateElement(element,html,flash); }
        }
    };
    
    var updateElement = function(element, html, flash){
        if (flash)
            updateElementWithFlash(element,html);
        else
            element.html(html);
    }
    
    var updateElementWithFlash = function(element, html) {
        var originalBgColor = element.css('backgroundColor')
        
        element.animate({
            backgroundColor: '#FAF75C3'
        }, 500,
            function(){
                element.css('backgroundColor', originalBgColor)
                    }
                        );
        
        element.html(html);
    }
    
    var updateBoxScore = function(json, flash) {
        updateHTMLIfChanged(selectors.player_1_score, json.player_1_score, null, flash);
        updateHTMLIfChanged(selectors.player_2_score, json.player_2_score, null, flash);
        updateHTMLIfChanged(selectors.player_1_score_in_legs, json.player_1_score_in_legs, null, flash);
        updateHTMLIfChanged(selectors.player_2_score_in_legs, json.player_2_score_in_legs, null, flash);
        updateToThrow(json);
    };
    
    var updateToThrow = function(json) {
        if (json.to_throw_first_in_next_leg == 1 && json.match_status_name == 'In play')
            {
                selectors.player_1_to_throw.show()
                selectors.player_2_to_throw.hide()
                selectors.player_throwing_desc.show()
            }
        else if (json.to_throw_first_in_next_leg == 2 && json.match_status_name == 'In play')    
            {
                selectors.player_2_to_throw.show()
                selectors.player_1_to_throw.hide()
                selectors.player_throwing_desc.show()
            }
        else
            {
                selectors.player_2_to_throw.hide()
                selectors.player_1_to_throw.hide()
                selectors.player_throwing_desc.hide()
            }
        };
            
    var updateLiveStats = function(flash) {
        if (flash == null)
            flash = false;

        json = mostRecentlyRetrievedJson;
        statsType = $("input[name='stats-type']:checked").val();
        
        switch(statsType) {
            case "tournament": updateTournamentStats(json,flash); break;
            case "match": updateMatchStats(json,flash); break;
        }
    };
            
    var updateTournamentStats = function(json,flash) {
        player_1_stats = json.entry_1.attributes
        player_2_stats = json.entry_2.attributes
    
        updateHTMLIfChanged(selectors.p1_average, player_1_stats.player_average, null, flash);
        updateHTMLIfChanged(selectors.p2_average, player_2_stats.player_average, null, flash);
        updateHTMLIfChanged(selectors.p1_9_dart_average, player_1_stats.first_9_average, null, flash);
        updateHTMLIfChanged(selectors.p2_9_dart_average, player_2_stats.first_9_average, null, flash);
        updateHTMLIfChanged(selectors.p1_180s, player_1_stats.player_180s, null, flash);
        updateHTMLIfChanged(selectors.p2_180s, player_2_stats.player_180s, null, flash);
        updateHTMLIfChanged(selectors.p1_140s, player_1_stats.player_140s, null, flash);
        updateHTMLIfChanged(selectors.p2_140s, player_2_stats.player_140s, null, flash);
        updateHTMLIfChanged(selectors.p1_100s, player_1_stats.player_100s, null, flash);
        updateHTMLIfChanged(selectors.p2_100s, player_2_stats.player_100s, null, flash);
        updateHTMLIfChanged(selectors.p1_doubles, player_1_stats.player_doubles_hit_percentage,'%', flash);
        updateHTMLIfChanged(selectors.p2_doubles, player_2_stats.player_doubles_hit_percentage,'%', flash);
        updateHTMLIfChanged(selectors.p1_checkouts, player_1_stats.player_checkouts_percentage,'%', flash);
        updateHTMLIfChanged(selectors.p2_checkouts, player_2_stats.player_checkouts_percentage,'%', flash);
        updateHTMLIfChanged(selectors.p1_biggest_checkout, player_1_stats.player_biggest_checkout, null, flash);
        updateHTMLIfChanged(selectors.p2_biggest_checkout, player_2_stats.player_biggest_checkout, null, flash);
        updateHTMLIfChanged(selectors.p1_lwat, player_1_stats.player_lwat, null, flash);
        updateHTMLIfChanged(selectors.p2_lwat, player_2_stats.player_lwat, null, flash);
    }

    var updateMatchStats = function(json, flash) {
        updateHTMLIfChanged(selectors.p1_average, json.player_1_average, null, flash);
        updateHTMLIfChanged(selectors.p2_average, json.player_2_average, null, flash);
        updateHTMLIfChanged(selectors.p1_9_dart_average, json.p1_first_9_average, null, flash);
        updateHTMLIfChanged(selectors.p2_9_dart_average, json.p2_first_9_average, null, flash);
        updateHTMLIfChanged(selectors.p1_180s, json.player_1_180s, null, flash);
        updateHTMLIfChanged(selectors.p2_180s, json.player_2_180s, null, flash);
        updateHTMLIfChanged(selectors.p1_140s, json.player_1_140s, null, flash);
        updateHTMLIfChanged(selectors.p2_140s, json.player_2_140s, null, flash);
        updateHTMLIfChanged(selectors.p1_100s, json.player_1_100s, null, flash);
        updateHTMLIfChanged(selectors.p2_100s, json.player_2_100s, null, flash);
        updateHTMLIfChanged(selectors.p1_doubles, json.player_1_doubles_hit_percentage,'%', flash);
        updateHTMLIfChanged(selectors.p2_doubles, json.player_2_doubles_hit_percentage,'%', flash);
        updateHTMLIfChanged(selectors.p1_checkouts, json.player_1_checkouts_percentage,'%', flash);
        updateHTMLIfChanged(selectors.p2_checkouts, json.player_2_checkouts_percentage,'%', flash);
        updateHTMLIfChanged(selectors.p1_biggest_checkout, json.player_1_biggest_checkout, null, flash);
        updateHTMLIfChanged(selectors.p2_biggest_checkout, json.player_2_biggest_checkout, null, flash);
        updateHTMLIfChanged(selectors.p1_lwat, json.player_1_lwat, null, flash);
        updateHTMLIfChanged(selectors.p2_lwat, json.player_2_lwat, null, flash);
    }

    // Perform a JSON update request, and update data needed for the lineups page.
    var doScoreUpdate = function(liveScoreJsonUrl,flash) {
        liveScoreJsonUrl += "&prevcache=" + Math.floor(Math.random()*999999)
        $.getJSON(liveScoreJsonUrl, function(json) {
            updateBoxScore(json, flash);
            mostRecentlyRetrievedJson = json;
            showHeading(json);
            updateLiveStats(flash);
            updateNav(json);
            updateStatuses(json);
            hideBetButtons(json);
        });
    };

    var hideBetButtons = function(json) {
        if (json.match_status_name == 'Completed')
            selectors.bet_buttons.hide();
    }

    var scoreFromJson = function(json) {
        if (json.match_status_name == 'Fixture')
         return "v"
        else if (json.number_of_sets == 1) 
         return json.player_1_score_in_legs + " - " + json.player_2_score_in_legs
        else 
         return json.player_1_score + " - " + json.player_2_score
    }
    
    var navStatusChangeFromJson = function(json) {
        if (json.match_status_name == 'Fixture')
          return false;
        else if (json.match_status_name == 'In play') 
            return "Live"
        else if (json.match_status_name == 'Completed') 
            return "R"
        
        return false;
    }
    
    var statusChangeFromJson = function(json) {
        if (json.match_status_name == 'Fixture')
          return false;
        else if (json.match_status_name == 'In play') 
            return "In Play"
        else if (json.match_status_name == 'Completed') 
            return "Result"
        
        return false;
    }

    var updateNav = function(json){
        $score= $("table.match-nav tr.match[data-match-id="+ json.id+ "]").children(".score");
        $score.html(scoreFromJson(json));
        $status = $("table.match-nav tr.match[data-match-id="+ json.id+ "]").children(".nav-status");
        new_status = navStatusChangeFromJson(json);
        if (new_status)
            $status.html(new_status);
    }

    var updateStatuses = function(json){
       new_status = statusChangeFromJson(json);
       if (new_status)
            $(".match-status").html(new_status)
    }

    var showHeading = function(json) {
        if (json.match_status_name == 'Fixture')
            {
                // show fixture heading
                selectors.match_stats_radio.hide()
                // select tournament radio
                if (!radioManuallySelected)
                    $("input[name='stats-type']:nth(0)").attr("checked","checked");
            }
            else
                {
                    // show in play heading
                    selectors.match_stats_radio.show()
                    // select this match radio
                    if (!radioManuallySelected)
                        $("input[name='stats-type']:nth(1)").attr("checked","checked");
                }
            }
        
            return {
                // ------------------
                // Exposed functions:
                // ------------------
            
                showStats: function(element) {
                    radioManuallySelected = true;
                    updateLiveStats();
                    element.blur();
                },
            
                // Start match details data updates.
                initScore: function(liveScoreJsonUrl) {
                    radioManuallySelected = false;
                
                    // clear any old intervals
                    if (liveScoreInterval)
                        clearInterval(liveScoreInterval);
                      
                    recompileSelectors();
                    doScoreUpdate(liveScoreJsonUrl,false);
                    // Perform an update every 10 seconds.
                    liveScoreInterval = window.setInterval(function() { doScoreUpdate(liveScoreJsonUrl,true); }, 7000);
                }
            }
    }();
                    
