﻿$(function() {
    initializeKnockoutTree();
});

function initializeKnockoutTree() {
    $("#divKnockoutTreeContent").css("width", ($(".KOStageContent").length * 325) + "px");

    window.initialStage = true;
    window.indexTreeLine = 0;
    AlignStages();
}


function AlignDivs(div1, div2) {
    var Ydiv1 = $(div1).offset().top;
    var Ydiv2 = $(div2).offset().top;
    var marginT = $(div1).css("marginTop");
    var distance = Ydiv2 - Ydiv1;

    marginT = marginT.replace('px', '');
    var NewMargin = (Math.abs(distance) + parseInt(marginT));

    if (distance === 0) {
        return;
    }
    else
        if (distance > 0) {
        $(div1).css("margin-top", NewMargin + "px");
    }
    else {
        $(div2).css("margin-top", NewMargin + "px");
    }
}

function GetTop(element) {
    return $(element).position().top + parseInt($(element).css("marginTop").replace("px", ""));
}

function AlignDivsToMiddle(div1, div2, divMiddle) {
    var div1Y = GetTop(div1);
    var div2Y = GetTop(div2);
    var divMiddleY = GetTop(divMiddle);

    var targetY = (div1Y + div2Y + $(div2).outerHeight()) * 0.5 - $(divMiddle).outerHeight() * 0.5;
    var divMiddleTopMargin = parseInt($(divMiddle).css("marginTop").replace("px", ""));

    $(divMiddle).css("marginTop", (divMiddleTopMargin + targetY - divMiddleY) + "px");

    DrawTreeLine(div1, div2);
}

function DrawTreeLine(div1, div2) {
    window.indexTreeLine++;
    id = window.indexTreeLine;

    var distanceD1D2 = ($(div2).offset().top - $(div1).offset().top);
    var nextVertical = $(div1).parent().parent().next();

    var posD1 = $(div1).offset().top;
    var marginTopD1 = $(div1).css("marginTop");
    marginTopD1 = marginTopD1.replace("px", "");

    var posD2 = $(div2).offset().top;
    var marginTopD2 = $(div2).css("marginTop");
    marginTopD2 = marginTopD2.replace("px", "");

    nextVertical.append("<div id='divTreeLine" + id + "' style= 'border-bottom:0px solid gray; height:" + distanceD1D2 + "px;"
        + " position:absolute; top:" + (posD1) + "px;"
        + " margin-top:0px; width:100% '>"
        + "<div style='float:left; height:100%; border:1px solid gray; margin-top:2px;'></div>"
        + "<div style='float:right; width:60px; height:0px; border:1px solid gray; position:absolute; margin-top:" + (distanceD1D2 / 2) + "px'></div>"
        + "</div>");

    var divTreeLine = $("#divTreeLine" + id);

    divTreeLinePos = $(divTreeLine).offset().top; 		//***  39 = (heightMatch / 2) - 2 (border) todo change make var 84
    var locationTreeNode = posD1 - nextVertical.offset().top + 39;  //

    $(divTreeLine).css("top", locationTreeNode + "px");
}

function AlignStages() {
    var arrStages = $(".KOStageContent");
    var i = 0;
    while (i <= arrStages.length && AlignNextStage(arrStages[i], arrStages[i + 1])) {
        window.initialStage = false; //(i == 0);
        i++;
    }
}

function AlignNextStage(currentStage, nextStage) {
    var currentStageTeams = $(currentStage).attr("id")
    var currentStageMatches = $(currentStage).children(".pnlRound");

    var nextStageTeams = $(nextStage).attr("id")
    var nextStageMatches = $(nextStage).children(".pnlRound");

    var indexMatch = 0;
    while (indexMatch < nextStageMatches.length
        && SortMatchInStage(currentStageMatches, nextStage, nextStageMatches[indexMatch])) {
        indexMatch++;
    }

    return true;
}

function SortTeamInStage(currentStageMatches, prevStageMatches, TeamID) {
    var match1 = getMatchForTeam(prevStageMatches, TeamID);
    var match2 = getMatchForTeam(currentStageMatches, TeamID);

    if (match1 != -1 && match2 != -1)
        AlignDivs(match1, match2);
}

