// -------------------------------------------------
// AJAX script (using Prototype framework).
//
// Global variables required:
// - gGameId
// - gVersion
// - gTeamSyncId
// - gLang
// - gHomeTeamId
// - gAwayTeamId
// - gHomeRes
// - gAwayRes
// -------------------------------------------------

var xmlParser;
var gamesXmlParser;

// ------------------------------------------
// Update game
// ------------------------------------------
function update(path) {
          
	// Error response
	var errFunc = function(t) {
		//alert('Error ' + t.status + ' -- ' + t.statusText);
	}
          
	// XML response
	var handlerFunc = function(t) {
		if (t.responseText != '') {

            xmlParser = new XmlParser(t.responseXML);
            
            // nothing to update?
            if (xmlParser.isEmpty()) {
                return true;
            }
            
            // update global variables
            gVersion = xmlParser.getRoot().version;

            // Update page        
            dateUpdate();
            resultUpdate();
            lineupUpdate();
            matchHistoryUpdate();
            annotationsUpdate();
            summaryUpdate();
            liveStatsUpdate();
            teamInfoUpdate();
            timeInfoUpdate();
        }
    }

    var params = "gameId=" + gGameId
                 + "&teamSyncId=" + gTeamSyncId
                 + "&version=" + gVersion
                 + "&partner=" + gPartner
                 + "&lang=" + gLang
                 + "&tz=" + gTimeZone;

    new Ajax.Request(path, {parameters:params, onSuccess:handlerFunc, onFailure:errFunc});

} // end function


// ------------------------------------------
// Update game tabs
// ------------------------------------------
function updateGames(path) {
          
    // Error response
    var errFunc = function(t) {
        //alert('Error ' + t.status + ' -- ' + t.statusText);
    }
          
    // XML response
    var handlerFunc = function(t) {
        if (t.responseText != '') {

            gamesXmlParser = new GamesXmlParser(t.responseXML);
                                   
            // Update page
            gamesUpdate();
        }
    }

    var params = "leagueId=" + gLeagueId + "&date=" + gDate + "&partner=" + gPartner;


    new Ajax.Request(path, {parameters:params, onSuccess:handlerFunc, onFailure:errFunc});

} // end function


// ------------------------------------------
// Update date (game starting time)
// ------------------------------------------
function dateUpdate(){
    var date = xmlParser.getRoot().date;

    // update container
    var container = document.getElementById("gameStart");

    if (container != null) {
        container.innerHTML = date;
    }
}

// ------------------------------------------
// Update result (standing)
// ------------------------------------------
function resultUpdate() {

    var result = xmlParser.getRoot().result;

    if (result == null) {
        return;
    }

    // update global variables
    gHomeRes = result.home;
    gAwayRes = result.away;

    var goalHome = document.getElementById("goalHome");
    var goalAway = document.getElementById("goalAway");

    goalHome.innerHTML = gHomeRes;
    goalAway.innerHTML = gAwayRes;
        //sound cookie
    var res = eval(gHomeRes + gAwayRes);
    if (res > 0) {
        playsound(res + '_' + gGameId, gGameId);
        pling();
    }

}

// ------------------------------------------
// Update time
// ------------------------------------------
function timeInfoUpdate(){
    var time = xmlParser.getRoot().time;
    
    if (time == null) {
        return;
    }
        
    if(gGameTimeUpdate != time.update){
        gGameTimeMinutes = time.min;
        gGameTimeUpdate = time.update;
    }
    
    gGameActive = time.status;
    gGamePeriod = time.period;
    
    updateTime();
}

// ------------------------------------------
// Update annotations
// ------------------------------------------
function annotationsUpdate() {

    var annotations = xmlParser.getRoot().annotations;
    var lineup = xmlParser.getRoot().lineup;

    if (annotations == null || lineup == null) {
        return;
    }

    var html = "<table>";
    for (var i = 0; i < annotations.length; i++) {
        var annotation = annotations[i];
        html += "<tr>";
        html += "<td>" + annotation.time + "</td>";
        html += "<td class='res_" + annotation.resulttype + "'></td>";
        html += "<td>" + annotation.text + "</td>";
        html += "</tr>";
    }
    html += "</table>";

    // update container
    var container = document.getElementById("annotationContainer");
    if (container != null) {
        container.innerHTML = html;
    }
}

