﻿var editMatchDetail = new Array();

function GenerateBracket(automationLevel, scheduledMatches, divIdToBind, eventScore, showEditOption, showScoreToEdit, isScoreEditable, isSingleEliminationOn, teamList) {

    //Here we need to set tournament bracket
    if (automationLevel == "Tournament") {
        $('#tournamentTypeText').text('');
        if (isSingleEliminationOn) {
            $('#tournamentTypeText').text('Single Elimination Bracket');
            GenerateSingleEliminationBracket(automationLevel, scheduledMatches, divIdToBind, eventScore, showEditOption, showScoreToEdit, isScoreEditable, teamList);
        } else {
            $('#tournamentTypeText').text('Double Elimination Winners Bracket');
            GenerateDoubleEliminationBracket(automationLevel, scheduledMatches, divIdToBind, eventScore, showEditOption, showScoreToEdit, isScoreEditable, teamList);
        }

    }
    //End
}

function GenerateBracket(automationLevel, scheduledMatches, divIdToBind, eventScore, showEditOption, showScoreToEdit, isScoreEditable, isSingleEliminationOn, teamList, showConflicts) {

    if (showEditOption == true)
        showConflicts = true;

    //Here we need to set tournament bracket
    if (automationLevel == "Tournament") {
        $('#tournamentTypeText').text('');
        if (isSingleEliminationOn) {
            $('#tournamentTypeText').text('Single Elimination Bracket');
            GenerateSingleEliminationBracket(automationLevel, scheduledMatches, divIdToBind, eventScore, showEditOption, showScoreToEdit, isScoreEditable, teamList, showConflicts);
        } else {
            $('#tournamentTypeText').text('Double Elimination Winners Bracket');
            GenerateDoubleEliminationBracket(automationLevel, scheduledMatches, divIdToBind, eventScore, showEditOption, showScoreToEdit, isScoreEditable, teamList, showConflicts);
        }

    }
    //End
}