function SortMatchInStage(prevStageMatches, currentStageMatches, match) {
    var homeTeamID = getTeamName("Home", match);
    var awayTeamID = getTeamName("Away", match);

    var match1 = getMatchForTeam(prevStageMatches, homeTeamID);
    var match2 = getMatchForTeam(prevStageMatches, awayTeamID);

    if (match1 != -1 && match2 != -1 && match != -1) {
        AlignDivsToMiddle(match1, match2, match);
    }

    return true;
}

function containsTeam(divMatch, teamID) {
    var text = $(divMatch).children(":first").children(":first").children(":first").text();

    if (text.indexOf(teamID) != -1) {
        return divMatch;
    }
    return text.indexOf(teamID) != -1;
}

function getMatchForTeam(Matches, teamID) {
    var match;
    for (i = 0; i < Matches.length; i++) {
        match = containsTeam(Matches[i], teamID);
        if (match != false) {
            return match;
        }
    }
    return -1;
}

function getTeamName(HomeAway, match) {
    return $("#" + $(match).attr("id") + " > div >  .KnockoutGame > div > .KnockoutTeam > a[id*='lnk" + HomeAway + "TeamName']").text();
}

/**
* Classes to support knockout tree
*/
var FSI = (function() {
    var itself = {};
    itself.Knockout = (function() {
        var itself = {};
        itself.stage = function(stageId, name, sequence) {
            var that = {};
            that.getId = function() {
                return stageId;
            };
            that.getName = function() {
                return name;
            };
            that.getSequence = function() {
                return sequence;
            };
            return that;
        };
        itself.group = function(groupId, name, sequence, stage) {
            var that = {};
            that.getId = function() {
                return groupId;
            };
            that.getName = function() {
                return name;
            };
            that.getSequence = function() {
                return sequence;
            };
            that.getStage = function() {
                return stage;
            };
            return that;
        };
        itself.round = function(roundId, name, sequence, group) {
            var that = {};
            that.getId = function() {
                return roundId;
            };
            that.getName = function() {
                return name;
            };
            that.getSequence = function() {
                return sequence;
            };
            that.getGroup = function() {
                return group;
            };
            return that;
        };
        itself.fixture = function(fixtureId, name, sequence, round, templateGroupName) {
            var that = {};
            var previousFixtures = [];
            that.getId = function() {
                return fixtureId;
            };
            that.getName = function() {
                return name;
                return templateGroupName;
            };
            that.getSequence = function() {
                return sequence;
            };
            that.getRound = function() {
                return round;
            };
            that.getTemplateGroupName = function() {
                return templateGroupName;
            };
            that.setPreviousFixtures = function(fixture1, fixture2) {
                previousFixtures[0] = fixture1;
                previousFixtures[1] = fixture2;
            };
            that.getPreviousFixtures = function() {
                return previousFixtures;
            };
            return that;
        };
        return itself;
    } ());
    return itself;
} ());