// ------------------------------------------
// Update lineups
// ------------------------------------------
function lineupUpdate() {

    var lineup = xmlParser.getRoot().lineup;

    if (lineup == null) {
        return;
    }

    // update global variables
    gTeamSyncId = lineup.syncId;
    gHomeTeamId = lineup.home.id;
    gAwayTeamId = lineup.away.id;

    var homeLineupContainer = document.getElementById("homeLineupContainer");
    var awayLineupContainer = document.getElementById("awayLineupContainer");

    // update lineup containers
    homeLineupContainer.innerHTML = createLineupHtml(lineup.home.players);
    awayLineupContainer.innerHTML = createLineupHtml(lineup.away.players);


    function createLineupHtml(players) {

        var html = "<table>";
        var positionLast = "";
        var onField;
        // loop players
        for (var i = 0; i < players.length; i++) {

            var player = players[i];

            // default value
            onField = (player.position != 5 ? "onField" : "notOnField");

            if (player.position != positionLast) {
                var positionName;
                switch (player.position) {
                    case "1":
                        positionName = gGoalkeeper;
                        break;
                    case "2":
                        positionName = gDefender;
                        break;
                    case "3":
                        positionName = gMidfielder;
                        break;
                    case "4":
                        positionName = gForward;
                        break;
                    case "5":
                        positionName = gSubstituter;
                        //onField = "notOnField";
                        break;
                    default:
                        positionName = player.position;
                }
                html += "<tr>";
                html += "<td colspan='5' class='pos'>" + positionName + "</td>";
                html += "</tr>";
            }

            var statusClass = "";
            if (player.status == '2') {
                statusClass = " yellowCard";
            } else if (player.status == '3') {
                statusClass = " yellowRedCard";
                onField = "notOnField";
            } else if (player.status == '4') {
                statusClass = " redCard";
                onField = "notOnField";
            }

            var substClass = "";
            if (player.subst == 'IN') {
                substClass = " res_460";
                onField = "onField";
            } else if (player.subst == 'OUT') {
                substClass = " res_461";
                onField = "notOnField";
            }

            var goalClass = "";
            if (player.goals == '0') {
                goalCount = "";
            } else {
                goalClass = "res_400";
            }
            //subst result time
            var totTime = player.substTime;
            if (player.substPeriod == '100' && player.substTime > 45) {
                totTime = "45+" + eval(player.substTime - 45);
            }else if (player.substPeriod == '110' && player.substTime > 90) {
                totTime = "90+" + eval(player.substTime-90);
            }

            // Skip 'Own Goal'
            if (player.surName.indexOf("Own Goal") == -1) {
                html += "<tr>";
                // Dont show count for one goal
                if (player.goals <= 1) {
                    player.goals = "";
                }
                html += "<td class='" + goalClass + "'>" + player.goals + "</td>";
                html += "<td class='subst" + substClass + "'>"+totTime+"</td>";
                html += "<td class='nr'>" + player.number + "</td>";
                html += "<td class='player " + onField;
                if(playerStats){
                    html += "' onmouseover='showStats(this, " + player.id + ");' onmouseout='hideStats(" + player.id + ");";
                }
                html += "'>";
                if(playerStats2){
                    html += "<a href='#' onclick='openPlayerstat(" + player.id + ");'>";
                }

                html += player.firstName + " " + player.surName;
                if(playerStats2=='full'){
                    html += "</a>";
                }
                html += "</td><td class='status" + statusClass + "'></td>";
                html += "</tr>";
            }

            positionLast = player.position;
        } // for

        html += "</table>";

        return html;

    } // end function

}
// ------------------------------------------
// Update match history
// ------------------------------------------
function matchHistoryUpdate() {
    var lineup = xmlParser.getRoot().lineup;

    if (lineup == null) {
        return;
    }


    var html = "<table>";

    // header
    html += "<tr>";
    html += "<th>" + gTime + "</th>";
    html += "<th colspan='2'>" + gAction + "</th>";
    html += "<th>" + gName + "</th>";
    html += "<th>" + gResult + "</th>";

    html += "</tr>";

    for (var i = 0; i < lineup.results.length; i++) {
        var result = lineup.results[i];

        var totTime = result.time;
        if (result.period == '100' && result.time > 45) {
            totTime = "45+" + eval(result.time - 45);
        }else if (result.period == '110' && result.time > 90) {
            totTime = "90+" + eval(result.time-90);
        }

        // body
        html += "<tr>";

        html += "<td>" + totTime + "'</td>";
        
        var resClass = "res_" + result.type;

        if (result.subType == '411') {
           resClass = "res_" + result.subType;
        }

        html += "<td width='10px' class='"+ resClass + "' />";

        html += "<td>";
        if (result.subType == '401') {
            html += "(";
            html += gPenaltyKick;
            html += ")";
        }
        html += "</td>";
        if(result.pName.toLowerCase().indexOf('own goal')!=-1){
            html += "<td>" + gOwnGoal + "</td>";
        }else{
           html += "<td>" + result.pName + "</td>";
        }
        html += "<td>";
        if ( !(result.type == "460" || result.type == "461") ) {
            html += result.value;
        }
        html += "</td>";
        html += "</tr>";
    } // for

    html += "</table>";

    // update match history container
    var container = document.getElementById('matchHistoryContainer');

    if (container != null) {
        container.innerHTML = html;
    }

}