function BindConflicts(scheduledMatches) {
    for (var i = 0; i < scheduledMatches.length; i++) {
        var scheduledMatch = scheduledMatches[i];
        if (scheduledMatch.ConflictsList != null && scheduledMatch.ConflictsList.length > 0) {
            var matchId = scheduledMatch.MatchID;
            var nextMatchId = scheduledMatch.NextMatch;

            var divId = 'editDiv' + matchId;
            var editDiv = $('#' + divId);
            if (editDiv != null) {
                var hardConflictList = null;
                var conflictLink, conflictList, displayConflictList;
                var conflictsList = scheduledMatch.ConflictsList;
                if (conflictsList != null) {
                    if (conflictsList.length > 0) {
                        hardConflictList = Enumerable.From(conflictsList)
                            .Where(function (x) {
                                return x.IsOverwritable == false;
                            })
                            .Select(function (x) {
                                return x;
                            }).ToArray();
                        if (hardConflictList.length > 0) {
                            conflictLink = $('<a class="hardConflictLink" href="javascript:void(0);"></a>');
                            conflictList = $('<div class="hardConflictList"></div>');
                            displayConflictList = hardConflictList;
                        } else {
                            conflictLink = $('<a class="conflictLink" href="javascript:void(0);"></a>');
                            conflictList = $('<div class="conflictList"></div>');
                            displayConflictList = conflictsList;
                        }
                        conflictLink.kendoTooltip({
                            content: function (e) {
                                var conflictDiv = $('<div></div>');
                                $.each(displayConflictList, function (index, value) {
                                    conflictDiv.append('<p>' + value.Message + '</p>');
                                    var isPortalNameHeaderAppend = false;
                                    var isPortalName = false;

                                    if (value.Matches.length > 0) {
                                        var conflictMatchesTable = $('<table width="700px" cellspacing="0" cellpadding="0"></table>');

                                        $.each(value.Matches, function (index3, value3) {
                                            if (value3.PortalID != 0) {
                                                isPortalName = true;
                                            }
                                        });

                                        $.each(value.Matches, function (index1, value1) {
                                            var matchDetailRow = $('<tr></tr>');

                                            if ($('.hdn_isUmbrellaScheduleEnabled').val() == "True") {
                                                if (isPortalName) {
                                                    if (isPortalNameHeaderAppend == false) {
                                                        conflictMatchesTable.append('<thead><tr><th>Portal</th><th>Order(Round)</th><th>Event Name</th><th>Match Date</th><th>Start-End Time</th><th>Team VS Team</th><th>Locations &amp; Fields</th></tr></thead>');
                                                        isPortalNameHeaderAppend = true;
                                                    }
                                                    if (value1.PortalID != 0) {
                                                        matchDetailRow.append('<td width="6%">' + value1.PortalName + '</td>');
                                                    }
                                                    else {
                                                        matchDetailRow.append('<td width="6%">&nbsp;&nbsp;</td>');
                                                    }
                                                }
                                                else {
                                                    if (isPortalNameHeaderAppend == false) {
                                                        conflictMatchesTable.append('<thead><tr><th>Order(Round)</th><th>Event Name</th><th>Match Date</th><th>Start-End Time</th><th>Team VS Team</th><th>Locations &amp; Fields</th></tr></thead>');
                                                        isPortalNameHeaderAppend = true;
                                                    }
                                                }
                                            } else {
                                                conflictMatchesTable.append('<thead><tr><th>Order(Round)</th><th>Event Name</th><th>Match Date</th><th>Start-End Time</th><th>Team VS Team</th><th>Locations &amp; Fields</th></tr></thead>');
                                            }

                                            matchDetailRow.append('<td width="5%">' + value1.MatchOrderNo + '(' + value1.RoundNumber + ')</td>');
                                            matchDetailRow.append('<td width="20%">' + value1.EventName + '</td>');
                                            matchDetailRow.append('<td width="16%">' + kendo.toString(kendo.parseDate(value1.Date), 'MM/dd/yyyy [ddd]') + '</td>');
                                            matchDetailRow.append('<td width="20%">' + kendo.format('{0:hh:mm tt}', kendo.parseDate(value1.StartTime)) + ' - ' + kendo.format('{0:hh:mm tt}', kendo.parseDate(value1.EndTime)) + '</td>');
                                            var team2 = (value1.EventDetail != null && value1.EventType.toLowerCase() == 'other') ? value1.EventDetail.EventName : value1.Team2;
                                            value1.EventType = '';
                                            if (value1.EventType == "Practice") {
                                                matchDetailRow.append('<td width="20%">' + value1.Team1 + '  ' + team2 + '</td>');
                                            } else {
                                                matchDetailRow.append('<td width="20%">' + value1.Team1 + ' <b>VS</b> ' + team2 + '</td>');
                                            }

                                            var locationName = value1.EventType.toLowerCase() != 'other' ? value1.LocationName + ' / ' + value1.FieldName : value1.LocationName;
                                            matchDetailRow.append('<td width="25%">' + locationName + '</td>');
                                            conflictMatchesTable.append(matchDetailRow);
                                        });
                                        conflictDiv.append(conflictMatchesTable);
                                    }
                                });
                                conflictList.append(conflictDiv);
                                return conflictList;
                            },
                            autoHide: true
                        }).data("kendoTooltip");

                        editDiv.append(conflictLink);
                    }
                }
            }
        }
    }
}