var Controls = (function() {
    var MATCH_CONTROL_WIDTH = 220, MATCH_CONTROL_HEIGHT = 80;

    function groupBannerControl(groupName, x, y, width, height) {
        var that = {};
        that.asHtml = function() {
            var s = [];
            s[s.length] = "<div style=\"background-color: lightgray; font-size: 150%; height: ";
            s[s.length] = height;
            s[s.length] = "px; left: ";
            s[s.length] = x;
            s[s.length] = "px; position: absolute; top: ";
            s[s.length] = y;
            s[s.length] = "px; width: ";
            s[s.length] = width;
            s[s.length] = "px; text-align: center;\">";
            s[s.length] = groupName;
            s[s.length] = "<\/div>";
            return s.join("");
        };
        that.renderOnCanvas = function(canvas) {
            canvas.innerHTML += that.asHtml();
        };
        return that;
    }

    function matchResultControl(matchdata, width, height) {
        var that = {};
        that.asHtml = function() {
            var s = [];
            s[s.length] = "<div style=\"height: ";
            s[s.length] = height;
            s[s.length] = "px; width: ";
            s[s.length] = width;
            s[s.length] = "px; text-align: center;\" class=\"KOFixturesList_ScoreTime\">";
            s[s.length] = "<div style=\"font-size: 75%; \">";
            s[s.length] = matchdata.matchDate;
            s[s.length] = "<\/div>";
            s[s.length] = "<div style=\"font-size: 125%; font-weight: bolder; height: ";
            s[s.length] = height * 0.25;
            s[s.length] = "px;\">";
            s[s.length] = "<a href=\"";
            s[s.length] = matchdata.fixtureUrl;
            s[s.length] = "\">";
            s[s.length] = matchdata.homeTeamFullTimeScore;
            s[s.length] = "<\/a>";
            s[s.length] = "<\/div>";
            s[s.length] = "<div>home<\/div>";
            s[s.length] = "<div style=\"font-size: 125%; font-weight: bolder; height: ";
            s[s.length] = height * 0.25;
            s[s.length] = "px;\">";
            s[s.length] = "<a href=\"";
            s[s.length] = matchdata.fixtureUrl;
            s[s.length] = "\">";
            s[s.length] = matchdata.awayTeamFullTimeScore;
            s[s.length] = "<\/a>";
            s[s.length] = "<\/div>";
            s[s.length] = "<div>away<\/div>";
            s[s.length] = "<\/div>";
            return s.join("");
        };
        that.renderOnCanvas = function(canvas) {
            canvas.innerHTML += that.asHtml();
        };
        return that;
    }

    var itself = {};
    itself.rectangle = function(id, x, y, width, height) {
        var that = {};
        that.getId = function() {
            return id;
        };
        that.renderOnCanvas = function(canvas) {
            var s = [];
            s[s.length] = "<div id=\"";
            s[s.length] = id;
            s[s.length] = "\" style=\"border: solid 1px gray; height: ";
            s[s.length] = height;
            s[s.length] = "px; left: ";
            s[s.length] = x;
            s[s.length] = "px; position: absolute; top: ";
            s[s.length] = y;
            s[s.length] = "px; width: ";
            s[s.length] = width;
            s[s.length] = "px;\"><\/div>";
            canvas.innerHTML += s.join("");
        };
        return that;
    };
    itself.horizontalLine = function(x, y, length) {
        var that = {};
        that.renderOnCanvas = function(canvas) {
            var s = [];
            s[s.length] = "<div style=\"border: solid 1px lightgray; height: 0px; left: ";
            s[s.length] = x + 1;
            s[s.length] = "px; padding: 0px; position: absolute; top: ";
            s[s.length] = y;
            s[s.length] = "px; width: ";
            s[s.length] = length - 1;
            s[s.length] = "px;\"><\/div>";
            canvas.innerHTML += s.join("");
        };
        return that;
    };
    itself.verticalLine = function(x, y, length) {
        var that = {};
        that.renderOnCanvas = function(canvas) {
            var s = [];
            s[s.length] = "<div style=\"border: solid 1px lightgray; height: ";
            s[s.length] = length;
            s[s.length] = "px; left: ";
            s[s.length] = x;
            s[s.length] = "px; padding: 0px; position: absolute; top: ";
            s[s.length] = y;
            s[s.length] = "px; width: 0px;\"><\/div>";
            canvas.innerHTML += s.join("");
        };
        return that;
    };
    itself.matchControl = function(matchdata) {
        var that = {};
        that.renderOnCanvas = function(canvas) {
            var s = [];
            s[s.length] = "<div style=\"height: ";
            s[s.length] = MATCH_CONTROL_HEIGHT;
            s[s.length] = "px;\" class=\"KnockoutGame\">";
            s[s.length] = "<table cellpadding=\"0\" cellspacing=\"0\" width=\"";
            s[s.length] = MATCH_CONTROL_WIDTH;
            s[s.length] = "\">";
            s[s.length] = "<tr valign=\"middle\" height=\"";
            s[s.length] = MATCH_CONTROL_HEIGHT * 0.5;
            s[s.length] = "\">";
            s[s.length] = "<td style=\"border-bottom: solid 1px black; padding: 2px; vertical-align: middle; width: 80%;\">";
            s[s.length] = "<a href=\"";
            s[s.length] = matchdata.homeTeamUrl;
            s[s.length] = "\">";
            s[s.length] = "<img src=\"";
            s[s.length] = matchdata.homeTeamImageUrl;
            s[s.length] = "\" class=\"KOFixturesList_TeamLogo\"\/>";
            s[s.length] = matchdata.homeTeamName;
            s[s.length] = "<\/a>";
            s[s.length] = "<\/td>";
            s[s.length] = "<td rowspan=\"2\">";
            s[s.length] = matchResultControl(matchdata, MATCH_CONTROL_WIDTH * 0.20, MATCH_CONTROL_HEIGHT).asHtml();
            s[s.length] = "<\/td>";
            s[s.length] = "<\/tr>";
            s[s.length] = "<tr valign=\"middle\" height=\"";
            s[s.length] = MATCH_CONTROL_HEIGHT  * 0.5;
            s[s.length] = "\">";
            s[s.length] = "<td style=\"padding: 2px; vertical-align: middle; width: 80%;\">";
            s[s.length] = "<a href=\"";
            s[s.length] = matchdata.awayTeamUrl;
            s[s.length] = "\">";
            s[s.length] = "<img src=\"";
            s[s.length] = matchdata.awayTeamImageUrl;
            s[s.length] = "\" class=\"KOFixturesList_TeamLogo\" \/>";
            s[s.length] = matchdata.awayTeamName;
            s[s.length] = "<\/a>";
            s[s.length] = "<\/td>";
            s[s.length] = "<\/tr>";
            s[s.length] = "<\/table>";
            s[s.length] = "<\/div>";
            canvas.innerHTML = s.join("");
        };
        return that;
    }
    itself.tree = function(listener) {
        /**
        * listener should be an object with the following methods:
        *
        *  getFixtures()
        *  getRounds() 
        *  handleControlRenderedForFixture(controlId, fixtureId) - This is called when a control has been rendered
        *   to represent the fixture.
        *   controlId is the id of the control that has been rendered; this id can be used to access the 
        *       element and populate it with other data. 
        *   fixtureId is the id for which the control has been created.
        *
        */
        var FIXTURE_INTERLEAVE = 20, ROUND_INTERLEAVE = 50, GROUP_BANNER_HEIGHT = 25;

        var countedFixtures = {}, drawnFixtures = {};

        function createTreeForFixtureAtPosition(fixture, canvas, position) {
            if (isFixtureDrawn(fixture)) {
                return;
            }
            var expectedWidth = (fixture.getRound().getSequence() + 1) * (MATCH_CONTROL_WIDTH + ROUND_INTERLEAVE),
				expectedHeight = (MATCH_CONTROL_HEIGHT + FIXTURE_INTERLEAVE) * Math.pow(2, fixture.getRound().getSequence() - getStartingRound(fixture));
            if (fixture.getTemplateGroupName() !== null &&
                    fixture.getTemplateGroupName() !== undefined && fixture.getTemplateGroupName() !== "") {
                var groupBannerRectangle = groupBannerControl(fixture.getTemplateGroupName(),
                    position.x, position.y, expectedWidth, GROUP_BANNER_HEIGHT);
                groupBannerRectangle.renderOnCanvas(canvas);
                position.y += GROUP_BANNER_HEIGHT;
            }
            var initialPosition = {
                x: position.x + (fixture.getRound().getSequence() * (MATCH_CONTROL_WIDTH + ROUND_INTERLEAVE)),
                y: position.y + ((expectedHeight - MATCH_CONTROL_HEIGHT) * 0.5)
            };
            renderFixtureTriplet(fixture, canvas, initialPosition);
            return { width: expectedWidth, height: expectedHeight };
        }

        function getStartingRound(fixture) {
            var startingRound = fixture.getRound().getSequence();
            var previousFixtures = fixture.getPreviousFixtures();
            if (previousFixtures.length === 2) {
                var temp1 = getStartingRound(previousFixtures[0]),
                    temp2 = getStartingRound(previousFixtures[1]);
                if (temp1 < startingRound) {
                    startingRound = temp1;
                }
                if (temp2 < startingRound) {
                    startingRound = temp2;
                }
            }
            countedFixtures[fixture.getId()] = fixture;
            return startingRound;
        }

        function isFixtureCounted(fixture) {
            var fixtureId = fixture.getId();
            return countedFixtures[fixtureId] !== undefined && countedFixtures[fixtureId] !== null;
        }

        function renderFixtureTriplet(fixture, canvas, initialPosition) {
            var previousFixtures = fixture.getPreviousFixtures();
            if (previousFixtures.length === 2 &&
								(!isFixtureDrawn(previousFixtures[0]) && !isFixtureDrawn(previousFixtures[1]))) {
                var position1 = { x: initialPosition.x - MATCH_CONTROL_WIDTH - ROUND_INTERLEAVE,
                    y: initialPosition.y - (Math.pow(2, previousFixtures[0].getRound().getSequence()) *
										(MATCH_CONTROL_HEIGHT + FIXTURE_INTERLEAVE) * 0.5)
                };
                renderFixtureTriplet(previousFixtures[0], canvas, position1);
                var position2 = { x: initialPosition.x - MATCH_CONTROL_WIDTH - ROUND_INTERLEAVE,
                    y: initialPosition.y + (Math.pow(2, previousFixtures[1].getRound().getSequence()) *
										(MATCH_CONTROL_HEIGHT + FIXTURE_INTERLEAVE) * 0.5)
                };
                renderFixtureTriplet(previousFixtures[1], canvas, position2);
                // draw the joining lines
                Controls.verticalLine(position1.x + MATCH_CONTROL_WIDTH + (ROUND_INTERLEAVE * 0.5),
									position1.y + (MATCH_CONTROL_HEIGHT * 0.5), position2.y - position1.y).renderOnCanvas(canvas);
                Controls.horizontalLine(position1.x + MATCH_CONTROL_WIDTH,
									position1.y + (MATCH_CONTROL_HEIGHT * 0.5), ROUND_INTERLEAVE * 0.5).renderOnCanvas(canvas);
                Controls.horizontalLine(position1.x + MATCH_CONTROL_WIDTH,
									position2.y + (MATCH_CONTROL_HEIGHT * 0.5), ROUND_INTERLEAVE * 0.5).renderOnCanvas(canvas);
                Controls.horizontalLine(initialPosition.x - (ROUND_INTERLEAVE * 0.5),
									initialPosition.y + (MATCH_CONTROL_HEIGHT * 0.5), ROUND_INTERLEAVE * 0.5).renderOnCanvas(canvas);
            }
            var rectangle = Controls.rectangle("Rectangle_" + fixture.getId(),
                initialPosition.x, initialPosition.y, MATCH_CONTROL_WIDTH, MATCH_CONTROL_HEIGHT);
            rectangle.renderOnCanvas(canvas);
            listener.handleControlRenderedForFixture(rectangle.getId(), fixture.getId());
            drawnFixtures[fixture.getId()] = fixture;
        }

        function isFixtureDrawn(fixture) {
            var fixtureId = fixture.getId();
            return drawnFixtures[fixtureId] !== undefined && drawnFixtures[fixtureId] !== null;
        }

        var that = {};
        that.renderOnCanvas = function(canvas) {
            var fixtures = listener.getFixtures(),
			    rounds = listener.getRounds();
            var position = { x: 0, y: 0 };
            for (var i = 0; i < fixtures.length; i++) {
                if (fixtures[i].getRound().getId() === rounds[rounds.length - 1].getId()) {
                    var tree = createTreeForFixtureAtPosition(fixtures[i], canvas, position);
                    position.y += tree.height;
                }
            }
        };
        return that;
    };
    return itself;
} ());