// ------------------------------------------
// Update summary
// ------------------------------------------
function summaryUpdate() {
    var summary = xmlParser.getRoot().summary;

    if (summary == null) {
        return;
    }

    var html = "<table>";

    html += "<tr>";
    html += "<td class='home teamName' colspan='5'>" + gTeamSummary + "</td>";
    html += "</tr>";

    html += "<tr>";
    html += "<td class='home teamName' colspan='2'>";
    html += summary.hTeam;
    html += "</td>";
    html += "<td class='separator'></td>";
    html += "<td class='away teamName' colspan='2'>";
    html += summary.aTeam;
    html += "</td>";
    html += "</tr>";

    var lastType = "";

    html += "<tr>";

    // loop summary results
    for (var i = 0; i < summary.results.length; i++) {
        var result = summary.results[i];

        if (lastType != result.type) {
            html += "</tr>";
            html += "<tr>";

            html += "<td class='home'>";
            html += getSummaryDesc(result.type);
            html += "</td>";

            html += "<td class='home'>";
            html += result.value;
            html += "</td>";
        } else {
            html +=  "<td class='separator'></td>";

            html += "<td class='away'>";
            html += result.value;
            html += "</td>";

            html += "<td class='away'>";
            html += getSummaryDesc(result.type);
            html += "</td>";
        }

        lastType = result.type;
    }

    html += "</tr>";
    html += "</table>";

    // update container
    var container = document.getElementById("summaryContainer");

    if (container != null) {
        container.innerHTML = html;
    }

    function getSummaryDesc(type) {

        var desc;

        switch (type) {
            case "900":
                desc = gShotsOnTarget;
                break;
            case "901":
                desc = gShotsOffTarget;
                break;
            case "902":
                desc = gBallPossession;
                break;
            case "903":
                desc = gCorners;
                break;
            case "904":
                desc = gFouls;
                break;
            case "905":
                desc = gOffside;
                break;
            case "906":
                desc = gSubstitutions;
                break;
            case "950":
                desc = gAttendance;
                break;
            default:
                desc = "";
        }

        return desc;

    } // end function
}
// ------------------------------------------
// Update live stats
// ------------------------------------------
function liveStatsUpdate() {
    var liveStats = xmlParser.getRoot().liveStats;
    var result = xmlParser.getRoot().result;

    if (liveStats == null) {
        return;
    }

    // next goal
    updateHtml("ls-nextGoalHome", liveStats.nextGoal.home);
    updateHtml("ls-nextGoalAway", liveStats.nextGoal.away);
    updateHtml("ls-noMoreGoals", liveStats.nextGoal.none);

    // outcome
    updateHtml("ls-win", liveStats.outcome.win);
    updateHtml("ls-draw", liveStats.outcome.draw);
    updateHtml("ls-loss", liveStats.outcome.loss);

    function updateHtml(elementId, value) {
        var container = document.getElementById(elementId);
        if (container != null) {
            if (isNaN(value)) {
                container.innerHTML = "&nbsp;-&nbsp;";
            } else if (value == 0.05) {
                container.innerHTML = "< " + Math.round(value * 100) + "%";
            } else if (value == 0.95) {
                container.innerHTML = "> " + Math.round(value * 100) + "%";
            } else {
                container.innerHTML = Math.round(value * 100) + "%";
            }
        }
    }

}