function GenerateDoubleEliminationBracket(automationLevel, scheduledMatches, divIdToBind, eventScore, showEditOption, showScoreToEdit, isScoreEditable, teamList, showConflicts) {

    $('#' + divIdToBind).html('');
    var wtotalRounds = Enumerable.From(scheduledMatches)
        .Where(function (x) {
            return x.IsLooserBracketMatch == false;
        })
        .Distinct(function (x) {
            return x.RoundNumber;
        })
        .OrderBy(function (x) {
            return x.RoundNumber;
        })
        .Select(function (x) {
            return {
                RoundNumber: x.RoundNumber,
            };
        }).ToArray();

    if (wtotalRounds.length < 1)
        return;

    var ltotalRounds = Enumerable.From(scheduledMatches)
        .Where(function (x) {
            return x.IsLooserBracketMatch == true;
        })
        .Distinct(function (x) {
            return x.RoundNumber;
        })
        .OrderBy(function (x) {
            return x.RoundNumber;
        })
        .Select(function (x) {
            return {
                RoundNumber: x.RoundNumber,
            };
        }).ToArray();


    var firstRoundMatches = Enumerable.From(scheduledMatches)
        .Where(function (x) {
            return x.RoundNumber == 1 && x.IsLooserBracketMatch == false;
        })
        .Select(function (x) {
            return x;
        }).ToArray();

    if (firstRoundMatches.length < 1)
        return;

    var teams = new Array;
	var totalTeamCount = 0;
    for (var j = 0; j < firstRoundMatches.length; j++) {
        var team1Name, team2Name;
        if (teamList) {
            var team1 = Enumerable.From(teamList)
                .Where(function (x) {
                    return x.TeamID == firstRoundMatches[j].HomeTeamID;
                })
                .Select(function (x) {
                    return x;
                }).FirstOrDefault(null);
            if (team1) {
                team1Name = "(" + team1.TeamRank + ") " + team1.TeamName;
				totalTeamCount++;
            } else {
                team1Name = firstRoundMatches[j].Team1;
				if(firstRoundMatches[j].Team1Type != 2)
				{
					totalTeamCount++;
				}
            }
            var team2 = Enumerable.From(teamList)
                .Where(function (x) {
                    return x.TeamID == firstRoundMatches[j].AwayTeamID;
                })
                .Select(function (x) {
                    return x;
                }).FirstOrDefault(null);
            if (team2) {
                team2Name = "(" + team2.TeamRank + ") " + team2.TeamName;
				totalTeamCount++;
            } else {
                team2Name = firstRoundMatches[j].Team2;
				if(firstRoundMatches[j].Team2Type != 2)
				{
					totalTeamCount++;
				}
            }
        } else {
            team1Name = firstRoundMatches[j].Team1;
			if(firstRoundMatches[j].Team1Type != 2)
			{
				totalTeamCount++;
			}
            team2Name = firstRoundMatches[j].Team2;
			if(firstRoundMatches[j].Team2Type != 2)
			{
				totalTeamCount++;
			}
        }
        teams.push(new Array(team1Name, team2Name, firstRoundMatches[j].HomeTeamID, firstRoundMatches[j].AwayTeamID, firstRoundMatches[j].Team1Type, firstRoundMatches[j].Team2Type));
    }

    //Generate result
    //Winners bracket
    var result = new Array;
    var matchIds = new Array;
    var matchDetails = new Array;

    var gresults = new Array;
    var gmatchIds = new Array;
    var gmatchDetails = new Array;
    var maxRoundNo = 0;
    var roundMatchIds, roundMatchDetails, roundResult, round, roundMatches, match, gameResult, homeScore, awayScore, isPosted, isScoreAdded, matchScore, score, gameDetails;
    for (var k = 0; k < wtotalRounds.length; k++) {
        maxRoundNo = k + 1;
        round = wtotalRounds[k].RoundNumber;
        roundResult = new Array;
        roundMatchIds = new Array;
        roundMatchDetails = new Array;
        var grandFinaleMatchResult = new Array;
        var grandFinaleMatchIds = new Array;
        var grandFinaleMatchDetails = new Array;
        var extraGrandFinaleMatchResult = new Array;
        var extraGrandFinaleMatchIds = new Array;
        var extraGrandFinaleMatchDetails = new Array;
        var isGrandFinaleMatch = (k + 1) >= (wtotalRounds.length - 1) ? true : false;
        roundMatches = Enumerable.From(scheduledMatches)
            .Where(function (x) {
                return x.RoundNumber == round && x.IsLooserBracketMatch == false;
            })
            .Select(function (x) {
                return x;
            }).ToArray();
        if (roundMatches.length < 1)
            continue;
        for (var l = 0; l < roundMatches.length; l++) {
            match = roundMatches[l];
            gameResult = new Array;
            if (match.Team2Type == 2) { //For bye type game
                gameResult.push(1, 0, true);
                if (isGrandFinaleMatch) {
                    if ((k + 1) == (wtotalRounds.length - 1)) {
                        grandFinaleMatchResult.push(gameResult);
                    } else {
                        extraGrandFinaleMatchResult.push(gameResult);
                    }
                }
                else
                    roundResult.push(gameResult);
            } else {
                // First we need to find the score from list
                homeScore = 0;
                awayScore = 0;
                isPosted = false;
                isScoreAdded = false;
                matchScore = Enumerable.From(eventScore)
                    .Where(function (x) {
                        return x.MatchID == match.MatchID;
                    })
                    .Select(function (x) {
                        return x;
                    }).ToArray();
                if (matchScore != null && matchScore.length > 0) {
                    score = matchScore[0];
                    if (match.HomeTeamID == score.HomeTeamID) {
                        homeScore = score.WinScore;
                        awayScore = score.LostScore;
                    } else {
                        homeScore = score.LostScore;
                        awayScore = score.WinScore;
                    }
                    isPosted = score.IsPosted;
                    isScoreAdded = (homeScore != 0 || awayScore != 0) ? true : false;
                }

                gameResult.push(homeScore, awayScore, isPosted, isScoreAdded);
                if (isGrandFinaleMatch) {
                    if ((k + 1) == (wtotalRounds.length - 1)) {
                        grandFinaleMatchResult.push(gameResult);
                    } else {
                        extraGrandFinaleMatchResult.push(gameResult);
                    }
                }

                else
                    roundResult.push(gameResult);
            }
            if (isGrandFinaleMatch) {
                if ((k + 1) == (wtotalRounds.length - 1)) {
                    grandFinaleMatchIds.push(match.MatchID);
                } else {
                    extraGrandFinaleMatchIds.push(match.MatchID);
                }
            }

            else
                roundMatchIds.push(match.MatchID);
            gameDetails = {
                date: match.Date,
                startTime: match.StartTime,
                endTime: match.EndTime,
                locationName: match.LocationName,
                fieldName: match.FieldName,
                conflictsList: match.ConflictsList,
                orderNo: match.MatchOrderNo,
                isPastMatch: match.IsPastMatch,
                isLastMatch: match.isLastMatch,
                isLoserMatch: false,
                MatchRoundNo: round,
                IsGrandFinaleMatch: isGrandFinaleMatch,
                RoundNumber: match.RoundNumber,
                Team1: match.Team1,
                Team1Type: match.Team1Type,
                Team2: match.Team2,
                Team2Type: match.Team2Type,
                actionStatus: match.ActionStatus,
                note: match.Notes,
				homeTeamPlaceHolder: match.HomeTeamPlaceHolder,
				awayTeamPlaceHolder: match.AwayTeamPlaceHolder
            };
            if (isGrandFinaleMatch) {
                if ((k + 1) == (wtotalRounds.length - 1)) {
                    grandFinaleMatchDetails.push(gameDetails);
                } else {
                    extraGrandFinaleMatchDetails.push(gameDetails);
                }
            }

            else
                roundMatchDetails.push(gameDetails);
        }
        if (grandFinaleMatchResult.length > 0) {
            gresults.push(grandFinaleMatchResult);
            gmatchIds.push(grandFinaleMatchIds);
            gmatchDetails.push(grandFinaleMatchDetails);
        }
        else if (extraGrandFinaleMatchResult.length > 0) {
            var isNeedExtraMatch = false;
            if (extraGrandFinaleMatchResult[0][0].isScoreAdded)
                isNeedExtraMatch = true;
            gresults.push(extraGrandFinaleMatchResult);
            gmatchIds.push(extraGrandFinaleMatchIds);
            gmatchDetails.push(extraGrandFinaleMatchDetails);
        }
        else {
            result.push(roundResult);
            matchIds.push(roundMatchIds);
            matchDetails.push(roundMatchDetails);
        }
    }

    //Looser bracket
    var lresults = new Array;
    var lmatchIds = new Array;
    var lmatchDetails = new Array;
    var looserBracketMaxRoundNo = 0;
    var needToApplySeededAlgorithm = totalTeamCount > 8 ? true : false;
    for (var k = 0; k < ltotalRounds.length; k++) {
        looserBracketMaxRoundNo = ltotalRounds[k].RoundNumber;
        round = ltotalRounds[k].RoundNumber;
        roundResult = new Array;
        roundMatchIds = new Array;
        roundMatchDetails = new Array;
        roundMatches = Enumerable.From(scheduledMatches)
                        .Where(function (x) {
                            return x.RoundNumber == round && x.IsLooserBracketMatch == true;
                        })
                        .Select(function (x) {
                            return x;
                        }).ToArray();


        var currentRoundWinnerBracketMatches;
        if (round % 2 == 0) {

            if (round == 2 && needToApplySeededAlgorithm) {

                currentRoundWinnerBracketMatches = Enumerable.From(scheduledMatches)
                                                    .Where(function (x) {
                                                        return x.RoundNumber == round && x.IsLooserBracketMatch == false;
                                                    })
                                                    .OrderBy(function (x) {
                                                        return x.MatchOrderNo;
                                                    })
                                                    .Select(function (x) {
                                                        return x;
                                                    }).ToArray();

                let halfLength = Math.floor(currentRoundWinnerBracketMatches.length / 2);
                let currentRoundWinnerBracketFirstHalfMatches = currentRoundWinnerBracketMatches.slice(0, halfLength);
                let currentRoundWinnerBracketFirstSecondHalfMatches = currentRoundWinnerBracketMatches.slice(halfLength, currentRoundWinnerBracketMatches.length);
                currentRoundWinnerBracketMatches = [];

                for (var l = 0; l < currentRoundWinnerBracketFirstSecondHalfMatches.length; l++) {
                    currentRoundWinnerBracketMatches.push(currentRoundWinnerBracketFirstSecondHalfMatches[l]);
                }
                for (var l = 0; l < currentRoundWinnerBracketFirstHalfMatches.length; l++) {
                    currentRoundWinnerBracketMatches.push(currentRoundWinnerBracketFirstHalfMatches[l]);
                }               
            }
            else
            {
                currentRoundWinnerBracketMatches = Enumerable.From(scheduledMatches)
                                                                    .Where(function (x) {
                                                                        return x.RoundNumber == round && x.IsLooserBracketMatch == false;
                                                                    })
                                                                    .OrderByDescending(function (x) {
                                                                        return x.MatchOrderNo;
                                                                    })
                                                                    .Select(function (x) {
                                                                        return x;
                                                                    }).ToArray();
            }
        } else {
            currentRoundWinnerBracketMatches = Enumerable.From(scheduledMatches)
                                                .Where(function (x) {
                                                    return x.RoundNumber == round && x.IsLooserBracketMatch == false;
                                                })
                                                .Select(function (x) {
                                                    return x;
                                                }).ToArray();
            if (round == 3 && needToApplySeededAlgorithm)
            {
                let halfLength = Math.floor(currentRoundWinnerBracketMatches.length / 2);

                let currentRoundWinnerBracketFirstHalfMatches = currentRoundWinnerBracketMatches.slice(0, halfLength);
                let currentRoundWinnerBracketFirstSecondHalfMatches = currentRoundWinnerBracketMatches.slice(halfLength, currentRoundWinnerBracketMatches.length);
                currentRoundWinnerBracketMatches = [];               
               
                for (var l = 0; l < currentRoundWinnerBracketFirstHalfMatches.length; l++) {
                    currentRoundWinnerBracketMatches.push(currentRoundWinnerBracketFirstHalfMatches[l]);
                }
                for (var l = 0; l < currentRoundWinnerBracketFirstSecondHalfMatches.length; l++) {
                    currentRoundWinnerBracketMatches.push(currentRoundWinnerBracketFirstSecondHalfMatches[l]);
                }
            }
        }
        if (round == 1) {
            var looserBracketMatches = new Array;
            for (var i = 0; i < currentRoundWinnerBracketMatches.length; i = i + 2) {
                var match1 = currentRoundWinnerBracketMatches[i];
                var firstTeam;
                if (match1.Team2Type == 2 || match1.Team1Type == 2) {
                    firstTeam = "Bye";
                } else {
                    firstTeam = "G" + match1.MatchOrderNo + " Loss";
                }
                var match2 = currentRoundWinnerBracketMatches[i + 1];
                var secondTeam;
                if (match2.Team2Type == 2 || match2.Team1Type == 2) {
                    secondTeam = "Bye";
                } else {
                    secondTeam = "G" + match2.MatchOrderNo + " Loss";
                }
                var looserMatch = Enumerable.From(roundMatches)
                                    .Where(function (x) {
                                        return ((x.HomeTeamPlaceHolder == firstTeam || x.Team1 == firstTeam || x.HomeTeamPlaceHolder == match1.MatchOrderNo) && (x.AwayTeamPlaceHolder == secondTeam || x.Team2 == secondTeam || x.AwayTeamPlaceHolder == match2.MatchOrderNo))
                                        || ((x.HomeTeamPlaceHolder == secondTeam || x.Team1 == secondTeam || x.HomeTeamPlaceHolder == match2.MatchOrderNo) && (x.AwayTeamPlaceHolder == firstTeam || x.Team2 == firstTeam || x.AwayTeamPlaceHolder == match1.MatchOrderNo));
                                    })
                                    .Select(function (x) {
                                        return x;
                                    }).FirstOrDefault(null);

                looserBracketMatches.push(looserMatch);
            }
            roundMatches = looserBracketMatches;
        }
        if (round == 2) {
            var looserBracketMatches = new Array;
            for (var i = 0; i < currentRoundWinnerBracketMatches.length; i = i + 1) {
                var match1 = currentRoundWinnerBracketMatches[i];
                var firstTeam;
                if (match1.Team2Type == 2 || match1.Team1Type == 2) {
                    firstTeam = "Bye";
                } else {
                    firstTeam = "G" + match1.MatchOrderNo + " Loss";
                }
                var looserMatch = Enumerable.From(roundMatches)
                                    .Where(function (x) {
                                        return (x.HomeTeamPlaceHolder == firstTeam || x.Team1 == firstTeam || x.AwayTeamPlaceHolder == firstTeam || x.Team2 == firstTeam
                                            || x.HomeTeamPlaceHolder == match1.MatchOrderNo);
                                    })
                                    .Select(function (x) {
                                        return x;
                                    }).FirstOrDefault(null);

                looserBracketMatches.push(looserMatch);
            }
            roundMatches = looserBracketMatches;
        }
        if (roundMatches.length < 1)
            continue;
        for (var l = 0; l < roundMatches.length; l++) {
            match = roundMatches[l];
            gameResult = new Array;
            if (match.Team2Type == 2 || match.Team1Type == 2) { //For bye type game
                gameResult.push(1, 0, true);
                roundResult.push(gameResult);
            } else {
                // First we need to find the score from list
                homeScore = 0;
                awayScore = 0;
                isPosted = false;
                isScoreAdded = false;
                matchScore = Enumerable.From(eventScore)
                             .Where(function (x) {
                                 return x.MatchID == match.MatchID;
                             })
                            .Select(function (x) {
                                return x;
                            }).ToArray();
                if (matchScore != null && matchScore.length > 0) {
                    score = matchScore[0];
                    if (match.HomeTeamID == score.HomeTeamID) {
                        homeScore = score.WinScore;
                        awayScore = score.LostScore;
                    } else {
                        homeScore = score.LostScore;
                        awayScore = score.WinScore;
                    }
                    isPosted = score.IsPosted;
                    isScoreAdded = (homeScore != 0 || awayScore != 0) ? true : false;
                }

                gameResult.push(homeScore, awayScore, isPosted, isScoreAdded);
                roundResult.push(gameResult);
            }

            roundMatchIds.push(match.MatchID);

            var isLooserBracketLastMatch = false;
            if ((ltotalRounds.length == (k + 1)) && ((l + 1) == roundMatches.length))
                isLooserBracketLastMatch = true;

            gameDetails = {
                date: match.Date,
                startTime: match.StartTime,
                endTime: match.EndTime,
                locationName: match.LocationName,
                fieldName: match.FieldName,
                conflictsList: match.ConflictsList,
                orderNo: match.MatchOrderNo,
                isPastMatch: match.IsPastMatch,
                isLoserMatch: true,
                RoundNumber: match.RoundNumber,
                Team1: match.Team1,
                Team1Type: match.Team1Type,
                Team2: match.Team2,
                Team2Type: match.Team2Type,
                Team1ID: match.HomeTeamID,
                Team2ID: match.AwayTeamID,
                isLooserBracketLastMatch: isLooserBracketLastMatch,               
                actionStatus: match.ActionStatus,
                note: match.Notes,
				homeTeamPlaceHolder: match.HomeTeamPlaceHolder,
				awayTeamPlaceHolder: match.AwayTeamPlaceHolder
            };
            roundMatchDetails.push(gameDetails);
        }
        lresults.push(roundResult);
        lmatchIds.push(roundMatchIds);
        lmatchDetails.push(roundMatchDetails);
    }
    var finalResults = new Array;
    finalResults.push(result);
    finalResults.push(lresults);
    finalResults.push(gresults);
    var finalMatchIds = new Array;
    finalMatchIds.push(matchIds);
    finalMatchIds.push(lmatchIds);
    finalMatchIds.push(gmatchIds);
    var finalMatchDetails = new Array;
    finalMatchDetails.push(matchDetails);
    finalMatchDetails.push(lmatchDetails);
    finalMatchDetails.push(gmatchDetails);


    function savefn(data) {
        if (editMatchDetail != null)
            for (var i = 0; i < editMatchDetail.length; i++) {
                if (editMatchDetail[i][0].matchId == data[0].matchId) {
                    editMatchDetail[i][0].team1Score = data[0].team1Score;
                    editMatchDetail[i][0].team2Score = data[0].team2Score;

                    return;
                }
            }
        var sucessmsg = $('.sucessMsg');
        sucessmsg[0].innerHTML = "";
        editMatchDetail.push(data);
        editMatchDetail.sort(function (obj1, obj2) {
            return obj1[0].matchId - obj2[0].matchId;
        });
    }
    var singleElimination = {
        "teams": teams,
        "noOfTeams": (firstRoundMatches.length * 2),
        "results": finalResults,
        "matchIds": finalMatchIds,
        "matchDetails": finalMatchDetails
    };
    if ((firstRoundMatches.length * 2) <= 4) {
        looserBracketMaxRoundNo++;
    }
    if (showScoreToEdit == true) {
        $('#' + divIdToBind).bracket({
            init: singleElimination, /* data to initialize the bracket with */
            showEditOption: showEditOption,
            skipConsolationRound: true,
            save: savefn, /* without save() labels are disabled */
            isScoreEditable: isScoreEditable,
            maxRoundNo: maxRoundNo,
            looserBracketMaxRoundNo: looserBracketMaxRoundNo,
            skipSecondaryFinal: false,
            skipGrandFinalComeback: false
        });
    } else {
        $('#' + divIdToBind).bracket({
            init: singleElimination, /* data to initialize the bracket with */
            skipConsolationRound: true,
            showEditOption: showEditOption,
            maxRoundNo: maxRoundNo,
            looserBracketMaxRoundNo: looserBracketMaxRoundNo,
            skipSecondaryFinal: false,
            skipGrandFinalComeback: false
        });

        jQuery('div.jQBracket .team div.label').width(150);
    }
}
function GenerateSingleEliminationBracket(automationLevel, scheduledMatches, divIdToBind, eventScore, showEditOption, showScoreToEdit, isScoreEditable, teamList, showConflicts) {

    $('#' + divIdToBind).html('');

    var totalRounds = Enumerable.From(scheduledMatches)
        .Distinct(function (x) {
            return x.RoundNumber;
        }).Select(function (x) {
            return {
                RoundNumber: x.RoundNumber,
            };
        }).ToArray();

    if (totalRounds.length < 1)
        return;

    var firstRoundMatches = Enumerable.From(scheduledMatches)
                            .Where(function (x) {
                                return x.RoundNumber == 1;
                            })
                            .Select(function (x) {
                                return x;
                            }).ToArray();

    if (firstRoundMatches.length < 1)
        return;

    var teams = new Array;
    for (var j = 0; j < firstRoundMatches.length; j++) {
        var team1Name, team2Name;
        if (teamList) {
            var team1 = Enumerable.From(teamList)
                            .Where(function (x) {
                                return x.TeamID == firstRoundMatches[j].HomeTeamID;
                            })
                            .Select(function (x) {
                                return x;
                            }).FirstOrDefault(null);
            if (team1) {
                team1Name = "(" + team1.TeamRank + ") " + team1.TeamName;
            } else {
                team1Name = firstRoundMatches[j].Team1;
            }
            var team2 = Enumerable.From(teamList)
                            .Where(function (x) {
                                return x.TeamID == firstRoundMatches[j].AwayTeamID;
                            })
                            .Select(function (x) {
                                return x;
                            }).FirstOrDefault(null);
            if (team2) {
                team2Name = "(" + team2.TeamRank + ") " + team2.TeamName;
            } else {
                team2Name = firstRoundMatches[j].Team2;
            }
        } else {
            team1Name = firstRoundMatches[j].Team1;
            team2Name = firstRoundMatches[j].Team2;
        }
        teams.push(new Array(team1Name, team2Name, firstRoundMatches[j].HomeTeamID, firstRoundMatches[j].AwayTeamID, firstRoundMatches[j].Team1Type, firstRoundMatches[j].Team2Type));
    }

    //Generate result
    var result = new Array;
    var matchIds = new Array;
    var matchDetails = new Array;
    var maxRoundNo = 0;

    for (var k = 0; k < totalRounds.length; k++) {
        maxRoundNo = k + 1;

        var round = totalRounds[k].RoundNumber;
        var roundResult = new Array;
        var roundMatchIds = new Array;
        var roundMatchDetails = new Array;

        var roundMatches = Enumerable.From(scheduledMatches)
                            .Where(function (x) {
                                return x.RoundNumber == round;
                            })
                            .Select(function (x) {
                                return x;
                            }).ToArray();

        if (roundMatches.length < 1)
            continue;
        for (var l = 0; l < roundMatches.length; l++) {
            var match = roundMatches[l];
            var gameResult = new Array;
            var homeScore = 0, awayScore = 0;
            var isPosted = false;
            var isScoreAdded = false;

            if (match.Team2Type == 2) { //For bye type game
                var matchId = Enumerable.From(scheduledMatches)
                    .Where(function (x) {
                        return x.HomeTeamPlaceHolder == "G" + match.MatchOrderNo + " Win" || x.AwayTeamPlaceHolder == "G" + match.MatchOrderNo + " Win";
                    })
                .Select(function (x) {
                    return x.MatchID;
                }).ToArray();

                if (matchId != null)
                {   
                    var matchScore = Enumerable.From(eventScore)
                   .Where(function (x) {
                       return x.MatchID == matchId;
                   })
                   .Select(function (x) {
                       return x;
                   }).ToArray();

                    if (matchScore != null && matchScore.length > 0) {
                        var score = matchScore[0];
                        if (match.HomeTeamID == score.HomeTeamID) {
                            homeScore = score.WinScore;
                            awayScore = score.LostScore;
                        } else {
                            homeScore = score.LostScore;
                            awayScore = score.WinScore;
                        }
                        isPosted = score.IsPosted;
                        isScoreAdded = (homeScore != 0 || awayScore != 0 || isPosted) ? true : false;
                        match.isScoreAdded = isScoreAdded;
                    }
                }
                gameResult.push(1, 0, true,isScoreAdded);
                roundResult.push(gameResult);
            } else {
                // First we need to find the score from list
                
                var matchScore = Enumerable.From(eventScore)
                    .Where(function (x) {
                        return x.MatchID == match.MatchID;
                    })
                    .Select(function (x) {
                        return x;
                    }).ToArray();

                if (matchScore != null && matchScore.length > 0) {
                    var score = matchScore[0];
                    if (match.HomeTeamID == score.HomeTeamID) {
                        homeScore = score.WinScore;
                        awayScore = score.LostScore;
                    } else {
                        homeScore = score.LostScore;
                        awayScore = score.WinScore;
                    }
                    isPosted = score.IsPosted;
                    isScoreAdded = (homeScore != 0 || awayScore != 0) ? true : false;
                }

                gameResult.push(homeScore, awayScore, isPosted, isScoreAdded);
                roundResult.push(gameResult);
            }
            roundMatchIds.push(match.MatchID);
            var gameDetails = {
                date: match.Date, startTime: match.StartTime,
                endTime: match.EndTime, locationName: match.LocationName, fieldName: match.FieldName, actionStatus: match.ActionStatus, note: match.Notes,
                conflictsList: match.ConflictsList, orderNo: match.MatchOrderNo, isPastMatch: match.IsPastMatch, nextMatchId: match.NextMatch
            };
            roundMatchDetails.push(gameDetails);
        }
        result.push(roundResult);
        matchIds.push(roundMatchIds);
        matchDetails.push(roundMatchDetails);
    }
    function savefn(data) {
        if (editMatchDetail != null)
            for (var i = 0; i < editMatchDetail.length; i++) {
                if (editMatchDetail[i][0].matchId == data[0].matchId) {
                    editMatchDetail[i][0].team1Score = data[0].team1Score;
                    editMatchDetail[i][0].team2Score = data[0].team2Score;
                    return;
                }
            }
        var sucessmsg = $('.sucessMsg');
        sucessmsg[0].innerHTML = "";
        editMatchDetail.push(data);
        editMatchDetail.sort(function (obj1, obj2) {
            return obj1[0].matchId - obj2[0].matchId;
        });
    }

    var finalresults = new Array;
    finalresults.push(result);
    var finalmatchIds = new Array;
    finalmatchIds.push(matchIds);
    var finalmatchDetails = new Array;
    finalmatchDetails.push(matchDetails);
    var singleElimination = {
        "teams": teams,
        "results": finalresults,
        "matchIds": finalmatchIds,
        "matchDetails": finalmatchDetails
    };
    if (showScoreToEdit == true) {
        $('#' + divIdToBind).bracket({
            init: singleElimination, /* data to initialize the bracket with */
            skipConsolationRound: true,
            showEditOption: showEditOption,
            save: savefn, /* without save() labels are disabled */
            isScoreEditable: isScoreEditable,
            maxRoundNo: maxRoundNo,
            showConflicts: showConflicts
        });
    } else {
        $('#' + divIdToBind).bracket({
            init: singleElimination, /* data to initialize the bracket with */
            skipConsolationRound: true,
            showEditOption: showEditOption,
            maxRoundNo: maxRoundNo,
            showConflicts: showConflicts
        });

        jQuery('div.jQBracket .team div.label').width(150);
    }
}