// ------------------------------------------
// Team info (team names and shirts)
// ------------------------------------------
function teamInfoUpdate() {
    var summary = xmlParser.getRoot().summary;
    var lineup = xmlParser.getRoot().lineup;

    if (summary == null) {
        return;
    }

    // title
    //var title = document.getElementsByTagName("title")[0];

    // scoreboard
    var homeTeamName1 = document.getElementById("homeTeamName1");
    var awayTeamName1 = document.getElementById("awayTeamName1");
    var homeTeamImg = document.getElementById("homeTeamImg");
    var awayTeamImg = document.getElementById("awayTeamImg");
    // livestats
    var homeTeamName2 = document.getElementById("homeTeamName2");
    var awayTeamName2 = document.getElementById("awayTeamName2");
    var homeTeamName3 = document.getElementById("homeTeamName3");
    var awayTeamName3 = document.getElementById("awayTeamName3");
    var homeTeamName4 = document.getElementById("homeTeamName4");
    var awayTeamName4 = document.getElementById("awayTeamName4");

    // Update team names
    //title.text = summary.hTeam + " - " + summary.aTeam;
    
    homeTeamName1.innerHTML = summary.hTeam;
    awayTeamName1.innerHTML = summary.aTeam;

    if (homeTeamName2 != null) {
        homeTeamName2.innerHTML = summary.hTeam;
        awayTeamName2.innerHTML = summary.aTeam;
        // Not showing card stats anymore
        //homeTeamName3.innerHTML = summary.hTeam;
        //awayTeamName3.innerHTML = summary.aTeam;
        homeTeamName4.innerHTML = summary.hTeam;
        awayTeamName4.innerHTML = summary.aTeam;
    }

    // Update shirts
    if (lineup != null) {
        homeTeamImg.src = "images/shirt/" + lineup.home.id + ".gif";
        awayTeamImg.src = "images/shirt/" + lineup.away.id + ".gif";
    }

}

// ------------------------------------------
// Games tab
// ------------------------------------------
function gamesUpdate() {
    var games = gamesXmlParser.getGames();
    
    var html = "";
    for (var i = 0; i < games.length; i++) {
        var game = games[i];
        //check if customer should have all tabs, removed 20080327 as requested from Mikael
        //var teamExists = true;
        /*for (var j = 0; j < gTeams.length; j++) {
            var teamId = gTeams[j];
            if (game.home.id == teamId||teamId==-1) {
                teamExists = true;
                break;
            }
        } */

        //if(teamExists){
        var result = game.home.sname + " - " + game.away.sname + " "
            + game.home.score + " - " + game.away.score;
            
        var className = "unselected";
        if ( (i == 0 && gGameId == -1) || game.id == gGameId) {
            if (gGameId == -1) {
                gGameId = game.id;
            }
            className = "selected";
            
            // change title
            var title = document.getElementsByTagName("title")[0];
            title.text = result;
        }
        
        html += "<div class='tab " + className + "' title='" + game.home.name + " - " 
            + game.away.name + "'>";
            
        if (className == "unselected") {
            html += "<a href='?" + buildHref(game.id) + "'>";
        }
        html += result;
        if (className == "unselected") {
            html += "</a>";
        }
        
        html += "</div>";
       //}
    }
    
    // update container
    var container = document.getElementById("gamesContainer");
    
    container.innerHTML = html;
 
    function buildHref(gameId) {
        var href = "gameId=" + gameId;
        href += "&amp;leagueId=" + gLeagueId;
        href += "&amp;partner=" + gPartner;
        href += "&amp;lang=" + gLang;

        if (gDate != '') {
            href += "&amp;date=" + gDate;
        }
        
        return href;
    }
       
}

