﻿

var wwwroot = "";

var Port = location.port;

if (Port != "")
    wwwroot = "taptiming.com/";


var SERVER = location.protocol + "//" + location.host + "/" + wwwroot;
var imageLink = "";

var isRaceAlreadySealected = false;

var isCompareLapDiv = "";
var isScaleDiv = "";
var isStaticsDiv = "";
var isCompetitorArray = new Array();
var raceArray = new Array();
var raceComparisionDivArray = new Array();
function MaintainRiderState(raceNo)
{
    var isMainDiv = $("#MainDiv").html();

    raceComparisionDivArray[raceNo] = [isMainDiv, competitorArray, selectedArray];
    selectedArray = new Array();
}

function DeliverState(raceNo)
{
    $("#MainDiv").html(raceComparisionDivArray[raceNo][0]);
    competitorArray = raceComparisionDivArray[raceNo][1];
    $.each(raceComparisionDivArray[raceNo][2], function (iIndex, ttData)
    {
        $("#riderSelect_" + iIndex).val(ttData);
    });
    selectedArray = raceComparisionDivArray[raceNo][2];
   
}

function CompLap()
{
    var raceNo = $("#AllRaceInEvent").val();
    if (raceNo >= 0)
    {

        if (ttEvent.races[raceNo].teams.length > 2)
        {
            
            if (!isRaceAlreadySealected)
            {
                CompareByLaps(raceNo);
                $("#line20").hide();
                $("#ScrollConatinerDivAll").hide();
                $("#HoldCurrentRace").val(raceNo);
            }
            else
            {

                MaintainRiderState($("#HoldCurrentRace").val());
                raceArray[$("#HoldCurrentRace").val()] = $("#HoldCurrentRace").val();
                if (raceArray[raceNo] != undefined)
                {
                    DeliverState(raceNo);
                    if (selectedArray.length > 0)
                    {
                        $("#reset_Anchor").html(" <img src='" + imageLink + "Reset.png' />");
                        $("#reset_Anchor").css("cursor", "pointer");
                    }
                    else
                    {
                        $("#reset_Anchor").html(" <img src='" + imageLink + "Reset-click.png' />");
                        $("#reset_Anchor").css("cursor", "default");
                    }
                }
                else
                {
                    CompareByLaps(raceNo);
                    $("#line20").hide();
                    $("#ScrollConatinerDivAll").hide();
                    $("#reset_Anchor").html(" <img src='" + imageLink + "Reset-click.png' />");
                    $("#reset_Anchor").css("cursor", "default");
                }
               
                $("#HoldCurrentRace").val(raceNo);
            }
            isRaceAlreadySealected = true;
           
        }
        else
        {
            $("#MainDiv").html('<p>This Race was not run </p>');
        }
        
    }
    else
    {
        $("#MainDiv").html('');
    }
  
   
}

var isSingleRace = false;
function CompareLaps()
{
    
    var resultStr = "<input type='hidden' id='HoldCurrentRace' /><div id='resultComparebyLap'>";
    resultStr += "<div style='font-size:small; clear:both;'>";
    resultStr += "<p style='color:#580387;font-size:14px;font-family:helvetica, verdana, tahoma;'>Please select a race. Once you have selected a race you will be able to select the riders that you wish to compare. If a race has been greyed out, it means that the race was not run.</p>";
    resultStr += "<div style='float:left; width:290px;text-align:left;'>";
    resultStr += "<select style='background-color:#DCD2E6; color:#551B8B;' onChange='CompLap();' id='AllRaceInEvent'>";
    var RaceCount = ttEvent.races.length;
    if (RaceCount != 1)
    {
        resultStr += "<option value='-1' > -- Choose Race --</option>";
        $.each(ttEvent.races, function (iRaceNo, ttRaceData)
        {
            if (ttRaceData.teams.length > 0)
            {
                resultStr += "<option value='" + iRaceNo + "'> " + ttRaceData.title + "</option>";
            }
            else
            {
                resultStr += "<option style='color:gray;' title=' Race was not run' disabled='disabled' value='" + iRaceNo + "'> " + ttRaceData.title + " (Race was not run)</option>";
            }
        });
       
    }
    else
    {
        isSingleRace = true;
        $.each(ttEvent.races, function (iRaceNo, ttRaceData)
        {
            resultStr += "<option value='" + iRaceNo + "'> " + ttRaceData.title + "</option>";
        });
   }
  resultStr += " </select>";
    resultStr += "</div>";

    resultStr += "<div style='float:left;'>";
    resultStr += "<a onClick='Reset();' id='reset_Anchor' style='cursor:default;' > <img src='"+ imageLink +"Reset-click.png' alt=''/></a>";
    resultStr += "</div>";
    resultStr += "<div style='clear:both;'></div>";
    resultStr += "</div>";
    resultStr += "<div > <div style='min-height:280px;' id='MainDiv'>&nbsp;</div> <div>"
    resultStr += "</div>";
    $("#mainRaceBody").html(resultStr);
    $("#reset_Anchor").html(" <img src='"+ imageLink +"Reset-click.png' />");
    $("#reset_Anchor").css("cursor", "default");

    if (isSingleRace)
    {
        CompLap();
    }
}

function CheckAllnonSoloByCategory(ttcompetitorsData, raceNo)
{
    var isAllTeambycategory = true;
    $.each(ttcompetitorsData, function (iCategoryCompetitor, ttCompetitorNo)
    {
        if (ttEvent.races[raceNo].teams[ttCompetitorNo].isSolo == 1)
        {
            isAllTeambycategory = false;
            return isAllTeambycategory;
        }
    });
    return isAllTeambycategory;
}

function CheckAllnonSoloByOrder(ttRacesData)
{
    var isAllTeambyorder = true;
    $.each(ttRacesData.teams, function (iTeam, tTeamData)
    {
        if (tTeamData.isSolo == 1)
        {
            isAllTeambyorder = false;
            return isAllTeambyorder;
        }
    });
    return isAllTeambyorder;
}

var showLapsDetail = 6;
function TeamLapDetail(LapData, RaceNo, Categoryno, Rowno)
{
   
    var resultStr = "";
    var competitorArray = new Array();
    var countLapIndex = 0;
    $.each(LapData, function (iLapno, ttLapData)
    {
        if (iLapno == 0)
        {
            competitorArray[countLapIndex] = [ttLapData.competitorNo, iLapno, ttLapData.competitorName];
            countLapIndex = countLapIndex + 1;
        }
        else
        {
            var iAlreadyExist = false;
            var iAlreadyIndex = 0;
            for (var iIndex = 0; iIndex < competitorArray.length; iIndex++)
            {
                if (competitorArray[iIndex][0] == ttLapData.competitorNo)
                {
                    iAlreadyExist = true;
                    iAlreadyIndex = iIndex;
                }


            }
            if (iAlreadyExist)
            {
                competitorArray[iAlreadyIndex] = [ttLapData.competitorNo, competitorArray[iAlreadyIndex][1] + "," + iLapno, ttLapData.competitorName];
            }
            else
            {
                competitorArray[countLapIndex] = [ttLapData.competitorNo, iLapno, ttLapData.competitorName];
                countLapIndex = countLapIndex + 1;
            }
        }
    });
    resultStr += "<div style='clear:both;'> ";
    resultStr += "<input type='hidden' id='currentShowing_" + RaceNo + "_" + Categoryno + "_" + Rowno + "' value='" + showLapsDetail + "' /> ";
    resultStr += "<input type='hidden' id='race_maxLaps_" + RaceNo + "_" + Categoryno + "_" + Rowno + "' value='" + LapData.length + "' /> ";
    resultStr += "<input type='hidden' id='maxNoRows_" + RaceNo + "_" + Categoryno + "_" + Rowno + "'  value='" + competitorArray.length + "' />";
    resultStr += "<div class='Heading_Number'> No.</div>";
    resultStr += "<div class='Heading_Name_inner' >Name</div>";
    resultStr += "<div class='Div_Image'>&nbsp;</div>";
    for (var iIndex = 0; iIndex < LapData.length; iIndex++)
    {
        if (iIndex < showLapsDetail)
        {
            resultStr += "<div id='innerHeading_" + RaceNo + "_" + Categoryno + "_" + Rowno + "_" + iIndex + "' class='Heading_Lap_show'>Lap " + (iIndex + 1) + "</div>";
        }
        else
        {
            resultStr += "<div id='innerHeading_" + RaceNo + "_" + Categoryno + "_" + Rowno + "_" + iIndex + "' class='Heading_Lap_Hide'>Lap " + (iIndex + 1) + "</div>";
        }
    }
    resultStr += "<div class='Div_Image'>&nbsp;</div><div style='Clear:both;'></div></div>";
    $.each(competitorArray, function (iArrayindex, ttArrayData)
    {
        resultStr += "<div style='clear:both;'>";
        resultStr += "<div class='Div_Number'>" + ttArrayData[0] + "</div>";
        resultStr += "<div class='Div_Name_inner' title='" + ttArrayData[2] + "'>" + ttArrayData[2] + "</div>";
        resultStr += "<div class='Div_Image' style='cursor:default;' id='innerLeft_" + RaceNo + "_" + Categoryno + "_" + Rowno + "_" + iArrayindex +
                     "' onclick='ShiftleftByOrderInner(this)';>&nbsp;</div>";
        var lapNo = ttArrayData[1].split(',');
        for (var iIndex = 0; iIndex < LapData.length; iIndex++)
        {

            if (iIndex < showLapsDetail)
            {
                resultStr += "<div class='Div_Lap_Show' id='innerRow_" + RaceNo + "_" + Categoryno + "_" + Rowno + "_" + iArrayindex + "_" + iIndex + "'>";
            }
            else
            {
                resultStr += "<div class='Div_Lap_Hide' id='innerRow_" + RaceNo + "_" + Categoryno + "_" + Rowno + "_" + iArrayindex + "_" + iIndex + "'>";
            }
            if (CheckCompetitorLapExist(lapNo, iIndex))
            {
                resultStr += LapData[iIndex].lapTime;
            }
            else
            {
                resultStr += "&nbsp;&nbsp;--";
            }
            resultStr += "</div>";
        }
        if (LapData.length > showLapsDetail)
        {
            resultStr += "<div class='Div_Image' id='innerRight_" + RaceNo + "_" + Categoryno + "_" + Rowno + "_" + iArrayindex + "' onclick='ShiftRightByOrderInner(this)'>";
            resultStr += "<img alt='Click here to see Next lap' style=' height:13px; width:13px;' src='"+ imageLink +"Arrow_1.png'></div>";
        }

        resultStr += "<div style='Clear:both;'></div></div>";
    });
    return resultStr;
}

function ShiftleftByOrderInner(ctrl)
{
    var ctrlDiv = ctrl.id.split('_');
    var currentShow = parseInt($("#currentShowing_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3]).val());
    var maxLap = parseInt($("#race_maxLaps_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3]).val());
    var maxRow = parseInt($("#maxNoRows_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3]).val());

    for (var i = 0; i < maxRow; i++)
    {
        if (((currentShow + 1) <= maxLap) && ((currentShow - 5) >= 1))
        {
            var currentRowLapcount = maxLap;
            if (currentRowLapcount > (currentShow))
            {
                $("#innerRight_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3] + "_" + i).html("<img src='"+ imageLink +"Arrow_1.png' style=' height:13px; width:13px;' alt='Click here to see previous lap' /> ");
                $("#innerRight_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3] + "_" + i).show();
            }
            else
            {
                $("#innerRight_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3] + "_" + i).html('');
                $("#innerRight_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3] + "_" + i).hide();
            }
            if (i == 0)
            {

                $("#innerHeading_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3] + "_" + (currentShow - 6)).removeClass("Heading_Lap_Hide").addClass("Heading_Lap_show");
                $("#innerHeading_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3] + "_" + (currentShow)).removeClass("Heading_Lap_show").addClass("Heading_Lap_Hide");
            }
            $("#innerRow_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3] + "_" + i + "_" + (currentShow - 6)).removeClass("Div_Lap_Hide").addClass("Div_Lap_Show");
            $("#innerRow_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3] + "_" + i + "_" + (currentShow)).removeClass("Div_Lap_Show").addClass("Div_Lap_Hide");
            if (currentShow - 5 > 1)
            {
                $("#innerLeft_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3] + "_" + i).html("<img src='" + imageLink + "Arrow_3.png' style=' height:13px; width:13px;' alt='Click here to see previous lap' /> ");
                $("#innerLeft_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3] + "_" + i).css("cursor", "pointer");
            }
            else
            {
                $("#innerLeft_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3] + "_" + i).html("");
                $("#innerLeft_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3] + "_" + i).css("cursor", "default");
            }
        }
    }
    currentShow = currentShow - 1;
    if (currentShow < 6)
    {
        currentShow = 6;
    }
    $("#currentShowing_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3]).val(currentShow);
}

function ShiftRightByOrderInner(ctrl)
{
    var ctrlDiv = ctrl.id.split('_');
    var currentShow = parseInt($("#currentShowing_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3]).val());
    var maxLap = parseInt($("#race_maxLaps_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3]).val());
    var maxRow = parseInt($("#maxNoRows_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3]).val());

    for (var i = 0; i < maxRow; i++)
    {
        if (((currentShow + 1) <= maxLap))
        {
            var currentRowLapcount = maxLap
            if (currentRowLapcount > (currentShow + 1))
            {
                $("#innerRight_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3] + "_" + i).html("<img src='"+ imageLink +"Arrow_1.png' style=' height:13px; width:13px;' alt='Click here to see previous lap' /> ");
                $("#innerRight_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3] + "_" + i).show();
            }
            else
            {
                $("#innerRight_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3] + "_" + i).html('');
                $("#innerRight_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3] + "_" + i).hide();
            }
            if (i == 0)
            {

                $("#innerHeading_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3] + "_" + (currentShow - 6)).removeClass("Heading_Lap_show").addClass("Heading_Lap_Hide");
                $("#innerHeading_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3] + "_" + (currentShow)).removeClass("Heading_Lap_Hide").addClass("Heading_Lap_show");
            }
            $("#innerRow_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3] + "_" + i + "_" + (currentShow - 6)).removeClass("Div_Lap_Show").addClass("Div_Lap_Hide");
            $("#innerRow_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3] + "_" + i + "_" + (currentShow)).removeClass("Div_Lap_Hide").addClass("Div_Lap_Show");
            $("#innerLeft_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3] + "_" + i).html("<img src='" + imageLink + "Arrow_3.png' style=' height:13px; width:13px;' alt='Click here to see previous lap' /> ");
            $("#innerLeft_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3] + "_" + i).css("cursor", "pointer");
        }
    }
    currentShow = currentShow + 1;
    $("#currentShowing_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + ctrlDiv[3]).val(currentShow);
}

function CheckCompetitorLapExist(lapno, index)
{
    var resBool = false;
    for (var iIndex = 0; iIndex < lapno.length; iIndex++)
    {
        if (lapno[iIndex] == index)
        {
            resBool = true;
            break;
        }
    }
    return resBool;
}

var imagesVisible = false;
function toggleMoreImages()
{
    var moreImages = $('#lightbox-moreImages');
    moreImages.toggle();

    imagesVisible = !imagesVisible;

    var image = $('#toggleImgHolder');

    if (imagesVisible)
        image.attr("src", SERVER + "results/newStyle/button_lessImages.png");
    else
        image.attr("src", SERVER + "results/newStyle/button_moreImages.png");

}

function showUploadImages()
{
    var uploadImagesDiv = document.getElementById("uploadImagesContainer");
    uploadImagesDiv.style.display = "";
}

function RoundsNavigate(iIndexLink)
{

    location.href = iIndexLink;
}

function hideUploadImages()
{
    var uploadImagesDiv = document.getElementById("uploadImagesContainer");
    uploadImagesDiv.style.display = "none";
}

function SelectedTabByCategory(iRaceNo, iCategoryNo, iLapno)
{
    var ttRaces = ttEvent.races;
    var totalLaps = ttRaces[iRaceNo].teams[ttRaces[iRaceNo].competitorsByCategories[iCategoryNo].competitors[0]].laps.length;
    for (var i = 1; i <= totalLaps; i++)
    {
        $("#raceLapid_" + iRaceNo + "_" + iCategoryNo + "_" + i).removeClass("Div_Number_Lap_current").addClass("Div_Number_Lap");
    }
    $("#raceLapid_" + iRaceNo + "_" + iCategoryNo + "_" + (iLapno + 1)).removeClass("Div_Number_Lap").addClass("Div_Number_Lap_current");
}

function SelectedTab(iRaceNo, iLapno)
{
    var ttRaces = ttEvent.races;
    var totalLaps = ttRaces[iRaceNo].teams[0].laps.length;
    for (var i = 1; i <= totalLaps; i++)
    {
        $("#raceLapid_" + iRaceNo + "_" + i).removeClass("Div_Number_Lap_current").addClass("Div_Number_Lap");
    }
    $("#raceLapid_" + iRaceNo + "_" + (iLapno + 1)).removeClass("Div_Number_Lap").addClass("Div_Number_Lap_current");
}



function ByLapClickByCategory(iRaceNo, iCategoryNo, iLapno,totalLap)
{
    var resultStr = '';
    var arrayContainer = new Array();
    var arrayPostion = new Array();
    var ttRaces = ttEvent.races;
    var isAllTeam = CheckAllnonSoloByCategory(ttRaces[iRaceNo].competitorsByCategories[iCategoryNo].competitors, iRaceNo);
    resultStr += "<div class='Div_Main_Div'><div class='Heading_Position'>Pos.</div>";
    if (!isAllTeam)
    {
        resultStr += " <div class='Heading_Number'>No.</div>";
    }
    if ((iLapno - 1) >= 0)
    {
        resultStr += "<div class='Heading_Fastest_Lap'>Gain/Loss</div>";
    }
    resultStr += "<div class='Heading_Name'>Name/Club</div>";
    resultStr += "<div class='Heading_Time'>Time</div><div class='Clear'></div></div>";
    $("#raceNo_" + iRaceNo + "_" + iCategoryNo).html(CreateLapRowForCat(totalLap, 0, iRaceNo, iCategoryNo));
    $.each(ttRaces[iRaceNo].competitorsByCategories[iCategoryNo].competitors, function (iCompetitor, ttCompetitorData)
    {
        var maxLaps = ttRaces[iRaceNo].teams[ttCompetitorData].laps.length - 1;
        if (maxLaps >= iLapno)
        {
            var currLaptime = '';
            var tempLaptime = '';
            if ((iLapno - 1) >= 0)
            {
                $.each(ttRaces[iRaceNo].teams[ttCompetitorData].laps, function (iLapIndex, ttlap)
                {
                    if (iLapIndex == 0)
                    {
                        currLaptime = ttlap.lapTime;
                    }
                    else if (iLapIndex <= (iLapno - 1))
                    {
                        tempLaptime = ttlap.lapTime;
                        currLaptime = TimeAdd(currLaptime, tempLaptime);
                    }

                });
                arrayPostion[iCompetitor] = [ttCompetitorData, currLaptime];
            }

            $.each(ttRaces[iRaceNo].teams[ttCompetitorData].laps, function (iLapIndex, ttlap)
            {
                if (iLapIndex == 0)
                {
                    var iLapTime = ttlap.lapTime.split(':')[2] >= 0 ? false : true;
                    if (!iLapTime)
                        currLaptime = ttlap.lapTime;
                    else
                        currLaptime = "DNF";
                }
                else if (iLapIndex <= iLapno)
                {
                    var iLapTime = ttlap.lapTime.split(':')[2] >= 0 ? false : true;
                    if (!iLapTime)
                    {
                        tempLaptime = ttlap.lapTime;
                        currLaptime = TimeAdd(currLaptime, tempLaptime);
                    }
                    else
                    {
                        var thisMaxLap = ttRaces[iRaceNo].teams[ttCompetitorData].laps.length;
                        if (((iLapno + 1) - (thisMaxLap - 1)) > 1)
                        {
                            currLaptime = " z_" + ((iLapno + 1) - (thisMaxLap - 1)) + " Laps";
                        }
                        else
                        {
                            currLaptime = "z_" + ((iLapno + 1) - (thisMaxLap - 1)) + " Lapq";
                        }
                    }

                }

            });
            arrayContainer[iCompetitor] = [ttCompetitorData, currLaptime];
        }
        else
        {
            var checkDnf = IsDNF(ttRaces[iRaceNo].teams[ttCompetitorData]);
            var thisMaxLap = ttRaces[iRaceNo].teams[ttCompetitorData].laps.length;
            if (!checkDnf)
            {

                if (((iLapno + 1) - thisMaxLap) > 1)
                {
                    arrayContainer[iCompetitor] = [ttCompetitorData, ((iLapno + 1) - thisMaxLap) + " Laps"];
                    if ((iLapno - 1) >= 0)
                    {
                        arrayPostion[iCompetitor] = [ttCompetitorData, ((iLapno + 1) - thisMaxLap) + " Laps"];
                    }
                }
                else
                {
                    arrayContainer[iCompetitor] = [ttCompetitorData, ((iLapno + 1) - thisMaxLap) + " Lapq"];
                    if ((iLapno - 1) >= 0)
                    {
                        arrayPostion[iCompetitor] = [ttCompetitorData, ((iLapno + 1) - thisMaxLap) + " Lapq"];
                    }
                }
            }
            else
            {
                arrayContainer[iCompetitor] = [ttCompetitorData, "z_" + ((iLapno + 1) - (thisMaxLap - 1)) + " Laps"];
                arrayPostion[iCompetitor] = [ttCompetitorData, "z_" + ((iLapno + 1) - (thisMaxLap - 1)) + " Laps"];
            }

        }
    });
    arrayPostion.sort(sortMultiDimensional);
    arrayContainer.sort(sortMultiDimensional);
    $.each(arrayContainer, function (iCompetiorIndex, ttCompetitorTimeData)
    {
        var participantsData = ttRaces[iRaceNo].teams[ttCompetitorTimeData[0]];
        if (participantsData != null)
        {
            var title = ""
            if (participantsData.club.length > 0)
            {
                title += participantsData.name + " / " + participantsData.club + " was in ";
            }
            else
            {
                title += participantsData.name + " was in ";
            }
            title += GetPostion((iCompetiorIndex + 1)) + " position on Lap " + (parseInt(iLapno) + 1);
            if (iCompetiorIndex % 2 == 0)
            {
                resultStr += "<div class='Div_Even'  style='cursor:default;'>";
            }
            else
            {
                resultStr += "<div class='Div_Odd'  style='cursor:default;'>";
            }

            var checkDNF = LapNoDNF(participantsData.laps);
            if (checkDNF == iLapno)
            {

                resultStr += "<div class='Div_Position'>DNF</div>";
            }
            else
            {
                if (checkDNF == -1)
                {
                    resultStr += "<div class='Div_Position'>" + (iCompetiorIndex + 1) + "</div>";
                }
                else
                {
                    resultStr += "<div class='Div_Position'>" + (iCompetiorIndex + 1) + "</div>";
                }
            }
            if (!isAllTeam)
            {
                if (participantsData.isSolo == "1")
                {
                    resultStr += "<div class='Div_Number'>" + participantsData.raceNumber + "</div>";
                }
                else
                {
                    resultStr += "<div class='Div_Number'>&nbsp;</div>";
                }
            }
            if ((iLapno - 1) >= 0)
            {
                var position = ReturnPostion(arrayPostion, ttCompetitorTimeData[0]);
                var positionVal = "";
                if ((position - iCompetiorIndex) > 0)
                {
                    positionVal = "+ " + (position - iCompetiorIndex);
                }
                else if ((position - iCompetiorIndex) == 0)
                {
                    positionVal = "=";
                }
                else if ((position - iCompetiorIndex) < 0)
                {
                    positionVal = "- &nbsp;" + ((position - iCompetiorIndex) * (-1));
                }
                position = 0;
                resultStr += "<div class='Div_Fastest_Lap' style='text-align:left;' >" + positionVal + "</div>"
            }
            if (participantsData.club.length > 0)
            {
                resultStr += "<div class='Div_Name' title='" + title + "' > <span class='Div_Name_span'>" + participantsData.name + "</span> / " + participantsData.club + "</div> ";
            }
            else
            {
                resultStr += "<div class='Div_Name' title='" + title + "' > <span class='Div_Name_span'>" + participantsData.name + "</span></div> ";
            }
            var lapSuffix = ttCompetitorTimeData[1].substring((ttCompetitorTimeData[1].length - 4), ttCompetitorTimeData[1].length);
            if (lapSuffix == "Laps" || lapSuffix == "Lapq")
            {
                resultStr += "<div class='Div_Time_Byorder'>" + participantsData.totalTime + " ( +" + ttCompetitorTimeData[1].replace("q", "").replace("z_", "") + " )</div> ";
            }
            else
            {
                resultStr += "<div class='Div_Time_Byorder'>" + ttCompetitorTimeData[1] + "</div> ";
            }

            resultStr += "<div class='Clear'></div>";
            resultStr += "</div>";
        }
    });
    $("#RaceContainerID_" + iRaceNo + "_" + iCategoryNo).html(resultStr);

    ChangeSelectedTabByCategory((iLapno + 1), iRaceNo, iCategoryNo, totalLap);
}

function ReturnPostion(arrayPostion, iCompetiorIndex)
{
    var position = 0;
    for (var iIndex = 0; iIndex < arrayPostion.length; iIndex++)
    {
        if (arrayPostion[iIndex][0] == iCompetiorIndex)
        {
            position = iIndex;
            return position;
        }
    }
}

function LapNoDNF(lapsData)
{
    var isLapDNF = lapsData[lapsData.length - 1].lapTime.split(':')[2] >= 0 ? false : true;
    if (!isLapDNF)
    {
        return -1;
    }
    else
    {
        return (lapsData.length - 1);
    }
}

function ByLapClick(iRaceNo, iLapno, totalLap)
{
    if (iLapno != 0)
    {
        $("#raceNo_" + iRaceNo + "_0").html(CreateLapRowForOrder(totalLap, 0, iRaceNo, 0));
        var resultStr = '';
        var arrayContainer = new Array();
        var arrayPostion = new Array();
        var ttRaces = ttEvent.races;
        var isAllTeam = CheckAllnonSoloByOrder(ttRaces[iRaceNo]);
        resultStr += "<div class='Div_Main_Div'><div class='Heading_Position'>Pos.</div>";
        if (!isAllTeam)
        {
            resultStr += " <div class='Heading_Number'>No.</div>";
        }
        resultStr += "<div class='Heading_Fastest_Lap'>Gain/Loss</div>";
        resultStr += "<div class='Heading_Name'>Name/Club</div>";
        resultStr += "<div class='Heading_Time'>Time</div> ";

        resultStr += "<div class='Clear'></div></div>";

        $.each(ttRaces[iRaceNo].teams, function (iCompetitor, ttCompetitor)
        {
            var maxLaps = ttRaces[iRaceNo].teams[iCompetitor].laps.length - 1;

            if (maxLaps >= iLapno)
            {
                var currLaptime = '';
                var tempLaptime = '';
                $.each(ttCompetitor.laps, function (iLapIndex, ttlap)
                {
                    if (iLapIndex == 0)
                    {
                        currLaptime = ttlap.lapTime;
                    }
                    else if (iLapIndex <= (iLapno - 1))
                    {
                        if ((iLapno - 1) == 0)
                        {
                            currLaptime = ttlap.lapTime;
                        }
                        else
                        {
                            var iLapTime = ttlap.lapTime.split(':')[2] >= 0 ? false : true;
                            if (!iLapTime)
                            {
                                tempLaptime = ttlap.lapTime;
                                currLaptime = TimeAdd(currLaptime, tempLaptime);
                            }
                            else
                            {
                                var thisMaxLap = ttCompetitor.laps.length;
                                if (thisMaxLap - 1 > 1)
                                {
                                    currLaptime = (thisMaxLap - 1) + "Laps";
                                }
                                else
                                {
                                    currLaptime = (thisMaxLap - 1) + "Lapq";
                                }
                            }
                        }
                    }
                    arrayPostion[iCompetitor] = [iCompetitor, currLaptime];
                });

                $.each(ttCompetitor.laps, function (iLapIndex, ttlap)
                {
                    if (iLapIndex == 0)
                    {
                        var iLapTime = ttlap.lapTime.split(':')[2] >= 0 ? false : true;
                        if (!iLapTime)
                            currLaptime = ttlap.lapTime;
                        else
                            currLaptime = "DNF";
                    }
                    else if (iLapIndex <= iLapno)
                    {
                        var iLapTime = ttlap.lapTime.split(':')[2] >= 0 ? false : true;
                        if (!iLapTime)
                        {
                            tempLaptime = ttlap.lapTime;
                            currLaptime = TimeAdd(currLaptime, tempLaptime);
                        }
                        else
                        {
                            var thisMaxLap = ttCompetitor.laps.length;
                            if (((iLapno + 1) - (thisMaxLap - 1)) > 1)
                            {
                                currLaptime = " z_" + ((iLapno + 1) - (thisMaxLap - 1)) + " Laps";
                            }
                            else
                            {
                                currLaptime = "z_" + ((iLapno + 1) - (thisMaxLap - 1)) + " Lapq";
                            }
                        }

                    }

                });
                arrayContainer[iCompetitor] = [iCompetitor, currLaptime];
            }
            else
            {
                var checkDnf = IsDNF(ttCompetitor);
                var thisMaxLap = ttCompetitor.laps.length;
                if (!checkDnf)
                {

                    if (((iLapno + 1) - thisMaxLap) > 1)
                    {
                        arrayContainer[iCompetitor] = [iCompetitor, ((iLapno + 1) - thisMaxLap) + " Laps"];
                        arrayPostion[iCompetitor] = [iCompetitor, ((iLapno + 1) - thisMaxLap) + " Laps"];
                    }
                    else
                    {
                        arrayContainer[iCompetitor] = [iCompetitor, ((iLapno + 1) - thisMaxLap) + " Lapq"];
                        arrayPostion[iCompetitor] = [iCompetitor, ((iLapno + 1) - thisMaxLap) + " Lapq"];
                    }
                }
                else
                {
                    if ((iLapno + 1) - (thisMaxLap - 1) > 1)
                    {
                        arrayContainer[iCompetitor] = [iCompetitor, "z_" + ((iLapno + 1) - (thisMaxLap - 1)) + "  Laps"];
                        arrayPostion[iCompetitor] = [iCompetitor, "z_" + ((iLapno + 1) - (thisMaxLap - 1)) + " Laps"];
                    }
                    else
                    {
                        arrayContainer[iCompetitor] = [iCompetitor, "z_" + ((iLapno + 1) - (thisMaxLap - 1)) + "  Lapq"];
                        arrayPostion[iCompetitor] = [iCompetitor, "z_" + ((iLapno + 1) - (thisMaxLap - 1)) + " Lapq"];
                    }
                }

            }

        });
        arrayPostion.sort(sortMultiDimensional);
        arrayContainer.sort(sortMultiDimensional);
        $.each(arrayContainer, function (iCompetiorIndex, ttCompetitorTimeData)
        {
            var participantsData = ttRaces[iRaceNo].teams[ttCompetitorTimeData[0]];
            if (participantsData != null)
            {
                var title = ""
                if (participantsData.club.length > 0)
                {
                    title += participantsData.name + " / " + participantsData.club + " was in ";
                }
                else
                {
                    title += participantsData.name + " was in ";
                }
                title += GetPostion((iCompetiorIndex + 1)) + " position on Lap " + (parseInt(iLapno) + 1);
                if (iCompetiorIndex % 2 == 0)
                {
                    resultStr += "<div class='Div_Even'  style='cursor:default;'>";
                }
                else
                {
                    resultStr += "<div class='Div_Odd'  style='cursor:default;'>";
                }
                var checkDNF = LapNoDNF(participantsData.laps);
                if (checkDNF == iLapno)
                {

                    resultStr += "<div class='Div_Position'>DNF</div>";
                }
                else
                {
                    if (checkDNF == -1)
                    {
                        resultStr += "<div class='Div_Position'>" + (iCompetiorIndex + 1) + "</div>";
                    }
                    else
                    {
                        resultStr += "<div class='Div_Position'>" + (iCompetiorIndex + 1) + "</div>";
                    }
                    //                    else {
                    //                        resultStr += "<div class='Div_Position'>DNF</div>";
                    //                    }
                }

                if (!isAllTeam)
                {
                    if (participantsData.isSolo == 1)
                    {
                        resultStr += "<div class='Div_Number'>" + participantsData.raceNumber + "</div>";
                    }
                    else
                    {
                        resultStr += "<div class='Div_Number'>&nbsp;</div>";
                    }
                }
                var position = ReturnPostion(arrayPostion, ttCompetitorTimeData[0]);
                var positionVal = "";
                if ((position - iCompetiorIndex) > 0)
                {
                    positionVal = "+ " + (position - iCompetiorIndex);
                }
                else if ((position - iCompetiorIndex) == 0)
                {
                    positionVal = "=  ";
                }
                else if ((position - iCompetiorIndex) < 0)
                {
                    positionVal = "- &nbsp;" + ((position - iCompetiorIndex) * (-1));
                }
                position = 0;
                resultStr += "<div class='Div_Fastest_Lap' style='text-align:left;' >" + positionVal + "</div>"
                // positionVal = "";
                if (participantsData.club.length > 0)
                {
                    resultStr += "<div class='Div_Name' title='" + title + "' > <span class='Div_Name_span'>" + participantsData.name + "</span> / " + participantsData.club + "</div> ";
                }
                else
                {
                    resultStr += "<div class='Div_Name' title='" + title + "' > <span class='Div_Name_span'>" + participantsData.name + "</span> </div> ";
                }
                var lapSuffix = ttCompetitorTimeData[1].substring((ttCompetitorTimeData[1].length - 4), ttCompetitorTimeData[1].length);
                if (lapSuffix == "Laps" || lapSuffix == "Lapq")
                {
                    resultStr += "<div class='Div_Time_Byorder'>" + participantsData.totalTime + " ( +" + ttCompetitorTimeData[1].replace("q", "").replace("z_", "") + " )</div> ";
                }
                else
                {
                    resultStr += "<div class='Div_Time_Byorder'>" + ttCompetitorTimeData[1] + "</div> ";
                }
                resultStr += "<div class='Clear'></div>";
                resultStr += "</div>";
            }
        });
        $("#RaceContainerID_" + iRaceNo).html(resultStr);

        //  SelectedTab(iRaceNo, iLapno);
        ChangeSelectedTab((iLapno + 1), iRaceNo, 0, totalLap)
    }
    else
    {
        BYLap();
    }
}

var isByLapCategory = false;
var isByLapCategoryHTML = "";

var isByLapOrder = false;
var isByLapOrderHTML = "";

var currentTab = 0;

function ManageStateofOrderByLap(index)
{
    switch (index)
    {
        case 1:
            if (isByLapOrder)
            {
                CacheOrderByLap(currentTab);
                $("#OrderByResultContainer").html(isByLapOrderHTML);
            }
            else
            {
                CacheOrderByLap(currentTab);
                BYLap();

            }
            currentTab = 0;
            ToggleTabByCategory();
            break;
        case 2:
            if (isByLapCategory)
            {
                CacheOrderByLap(currentTab);
                $("#OrderByResultContainer").html(isByLapCategoryHTML);
            }
            else
            {
                CacheOrderByLap(currentTab);
                ByLapCategory();

            }
            currentTab = 1;
            ToogleTabByOrder();
            break;
    }
}


function CacheOrderByLap(currentTab)
{
    switch (currentTab)
    {
        case 0:
            isByLapOrderHTML = $("#OrderByResultContainer").html();
            isByLapOrder = true;
            break;
        case 1:
            isByLapCategoryHTML = $("#OrderByResultContainer").html();
            isByLapCategory = true;
            break;
    }
}

function ByLapCategory()
{
    var resultStr = '';
    var totalLaps = 0;
    var arrayContainer = new Array();
    var test = ttEvent;
    var ttRaces = ttEvent.races;
    ToogleTabByOrder();
    // get Race : Loop 1

    $.each(ttRaces, function (iRace, ttRaceData)
    {
        resultStr += "<div class='Race_Title'>" + ttRaceData.title + "</div>";
        if (ttRaceData.teams.length < 1)
        {
            resultStr += "<div class='Empty_Race'>Race not run</div>";
        }
        else
        {
            $.each(ttRaceData.competitorsByCategories, function (iCategory, ttCategoryData)
            {
                resultStr += "<div style='margin-top:15px;' class='Race_Category'>" + ttCategoryData.title + "</div>";
                if (ttCategoryData.competitors.length < 0)
                {
                    resultStr += "<div class='Empty_Race'>Race not run</div>";
                }
                else
                {
                    var isAllTeam = CheckAllnonSoloByCategory(ttCategoryData.competitors, iRace);
                    if (!IsDNF(ttRaceData.teams[ttCategoryData.competitors[0]]))
                    {
                        totalLaps = ttRaceData.teams[ttCategoryData.competitors[0]].laps.length;
                    }
                    else
                    {
                        totalLaps = ttRaceData.teams[ttCategoryData.competitors[0]].laps.length - 1;
                    }

                    resultStr += "<div id='raceNo_" + iRace + "_" + iCategory + "' style='padding-left:5px;'>";
                    resultStr += CreateLapRowForCat(totalLaps, 0, iRace, iCategory);
                    resultStr += "</div>";

                   
                    arrayContainer = new Array();
                    $.each(ttCategoryData.competitors, function (iCompetitor, ttCompetitorData)
                    {
                        var lapTimecurr = ttRaceData.teams[ttCompetitorData].laps[0].lapTime;
                        arrayContainer[iCompetitor] = [ttCompetitorData, lapTimecurr];
                    });
                    arrayContainer.sort(sortMultiDimensional);
                    resultStr += "<div id='RaceContainerID_" + iRace + "_" + iCategory + "'>";
                    resultStr += "<div class='Div_Main_Div'><div class='Heading_Position'>Pos.</div> ";
                    if (!isAllTeam)
                    {
                        resultStr += "<div class='Heading_Number'>No.</div>";
                    }
                    resultStr += "<div class='Heading_Name'>Name/Club</div>";
                    resultStr += "<div class='Heading_Time'>Time</div><div class='Clear'></div></div>";
                    $.each(arrayContainer, function (iCompetiorIndex, ttCompetitorTimeData)
                    {
                        var participantsData = ttRaceData.teams[ttCompetitorTimeData[0]];
                        if (participantsData != null)
                        {
                            var title = ""
                            if (participantsData.club.length > 0)
                            {
                                title += participantsData.name + " / " + participantsData.club + " was in ";
                            }
                            else
                            {
                                title += participantsData.name + " was in ";
                            }
                            title += GetPostion((iCompetiorIndex + 1)) + " position on Lap  1";
                            if (iCompetiorIndex % 2 == 0)
                            {
                                resultStr += "<div class='Div_Even'  style='cursor:default;'>";
                            }
                            else
                            {
                                resultStr += "<div class='Div_Odd'  style='cursor:default;'>";
                            }
                            var checkDNF = LapNoDNF(participantsData.laps);
                            if (checkDNF == 0)
                            {

                                resultStr += "<div class='Div_Position'>DNF</div>";
                            }
                            else
                            {
                                if (!IsDNF(participantsData))
                                {
                                    resultStr += "<div class='Div_Position'>" + (iCompetiorIndex + 1) + "</div>";
                                }
                                else
                                {
                                    if (totalLaps > 2)
                                    {
                                        resultStr += "<div class='Div_Position'>" + (iCompetiorIndex + 1) + "</div>";
                                    }
                                    else
                                    {
                                        resultStr += "<div class='Div_Position'>DNF</div>";
                                    }
                                }

                            }

                            if (!isAllTeam)
                            {
                                if (participantsData.isSolo == "1")
                                {
                                    resultStr += "<div class='Div_Number'>" + participantsData.raceNumber + "</div>";
                                }
                                else
                                {
                                    resultStr += "<div class='Div_Number'>&nbsp;</div>";
                                }
                            }
                            if (participantsData.club.length > 0)
                            {
                                resultStr += "<div class='Div_Name' title='" + title + "' > <span class='Div_Name_span'>" + participantsData.name + "</span> / " + participantsData.club + "</div> ";
                            }
                            else
                            {
                                resultStr += "<div class='Div_Name' title='" + title + "' > <span class='Div_Name_span'>" + participantsData.name + "</span></div> ";
                            }
                            resultStr += "<div class='Div_Time'>" + ttCompetitorTimeData[1] + "</div><div class='Clear'></div>";
                            resultStr += "</div>";
                        }
                    });
                    resultStr += "</div>";
                }
            });
        }
    });
    // end of Loop1

    $("#OrderByResultContainer").html(resultStr);

}


function CreateTabOrderByView()
{
    var resultStr = "";
    resultStr += "<div id='tabByOderByView' style='float:left; margin-right:5px;' onclick='ManageStateofOrderByLap(1);'>";
    resultStr += "<table cellspacing='0' cellpadding='0' style='border-collapse:collapse;'>";
    resultStr += "<tr>";
    resultStr += "<td id='TabViewByOder_1' class='Div_Selected_Start_Order_Lap' style='cursor:pointer;' >&nbsp;</td>";
    resultStr += "<td id='TabViewByOder_2' class='Div_Selected_Order' style='width:110px; text-align:center;cursor:pointer; ' > View by Order</td>";
    resultStr += "<td id='TabViewByOder_3' style='cursor:pointer;'  class='Div_Selected_End_Order'>&nbsp;</td>";
    resultStr += "</tr>";
    resultStr += "</table>";
    resultStr += "</div>";

    resultStr += "<div id='tabByOderByCat' style='float:left;' onclick='ManageStateofOrderByLap(2);'>";
    resultStr += "<table cellspacing='0' cellpadding='0' style='border-collapse:collapse;'>";
    resultStr += "<tr>";
    resultStr += "<td id='TabViewByCat_1' class='Div_Normal_Round_Order' style='cursor:pointer;'  >&nbsp;</td>";
    resultStr += "<td id='TabViewByCat_2' style='width:130px;text-align:center;cursor:pointer;' class='Div_Normal_Order' > View by Category</td>";
    resultStr += "<td id='TabViewByCat_3' style='cursor:pointer;'  class='Div_Normal_End_Order' >&nbsp;</td>";
    resultStr += "</tr>";
    resultStr += "</table>";
    resultStr += "</div>";
    resultStr += "<div clear:both;></div>"
    return resultStr;
}

function ToogleTabByOrder()
{
    $("#TabViewByOder_1").removeClass("Div_Selected_Start_Order_Lap").addClass("Div_Normal_Round_Order");
    $("#TabViewByOder_2").removeClass("Div_Selected_Order").addClass("Div_Normal_Order");
    $("#TabViewByOder_3").removeClass("Div_Selected_End_Order").addClass("Div_Normal_End_Order");


    $("#TabViewByCat_1").removeClass("Div_Normal_Round_Order").addClass("Div_Selected_Start_Order_Lap");
    $("#TabViewByCat_2").removeClass("Div_Normal_Order").addClass("Div_Selected_Order");
    $("#TabViewByCat_3").removeClass("Div_Normal_End_Order").addClass("Div_Selected_End_Order");
}

function ToggleTabByCategory()
{
    $("#TabViewByOder_1").removeClass("Div_Normal_Round_Order").addClass("Div_Selected_Start_Order_Lap");
    $("#TabViewByOder_2").removeClass("Div_Normal_Order").addClass("Div_Selected_Order");
    $("#TabViewByOder_3").removeClass("Div_Normal_End_Order").addClass("Div_Selected_End_Order");


    $("#TabViewByCat_1").removeClass("Div_Selected_Start_Order_Lap").addClass("Div_Normal_Round_Order");
    $("#TabViewByCat_2").removeClass("Div_Selected_Order").addClass("Div_Normal_Order");
    $("#TabViewByCat_3").removeClass("Div_Selected_End_Order").addClass("Div_Normal_End_Order");
}

function CreateLapRowForCat(tabMaxLap, SelectedLap, iRaceNo, iCategoryNo)
{

    var idCount = 1;
    var resultStr = "<div style='clear:both;'>";
    resultStr += "<div class='Div_Normal_Round_Order'>&nbsp;</div>";
    resultStr += "<div class='Div_Normal_StartText_Order' style='cursor:default;'>Laps</div>";
    for (var iIndex = 1; iIndex <= tabMaxLap; iIndex++)
    {

        if (tabMaxLap == 1)
        {
            resultStr += "<div class='Div_Selected_Start_Order'>&nbsp;</div>";
            resultStr += "<div class='Div_Selected_Order' > 1 </div>";
            resultStr += "<div class='Div_Selected_End_Order'>&nbsp;</div>";
            resultStr += "<div class='clear:both;'></div>";
        }
        else
        {
            if (iIndex == 1)
            {
                resultStr += "<div class='Div_Selected_Start_Order' id='lap_" + iRaceNo + "_" + iCategoryNo + "_" + idCount + "'>&nbsp;</div>";
                resultStr += "<div onclick='ByLapClickByCategory(" + iRaceNo + "," + iCategoryNo + "," + (iIndex - 1) + " , " + tabMaxLap + ");' class='Div_Selected_Order' id='lap_" + iRaceNo + "_" + iCategoryNo + "_" + (idCount + 1) + "'> " + iIndex + "</div>";
                resultStr += "<div class='Div_Selected_DividerL_Order' id='lap_" + iRaceNo + "_" + iCategoryNo + "_" + (idCount + 2) + "'>&nbsp;</div>";
                idCount = idCount + 3;
            }
            else if (iIndex == tabMaxLap)
            {

                resultStr += "<div onclick='ByLapClickByCategory(" + iRaceNo + "," + iCategoryNo + "," + (iIndex - 1) + " , " + tabMaxLap + ");' class='Div_Normal_Order' id='lap_" + iRaceNo + "_" + iCategoryNo + "_" + idCount + "'> " + iIndex + "</div>";
                resultStr += "<div class='Div_Normal_End_Order' id='lap_" + iRaceNo + "_" + iCategoryNo + "_" + (idCount + 1) + "'>&nbsp;</div>";
                idCount = idCount + 2;
            }
            else
            {
                resultStr += "<div onclick='ByLapClickByCategory(" + iRaceNo + "," + iCategoryNo + "," + (iIndex - 1) + " , " + tabMaxLap + ");' class='Div_Normal_Order' id='lap_" + iRaceNo + "_" + iCategoryNo + "_" + idCount + "'> " + iIndex + "</div>";
                resultStr += "<div class='Div_Normal_divider_Order' id='lap_" + iRaceNo + "_" + iCategoryNo + "_" + (idCount + 1) + "'>&nbsp;</div>";

                idCount = idCount + 2;
            }
        }
    }
    resultStr += "</div>";
    resultStr += "<div style='clear:both;'></div>";
    return resultStr;
}

function ChangeSelectedTabByCategory(SeletedLap, iRaceNo, iCategory, totalLap)
{
    var selectedID = (SeletedLap * 2);
    $("#lap_" + iRaceNo + "_" + iCategory + "_1").removeClass("Div_Selected_Start_Order").addClass("Div_Normal_Start_Order");
    $("#lap_" + iRaceNo + "_" + iCategory + "_2").removeClass("Div_Selected_Order").addClass("Div_Normal_Order");
    $("#lap_" + iRaceNo + "_" + iCategory + "_3").removeClass("Div_Selected_DividerL_Order").addClass("Div_Normal_divider_Order");
    if (SeletedLap == 1)
    {
        $("#lap_" + iRaceNo + "_" + iCategory + "_1").removeClass("Div_Normal_Start_Order").addClass("Div_Selected_Start_Order");
        $("#lap_" + iRaceNo + "_" + iCategory + "_2").removeClass("Div_Normal_Order").addClass("Div_Selected_Order");
        $("#lap_" + iRaceNo + "_" + iCategory + "_3").removeClass("Div_Normal_divider_Order").addClass("Div_Selected_DividerL_Order");
    }
    else if (SeletedLap == totalLap)
    {
        $("#lap_" + iRaceNo + "_" + iCategory + "_" + (selectedID - 1)).removeClass("Div_Normal_divider_Order").addClass("Div_Selected_Divider_order");
        $("#lap_" + iRaceNo + "_" + iCategory + "_" + selectedID).removeClass("Div_Normal_Order").addClass("Div_Selected_Order");
        $("#lap_" + iRaceNo + "_" + iCategory + "_" + (selectedID + 1)).removeClass("Div_Normal_End_Order").addClass("Div_Selected_End_Order");
    }
    else if (SeletedLap != 1 && SeletedLap != totalLap)
    {
        $("#lap_" + iRaceNo + "_" + iCategory + "_" + (selectedID - 1)).removeClass("Div_Normal_divider_Order").addClass("Div_Selected_Divider_order");
        $("#lap_" + iRaceNo + "_" + iCategory + "_" + selectedID).removeClass("Div_Normal_Order").addClass("Div_Selected_Order");
        $("#lap_" + iRaceNo + "_" + iCategory + "_" + (selectedID + 1)).removeClass("Div_Normal_divider_Order").addClass("Div_Selected_DividerL_Order");
    }

}


function ChangeSelectedTab(SeletedLap, iRaceNo, iCategory, totalLap)
{
    var selectedID = (SeletedLap * 2);
    $("#lap_" + iRaceNo + "_" + iCategory + "_1").removeClass("Div_Selected_Start_Order").addClass("Div_Normal_Start_Order");
    $("#lap_" + iRaceNo + "_" + iCategory + "_2").removeClass("Div_Selected_Order").addClass("Div_Normal_Order");
    $("#lap_" + iRaceNo + "_" + iCategory + "_3").removeClass("Div_Selected_DividerL_Order").addClass("Div_Normal_divider_Order");
    if (SeletedLap == totalLap)
    {
        $("#lap_" + iRaceNo + "_" + iCategory + "_" + (selectedID - 1)).removeClass("Div_Normal_divider_Order").addClass("Div_Selected_Divider_order");
        $("#lap_" + iRaceNo + "_" + iCategory + "_" + selectedID).removeClass("Div_Normal_Order").addClass("Div_Selected_Order");
        $("#lap_" + iRaceNo + "_" + iCategory + "_" + (selectedID + 1)).removeClass("Div_Normal_End_Order").addClass("Div_Selected_End_Order");
    }
    else if (SeletedLap != 1 && SeletedLap != totalLap)
    {
        $("#lap_" + iRaceNo + "_" + iCategory + "_" + (selectedID - 1)).removeClass("Div_Normal_divider_Order").addClass("Div_Selected_Divider_order");
        $("#lap_" + iRaceNo + "_" + iCategory + "_" + selectedID).removeClass("Div_Normal_Order").addClass("Div_Selected_Order");
        $("#lap_" + iRaceNo + "_" + iCategory + "_" + (selectedID + 1)).removeClass("Div_Normal_divider_Order").addClass("Div_Selected_DividerL_Order");
    }

}

function CreateLapRowForOrder(tabMaxLap, SelectedLap, iRaceNo, iCategoryNo)
{

    var idCount = 1;
    var resultStr = "<div style='clear:both;'>";
    resultStr += "<div class='Div_Normal_Round_Order'>&nbsp;</div>";
    resultStr += "<div class='Div_Normal_StartText_Order' style='cursor:default;'>Laps</div>";
    for (var iIndex = 1; iIndex <= tabMaxLap; iIndex++)
    {
        if (tabMaxLap == 1)
        {
            resultStr += "<div class='Div_Selected_Start_Order'>&nbsp;</div>";
            resultStr += "<div class='Div_Selected_Order' > 1 </div>";
            resultStr += "<div class='Div_Selected_End_Order'>&nbsp;</div>";
            resultStr += "<div class='clear:both;'></div>";
        }
        else
        {
            if (iIndex == 1)
            {
                resultStr += "<div class='Div_Selected_Start_Order' id='lap_" + iRaceNo + "_" + iCategoryNo + "_" + idCount + "'>&nbsp;</div>";
                resultStr += "<div onclick='ByLapClick(" + iRaceNo + "," + (iIndex - 1) + "," + tabMaxLap + ");' class='Div_Selected_Order' id='lap_" + iRaceNo + "_" + iCategoryNo + "_" + (idCount + 1) + "'> " + iIndex + "</div>";
                resultStr += "<div class='Div_Selected_DividerL_Order' id='lap_" + iRaceNo + "_" + iCategoryNo + "_" + (idCount + 2) + "'>&nbsp;</div>";
                idCount = idCount + 3;
            }
            else if (iIndex == tabMaxLap)
            {

                resultStr += "<div onclick='ByLapClick(" + iRaceNo + "," + (iIndex - 1) + "," + tabMaxLap + ");' class='Div_Normal_Order' id='lap_" + iRaceNo + "_" + iCategoryNo + "_" + idCount + "'> " + iIndex + "</div>";
                resultStr += "<div class='Div_Normal_End_Order' id='lap_" + iRaceNo + "_" + iCategoryNo + "_" + (idCount + 1) + "'>&nbsp;</div>";
                idCount = idCount + 2;
            }
            else
            {
                resultStr += "<div onclick='ByLapClick(" + iRaceNo + "," + (iIndex - 1) + "," + tabMaxLap + ");' class='Div_Normal_Order' id='lap_" + iRaceNo + "_" + iCategoryNo + "_" + idCount + "'> " + iIndex + "</div>";
                resultStr += "<div class='Div_Normal_divider_Order' id='lap_" + iRaceNo + "_" + iCategoryNo + "_" + (idCount + 1) + "'>&nbsp;</div>";

                idCount = idCount + 2;
            }
        }
    }
    resultStr += "</div>";
    resultStr += "<div style='clear:both;'></div>";
    return resultStr;
}

function GetPostion(position)
{
    
    var returnValue = "";
    if (position <= 10)
    {
        returnValue = position + GetFirstPosition(position);
    }
    else if (position > 10 && position <= 20)
    {
        returnValue = position + GetSecondPostion();
    }
    else
    {
        returnValue = position + GetAllPostion(position);
    }
    return returnValue;
}

function GetAllPostion(position)
{
    var textPos = "";
    textPos += position;
  var returnValue = "";
  var lengthPos = textPos.length;
  var numberPos = textPos.substring(lengthPos - 2, lengthPos);
  var num = parseInt(numberPos);
  if (num >= 11 && num <= 20)
  {
     returnValue = GetSecondPostion();
  }
  else 
  {

      returnValue = GetFirstPosition(textPos.substring(lengthPos - 1, lengthPos));
  }
  return returnValue ;
}

function GetSecondPostion()
{
   return "th";
}

function GetFirstPosition(position)
{
    var returnValue = "";
    var intPosition = parseInt(position);
    switch (intPosition)
    {
        case 1:
            returnValue =  "st";
            break;
        case 2:
            returnValue = "nd";
            break;
        case 3:
            returnValue = "rd";
            break;
        default:
            returnValue = "th";
            break;
    }
  return  returnValue;
}


function BYLap()
{
    var resultStr = '';
    var totalLaps = 0;
    var arrayContainer = new Array();
    var ttRaces = ttEvent.races;
    resultStr += "<div id='ByLapResult'>";
    // get Race : Loop 1

    resultStr += "<div style='margin-top:30px; margin-bottom:0px;'>";
    resultStr += CreateTabOrderByView();

    resultStr += "</div>";
    resultStr += "<div style='clear:both;'></div>";
    resultStr += "<div id='OrderByResultContainer' style='border: 1px solid #bebebe;' >";
    $.each(ttRaces, function (iRaceNo, ttRaceData)
    {

        resultStr += "<div class='Race_Title'>" + ttRaceData.title + "</div>"
        if (ttRaceData.teams.length < 1)
        {
            resultStr += "<div class='Empty_Race'>Race not run</div>";
        }
        else
        {
            var isAllTeam = CheckAllnonSoloByOrder(ttRaceData);

            if (!IsDNF(ttRaceData.teams[0]))
            {
                totalLaps = ttRaceData.teams[0].laps.length;
            }
            else
            {
                totalLaps = ttRaceData.teams[0].laps.length - 1;
            }

            resultStr += "<div id='raceNo_" + iRaceNo + "_0' style='padding-left:5px;'>";
            resultStr += CreateLapRowForOrder(totalLaps, 0, iRaceNo, 0);
            resultStr += "</div>";

            arrayContainer = new Array();
            $.each(ttRaceData.teams, function (iCompetitorNo, ttCompetitorData)
            {
                var isDnf = ttCompetitorData.laps[0].lapTime.split(':')[2] >= 0 ? false : true;
                if (!isDnf)
                {
                    arrayContainer[iCompetitorNo] = [iCompetitorNo, ttCompetitorData.laps[0].lapTime]
                }
                else
                {
                    arrayContainer[iCompetitorNo] = [iCompetitorNo, "DNF"]
                }
            });
            arrayContainer.sort(sortMultiDimensional);
            resultStr += "<div id='RaceContainerID_" + iRaceNo + "'>";
            resultStr += "<div class='Div_Main_Div'><div class='Heading_Position'>Pos.</div> ";
            if (!isAllTeam)
            {
                resultStr += "<div class='Heading_Number'>No.</div>";
            }

            resultStr += "<div class='Heading_Name'>Name/Club</div>";
            resultStr += "<div class='Heading_Time'>Time</div><div class='Clear'></div></div>";
            $.each(arrayContainer, function (iCompetiorIndex, ttCompetitorTimeData)
            {
                var participantsData = ttRaceData.teams[ttCompetitorTimeData[0]];
                if (participantsData != null)
                {
                    var title =  ""
                    if (participantsData.club.length > 0)
                    {
                        title += participantsData.name + " / " + participantsData.club + " was in ";
                    }
                    else
                    {
                        title += participantsData.name + " was in ";
                    }
                    title += GetPostion((iCompetiorIndex + 1)) + " position on Lap  1";
                    if (iCompetiorIndex % 2 == 0)
                    {
                        resultStr += "<div class='Div_Even'  style='cursor:default;'>";
                    }
                    else
                    {
                        resultStr += "<div class='Div_Odd'  style='cursor:default;'>";
                    }
                    var checkDNF = LapNoDNF(participantsData.laps);
                    if (checkDNF == 0)
                    {

                        resultStr += "<div class='Div_Position'>DNF</div>";
                    }
                    else
                    {
                        resultStr += "<div class='Div_Position'>" + (iCompetiorIndex + 1) + "</div>";

                    }


                    if (!isAllTeam)
                    {
                        if (participantsData.isSolo == "1")
                        {
                            resultStr += "<div class='Div_Number'>" + participantsData.raceNumber + "</div>";
                        }
                        else
                        {
                            resultStr += "<div class='Div_Number'>&nbsp;</div>";
                        }

                    }

                    if (participantsData.club.length > 0)
                    {
                        resultStr += "<div class='Div_Name' title='" + title + "' > <span class='Div_Name_span'>" + participantsData.name + "</span> / " + participantsData.club + "</div> ";
                    }
                    else
                    {
                        resultStr += "<div class='Div_Name' title='" + title + "' > <span class='Div_Name_span'>" + participantsData.name + "</span></div> ";
                    }
                    resultStr += "<div class='Div_Time'>" + ttCompetitorTimeData[1] + "</div><div class='Clear'></div>";
                    resultStr += "</div>";
                }
            });
            resultStr += "</div>";
        }
    });
    // End of Loop 1
    resultStr += "</div>";
    resultStr += "</div>";
    $("#mainRaceBody").html(resultStr);


}




function sortMultiDimensional(a, b)
{

    return ((a[1] < b[1]) ? -1 : ((a[1] > b[1]) ? 1 : 0));
}

function TimeAdd(a, b)
{

    var time1 = Secs(a);
    var time2 = Secs(b);
    var diff = parseFloat(time1) + parseFloat(time2);
    var result = '';

    result = diffResult(diff);
    return result;
}


function BySummary()
{
    var resultStr = '';
    var subresultStr = '';
    var noOfRows = 0;
    var minumTime = '';
    var maxLaps = 0;
    var defaultShow = 2;
    var ttRaces = ttEvent.races;

    resultStr += "<div id='BySummaryResult'>";
    // For Finding all the Races : Loop1
    $.each(ttRaces, function (iRaceNo, ttRacesData)
    {

        resultStr += "<div class='Race_Title'>" + ttRacesData.title + "</div>"
        // Checking the competitors in Races : Loop 2
        if (ttRacesData.teams.length < 1)
        {
            resultStr += "<div class='Empty_Race'>Race not run</div>";

        }
        else
        {
            var ttcompetitorsByCategories = ttRacesData.competitorsByCategories;

            //Searching data with in competitorsByCategories : Loop3
            $.each(ttcompetitorsByCategories, function (iCategoryNo, ttCategoryData)
            {
                var isAllTeam = CheckAllnonSoloByCategory(ttCategoryData.competitors, iRaceNo);
                resultStr += "<div class='Race_Category'>" + ttCategoryData.title + "</div>";
                if (ttCategoryData.competitors.length < 1)
                {
                    resultStr += "<div class='Empty_Race'>Race not run...</div>";
                    resultStr += "<div class='line9'>&nbsp;</div>";
                }
                else
                {

                    resultStr += "<div style='clear:both;' id='RaceNumber_" + iRaceNo + "_" + iCategoryNo + "'><div class='Div_Main_Div'><div class='Heading_Position'>Pos.</div> ";
                    if (!isAllTeam)
                    {
                        resultStr += "<div class='Heading_Number'>No.</div> ";
                    }
                    resultStr += " <div class='Heading_Name'>Name/Club</div> <div class='Heading_Laps_Count'>Laps</div>";
                    resultStr += "<div class='Heading_Time'>Time</div> <div class='Heading_Plus_Minus'>+/-</div>";
                    resultStr += "<div class='Heading_Fastest_Lap'>Fastest Lap<span>&nbsp;</span></div><div class='Div_Image' style='cursor:default;'>&nbsp;</div>";
                    if (!IsDNF(ttRacesData.teams[ttCategoryData.competitors[0]]))
                    {
                        maxLaps = ttRacesData.teams[ttCategoryData.competitors[0]].laps.length;
                    }
                    else
                    {
                        maxLaps = ttRacesData.teams[ttCategoryData.competitors[0]].laps.length - 1;
                    }

                    for (var i = 0; i < maxLaps; i++)
                    {
                        if (i < defaultShow)
                        {
                            resultStr += "<div class='Heading_Lap_show' id='race_" + iRaceNo + "_Cat_" + iCategoryNo + "_HLap_" + i + "' >Lap " + (i + 1) + " </div>";
                        }
                        else
                        {
                            resultStr += "<div class='Heading_Lap_Hide' id='race_" + iRaceNo + "_Cat_" + iCategoryNo + "_HLap_" + i + "' >Lap " + (i + 1) + " </div>";
                        }
                    }
                    resultStr += "<div class='Div_Image' style='cursor:default;' >&nbsp;</div><div style='clear:both;'></div></div><input type='hidden' id='race_maxLaps_" + iRaceNo + "_" + iCategoryNo + "' value='" + maxLaps + "' />";
                    resultStr += "<input type='hidden' id='currentShowing_" + iRaceNo + "_" + iCategoryNo + "' value='1' />";
                    // getting id of participants in particular category : loop 4
                    $.each(ttCategoryData.competitors, function (iCompetitorNo, ttCompetitorData)
                    {
                        if (iCompetitorNo < 3)
                        {
                           
                            noOfRows = noOfRows + 1;
                            var competitorData = ttRacesData.teams[ttCompetitorData];
                            var title = "Please click to see the laps for ";
                            if (competitorData.club.length > 0)
                            {
                                title += competitorData.name + " / " + competitorData.club;
                            }
                            else
                            {
                                title += competitorData.name;
                            }
                            if (iCompetitorNo == 0)
                            {
                                minumTime = competitorData.totalTime;
                            }
                            if ((iCompetitorNo % 2) != 0)
                            {
                                resultStr += "<div class='Div_Odd' title='" + title + "' id='rowNo_" + iRaceNo + "_" + iCategoryNo + "_" + iCompetitorNo + "' onClick='togglebyCategory(" + iRaceNo + "," + iCategoryNo + " ," + iCompetitorNo + ")'>";
                            }
                            else
                            {
                                resultStr += "<div class='Div_Even' title='"+ title +"' id='rowNo_" + iRaceNo + "_" + iCategoryNo + "_" + iCompetitorNo + "' onClick='togglebyCategory(" + iRaceNo + "," + iCategoryNo + " ," + iCompetitorNo + ")'>";
                            }
                            if (!IsDNF(competitorData))
                            {
                                resultStr += "<div class='Div_Position'>" + (iCompetitorNo + 1) + "</div> ";
                            }
                            else
                            {
                                resultStr += "<div class='Div_Position'>DNF</div> ";
                            }
                            if (!isAllTeam)
                            {
                                if (competitorData.isSolo == 1)
                                {
                                    resultStr += "<div class='Div_Number'>" + competitorData.raceNumber + "</div>";
                                }
                                else
                                {
                                    resultStr += "<div class='Div_Number'>&nbsp;</div>";
                                }
                            }
                            if (competitorData.club.length > 0)
                            {
                                resultStr += "<div class='Div_Name' title='" + competitorData.name + " / " + competitorData.club + " , Please click here to see the laps'><span class='Div_Name_Image'  id='span_" + iRaceNo + "_" + iCategoryNo + "_" + iCompetitorNo + "'><img alt='' src='" + imageLink + "Arrow_1.png' style='width:13px; height:13px;' /></span> <span class='Div_Name_span'> " + competitorData.name + "</span> / " + competitorData.club + "</div>";
                            }
                            else
                            {
                                resultStr += "<div class='Div_Name' title='" + competitorData.name + " , Please click here to see the laps'><span class='Div_Name_Image'  id='span_" + iRaceNo + "_" + iCategoryNo + "_" + iCompetitorNo + "'><img alt='' src='" + imageLink + "Arrow_1.png' style='width:13px; height:13px;' /></span> <span class='Div_Name_span'> " + competitorData.name + "</span> </div>";
                            }
                            if ((!IsDNF(competitorData)))
                            {
                                resultStr += "<div class='Div_Laps_Count'>" + competitorData.laps.length + "</div>";
                            }
                            else
                            {
                                resultStr += "<div class='Div_Laps_Count'>" + (competitorData.laps.length - 1) + "</div>";
                            }
                            resultStr += "<div class='Div_Time'>" + competitorData.totalTime + "</div>";
                            if (iCompetitorNo == 0)
                            {
                                resultStr += "<div class='Div_Plus_Minus'> 00:00:00</div>";
                            }
                            else
                            {
                                if (!IsDNF(competitorData))
                                {
                                    if (maxLaps == competitorData.laps.length)
                                    {
                                        resultStr += "<div class='Div_Plus_Minus'>" + TimeDiff(competitorData.totalTime, minumTime) + "</div>";
                                    }
                                    else
                                    {
                                        if ((maxLaps - competitorData.laps.length) > 1)
                                        {
                                            resultStr += "<div class='Div_Plus_Minus'> + " + (maxLaps - competitorData.laps.length) + " Laps</div>";
                                        }
                                        else
                                        {
                                            resultStr += "<div class='Div_Plus_Minus'> + " + (maxLaps - competitorData.laps.length) + " Lap</div>";
                                        }
                                    }
                                }
                                else
                                {
                                    if (maxLaps == (competitorData.laps.length - 1))
                                    {
                                        resultStr += "<div class='Div_Plus_Minus'>" + TimeDiff(competitorData.totalTime, minumTime) + "</div>";
                                    }
                                    else
                                    {
                                        if ((maxLaps - competitorData.laps.length) > 1)
                                        {
                                            resultStr += "<div class='Div_Plus_Minus'> + " + (maxLaps - (competitorData.laps.length - 1)) + " Laps</div>";
                                        }
                                        else
                                        {
                                            resultStr += "<div class='Div_Plus_Minus'> + " + (maxLaps - (competitorData.laps.length - 1)) + " Lap</div>";
                                        }
                                    }
                                }

                            }

                            resultStr += "<div class='Div_Fastest_Lap'>" + FastestLap(competitorData.laps) + "<span>&nbsp;</span></div>";
                            resultStr += "<div class='Div_Image' onClick='shiftLeftByCategory(this,event);'  id='left_" + iRaceNo + "_" + iCategoryNo + "_" + iCompetitorNo + "'>&nbsp;</div>";

                            subresultStr += "<div class='Div_all_Laps_Hide' id='Div_all_laps_" + iRaceNo + "_" + iCategoryNo + "_" + iCompetitorNo + "'>";
                            // Getting all the laps of competitior : Loop 5
                            $.each(competitorData.laps, function (iLapNo, ttLapData)
                            {
                                var iLapTime = ttLapData.lapTime.split(':')[2] >= 0 ? false : true;
                                if (!iLapTime)
                                {

                                    if (iLapNo < defaultShow)
                                    {
                                        resultStr += "<div class='Div_Lap_Show' id='Lap_" + iRaceNo + "_" + iCategoryNo + "_" + iCompetitorNo + "_" + iLapNo + "'>" + ttLapData.lapTime + "</div>";
                                    }
                                    else
                                    {
                                        resultStr += "<div class='Div_Lap_Hide' id='Lap_" + iRaceNo + "_" + iCategoryNo + "_" + iCompetitorNo + "_" + iLapNo + "'>" + ttLapData.lapTime + "</div>";
                                    }
                                    subresultStr += "<div class='Div_Block'> <div class='Div_Block_Heading'> Lap" + (iLapNo + 1) + "</div> <div class='Div_Block_Lap'>" + ttLapData.lapTime + "</div></div>";
                                }
                            });
                            // End of Loop 5
                            subresultStr += "<input type='hidden' value='0' id='isHidden_" + iRaceNo + "_" + iCategoryNo + "_" + iCompetitorNo + "' />";
                            resultStr += "<div class='Div_Image' id='right_" + iRaceNo + "_" + iCategoryNo + "_" + iCompetitorNo + "' onClick='ShiftRightByCategory(this,event)'>";
                            if (competitorData.laps.length > defaultShow)
                            {
                                resultStr += "<img src='" + imageLink + "Arrow_1.png' style=' height:13px; width:13px;' alt='Click here to see Next lap' />";
                            }
                            else
                            {
                                resultStr += "&nbsp;";
                            }
                            resultStr += "</div>";
                            subresultStr += "<div class='Clear'></div> </div>";
                            if (competitorData.isSolo == 0)
                            {
                                subresultStr = "";
                                subresultStr += "<div class='Div_all_Laps_Hide' id='Div_all_laps_" + iRaceNo + "_" + iCategoryNo + "_" + iCompetitorNo + "'>";
                                subresultStr += "<input type='hidden' value='0' id='isHidden_" + iRaceNo + "_" + iCategoryNo + "_" + iCompetitorNo + "' />";
                                subresultStr += TeamLapDetail(competitorData.laps, iRaceNo, iCategoryNo, iCompetitorNo);
                                subresultStr += "</div>";
                            }
                            resultStr += "<div class='Clear'></div> </div>" + subresultStr + "<input type='hidden' value='" + competitorData.laps.length + "' id='currentRowLapCount_" + iRaceNo + "_" + iCategoryNo + "_" + iCompetitorNo + "' />"; ;
                            subresultStr = ""
                        }
                    });
                    // end of Loop 4
                    resultStr += "<input type='hidden' value='" + noOfRows + "' id='maxNoRows_" + iRaceNo + "_" + iCategoryNo + "' /></div>";
                    noOfRows = 0;

                }
            });
            // End of Loop 3

        }
        resultStr += "<div class='line9'>&nbsp;</div>";
    });
    // End of Loop1
    resultStr += "</div>";

    $("#mainRaceBody").html(resultStr);
}


function ByCategory()
{
    var resultStr = '';
    var subresultStr = '';
    var noOfRows = 0;
    var minumTime = '';
    var maxLaps = 0;
    var defaultShow = 2;
    var ttRaces = ttEvent.races;
    resultStr += "<div id='ByCategoryResult'>";
    // For Finding all the Races : Loop1
    $.each(ttRaces, function (iRaceNo, ttRacesData)
    {

        resultStr += "<div class='Race_Title'>" + ttRacesData.title + "</div>"
        // Checking the competitors in Races : Loop 2
        if (ttRacesData.teams.length < 1)
        {
            resultStr += "<div class='Empty_Race'>Race not run</div>";

        }
        else
        {
            var ttcompetitorsByCategories = ttRacesData.competitorsByCategories;

            //Searching data with in competitorsByCategories : Loop3
            $.each(ttcompetitorsByCategories, function (iCategoryNo, ttCategoryData)
            {
                var isAllTeam = CheckAllnonSoloByCategory(ttCategoryData.competitors, iRaceNo);
                resultStr += "<div class='Race_Category'>" + ttCategoryData.title + "</div>";
                if (ttCategoryData.competitors.length < 1)
                {
                    resultStr += "<div class='Empty_Race'>Race not run...</div>";
                    resultStr += "<div class='line9'>&nbsp;</div>";
                }
                else
                {

                    resultStr += "<div style='clear:both;' id='RaceNumber_" + iRaceNo + "_" + iCategoryNo + "'><div class='Div_Main_Div'><div class='Heading_Position'>Pos.</div> ";
                    if (!isAllTeam)
                    {
                        resultStr += "<div class='Heading_Number'>No.</div> ";
                    }

                    resultStr += " <div class='Heading_Name'>Name/Club</div> <div class='Heading_Laps_Count'>Laps</div>";
                    resultStr += "<div class='Heading_Time'>Time</div> <div class='Heading_Plus_Minus'>+/-</div>";
                    resultStr += "<div class='Heading_Fastest_Lap'>Fastest Lap<span>&nbsp;</span></div><div class='Div_Image' style='cursor:default;'>&nbsp;</div>";
                    if (!IsDNF(ttRacesData.teams[ttCategoryData.competitors[0]]))
                    {
                        maxLaps = ttRacesData.teams[ttCategoryData.competitors[0]].laps.length;
                    }
                    else
                    {
                        maxLaps = ttRacesData.teams[ttCategoryData.competitors[0]].laps.length - 1;
                    }
                    for (var i = 0; i < maxLaps; i++)
                    {
                        if (i < defaultShow)
                        {
                            resultStr += "<div class='Heading_Lap_show' id='race_" + iRaceNo + "_Cat_" + iCategoryNo + "_HLap_" + i + "' >Lap " + (i + 1) + " </div>";
                        }
                        else
                        {
                            resultStr += "<div class='Heading_Lap_Hide' id='race_" + iRaceNo + "_Cat_" + iCategoryNo + "_HLap_" + i + "' >Lap " + (i + 1) + " </div>";
                        }
                    }
                    resultStr += "<div class='Div_Image' style='cursor:default;' >&nbsp;</div><div style='clear:both;'></div></div><input type='hidden' id='race_maxLaps_" + iRaceNo + "_" + iCategoryNo + "' value='" + maxLaps + "' />";
                    resultStr += "<input type='hidden' id='currentShowing_" + iRaceNo + "_" + iCategoryNo + "' value='1' />";
                    // getting id of participants in particular category : loop 4
                    $.each(ttCategoryData.competitors, function (iCompetitorNo, ttCompetitorData)
                    {

                       
                        noOfRows = noOfRows + 1;
                        var competitorData = ttRacesData.teams[ttCompetitorData];
                        if (iCompetitorNo == 0)
                        {
                            minumTime = competitorData.totalTime;
                        }
                        var title = "Please click to see the laps for ";
                        if (competitorData.club.length > 0)
                        {
                            title += competitorData.name + " / " + competitorData.club;
                        }
                        else
                        {
                            title += competitorData.name;
                        }
                        if ((iCompetitorNo % 2) != 0)
                        {
                            resultStr += "<div class='Div_Odd' title='" + title + "' id='rowNo_" + iRaceNo + "_" + iCategoryNo + "_" + iCompetitorNo + "' onClick='togglebyCategory(" + iRaceNo + "," + iCategoryNo + " ," + iCompetitorNo + ")'>";
                        }
                        else
                        {
                            resultStr += "<div class='Div_Even' title='" + title + "' id='rowNo_" + iRaceNo + "_" + iCategoryNo + "_" + iCompetitorNo + "' onClick='togglebyCategory(" + iRaceNo + "," + iCategoryNo + " ," + iCompetitorNo + ")'>";
                        }
                        if (!IsDNF(competitorData))
                        {
                            resultStr += "<div class='Div_Position'>" + (iCompetitorNo + 1) + "</div> ";
                        }
                        else
                        {
                            resultStr += "<div class='Div_Position'>DNF</div> ";
                        }
                        if (!isAllTeam)
                        {
                            if (competitorData.isSolo == 1)
                            {
                                resultStr += " <div class='Div_Number'>" + competitorData.raceNumber + "</div>";
                            }
                            else
                            {
                                resultStr += " <div class='Div_Number'>&nbsp;</div>";
                            }
                        }
                        if (competitorData.club.length > 0)
                        {
                            resultStr += "<div class='Div_Name' title='" + competitorData.name + " / " + competitorData.club + " , Please click here to see the laps'><span class='Div_Name_Image'  id='span_" + iRaceNo + "_" + iCategoryNo + "_" + iCompetitorNo + "'><img alt='' src='" + imageLink + "Arrow_1.png' style='width:13px; height:13px;' /></span> <span class='Div_Name_span'> " + competitorData.name + "</span> / " + competitorData.club + "</div>";
                        }
                        else
                        {
                            resultStr += "<div class='Div_Name' title='" + competitorData.name + " , Please click here to see the laps'><span class='Div_Name_Image'  id='span_" + iRaceNo + "_" + iCategoryNo + "_" + iCompetitorNo + "'><img alt='' src='" + imageLink + "Arrow_1.png' style='width:13px; height:13px;' /></span> <span class='Div_Name_span'> " + competitorData.name + "</span></div>";
                        }
                        if ((!IsDNF(competitorData)))
                        {
                            resultStr += "<div class='Div_Laps_Count'>" + competitorData.laps.length + "</div>";
                        }
                        else
                        {
                            resultStr += "<div class='Div_Laps_Count'>" + (competitorData.laps.length - 1) + "</div>";
                        }

                        resultStr += "<div class='Div_Time'>" + competitorData.totalTime + "</div>";
                        if (iCompetitorNo == 0)
                        {
                            resultStr += "<div class='Div_Plus_Minus'> 00:00:00</div>";
                        }
                        else
                        {
                            if (!IsDNF(competitorData))
                            {
                                if (maxLaps == competitorData.laps.length)
                                {
                                    resultStr += "<div class='Div_Plus_Minus'>" + TimeDiff(competitorData.totalTime, minumTime) + "</div>";
                                }
                                else
                                {
                                    if ((maxLaps - competitorData.laps.length) > 1)
                                    {
                                        resultStr += "<div class='Div_Plus_Minus'> + " + (maxLaps - competitorData.laps.length) + " Laps</div>";
                                    }
                                    else
                                    {
                                        resultStr += "<div class='Div_Plus_Minus'> + " + (maxLaps - competitorData.laps.length) + " Lap</div>";
                                    }
                                }
                            }
                            else
                            {
                                if (maxLaps == (competitorData.laps.length - 1))
                                {
                                    resultStr += "<div class='Div_Plus_Minus'>" + TimeDiff(competitorData.totalTime, minumTime) + "</div>";
                                }
                                else
                                {
                                    if ((maxLaps - competitorData.laps.length) > 1)
                                    {
                                        resultStr += "<div class='Div_Plus_Minus'> + " + (maxLaps - (competitorData.laps.length - 1)) + " Laps</div>";
                                    }
                                    else
                                    {
                                        resultStr += "<div class='Div_Plus_Minus'> + " + (maxLaps - (competitorData.laps.length - 1)) + " Lap</div>";
                                    }
                                }
                            }

                        }
                        resultStr += "<div class='Div_Fastest_Lap'>" + FastestLap(competitorData.laps) + "<span>&nbsp;</span></div>";
                        resultStr += "<div class='Div_Image' onClick='shiftLeftByCategory(this,event);' style='cursor:default;'  id='left_" + iRaceNo + "_" + iCategoryNo + "_" + iCompetitorNo + "'>&nbsp;</div>";

                        subresultStr += "<div class='Div_all_Laps_Hide' id='Div_all_laps_" + iRaceNo + "_" + iCategoryNo + "_" + iCompetitorNo + "'>";
                        // Getting all the laps of competitior : Loop 5
                        $.each(competitorData.laps, function (iLapNo, ttLapData)
                        {
                            var iLapTime = ttLapData.lapTime.split(':')[2] >= 0 ? false : true;
                            if (!iLapTime)
                            {
                                if (iLapNo < defaultShow)
                                {
                                    resultStr += "<div class='Div_Lap_Show' id='Lap_" + iRaceNo + "_" + iCategoryNo + "_" + iCompetitorNo + "_" + iLapNo + "'>" + ttLapData.lapTime + "</div>";
                                }
                                else
                                {
                                    resultStr += "<div class='Div_Lap_Hide' id='Lap_" + iRaceNo + "_" + iCategoryNo + "_" + iCompetitorNo + "_" + iLapNo + "'>" + ttLapData.lapTime + "</div>";
                                }
                                subresultStr += "<div class='Div_Block'> <div class='Div_Block_Heading'> Lap" + (iLapNo + 1) + "</div> <div class='Div_Block_Lap'>" + ttLapData.lapTime + "</div></div>";
                            }
                        });
                        // End of Loop 5
                        subresultStr += "<input type='hidden' value='0' id='isHidden_" + iRaceNo + "_" + iCategoryNo + "_" + iCompetitorNo + "' />";
                        resultStr += "<div class='Div_Image' id='right_" + iRaceNo + "_" + iCategoryNo + "_" + iCompetitorNo + "' onClick='ShiftRightByCategory(this,event)'>";
                        if (competitorData.laps.length > defaultShow)
                        {
                            resultStr += "<img src='"+ imageLink +"Arrow_1.png' style=' height:13px; width:13px;' alt='Click here to see Next lap' />";
                        }
                        else
                        {
                            resultStr += "&nbsp;";
                        }
                        resultStr += "</div>";
                        subresultStr += "<div class='Clear'></div> </div>";

                        if (competitorData.isSolo == 0)
                        {
                            subresultStr = "";
                            subresultStr += "<div class='Div_all_Laps_Hide' id='Div_all_laps_" + iRaceNo + "_" + iCategoryNo + "_" + iCompetitorNo + "'>";
                            subresultStr += "<input type='hidden' value='0' id='isHidden_" + iRaceNo + "_" + iCategoryNo + "_" + iCompetitorNo + "' />";
                            subresultStr += TeamLapDetail(competitorData.laps, iRaceNo, iCategoryNo, iCompetitorNo);
                            subresultStr += "</div>";
                        }
                        resultStr += "<div class='Clear'></div> </div>" + subresultStr + "<input type='hidden' value='" + competitorData.laps.length + "' id='currentRowLapCount_" + iRaceNo + "_" + iCategoryNo + "_" + iCompetitorNo + "' />"; ;
                        subresultStr = ""
                    });
                    // end of Loop 4
                    resultStr += "<input type='hidden' value='" + noOfRows + "' id='maxNoRows_" + iRaceNo + "_" + iCategoryNo + "' /></div>";
                    noOfRows = 0;

                }
            });
            // End of Loop 3

        }
        resultStr += "<div class='line9'>&nbsp;</div>";

    });
    // End of Loop1
    resultStr += "</div>";

    $("#mainRaceBody").html(resultStr);
}

function shiftLeftByCategory(ctrl, event)
{
    var ctrlDiv = ctrl.id.split('_');
    var currentShow = parseInt($("#currentShowing_" + ctrlDiv[1] + "_" + ctrlDiv[2]).val());
    var maxLap = parseInt($("#race_maxLaps_" + ctrlDiv[1] + "_" + ctrlDiv[2]).val());
    var maxRow = parseInt($("#maxNoRows_" + ctrlDiv[1] + "_" + ctrlDiv[2]).val());

    for (var i = 0; i < maxRow; i++)
    {
        if (((currentShow) > 1))
        {
            var currentRowLapcount = $("#currentRowLapCount_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + i).val();
            if (currentRowLapcount > (currentShow))
            {
                $("#right_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + i).show();
                $("#right_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + i).html("<img src='"+ imageLink +"Arrow_1.png' style=' height:13px; width:13px;' /> ");
            }
            else
            {
                $("#right_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + i).hide();
                $("#right_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + i).html('');
            }
            if (i == 0)
            {

                $("#race_" + ctrlDiv[1] + "_Cat_" + ctrlDiv[2] + "_HLap_" + (currentShow - 2)).removeClass("Heading_Lap_Hide").addClass("Heading_Lap_show");
                $("#race_" + ctrlDiv[1] + "_Cat_" + ctrlDiv[2] + "_HLap_" + (currentShow)).removeClass("Heading_Lap_show").addClass("Heading_Lap_Hide");
            }
            $("#Lap_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + i + "_" + (currentShow - 2)).removeClass("Div_Lap_Hide").addClass("Div_Lap_Show");
            $("#Lap_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + i + "_" + (currentShow)).removeClass("Div_Lap_Show").addClass("Div_Lap_Hide");
            if ((currentShow - 1) > 1)
            {
                $("#left_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + i).html("<img src='"+ imageLink +"Arrow_3.png' style=' height:13px; width:13px;' alt='Click here to see previous lap' /> ");
                $("#left_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + i).css("cursor", "pointer")
            }
            else
            {
                $("#left_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + i).html("");
                $("#left_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + i).css("cursor", "default")
            }
        }
    }
    currentShow = currentShow - 1;
    if (currentShow < 1)
    {
        currentShow = 1;
    }
    $("#currentShowing_" + ctrlDiv[1] + "_" + ctrlDiv[2]).val(currentShow);
    event.stopPropagation();
}

function ShiftRightByCategory(ctrl, event)
{
    var ctrlDiv = ctrl.id.split('_');
    var currentShow = parseInt($("#currentShowing_" + ctrlDiv[1] + "_" + ctrlDiv[2]).val());
    var maxLap = parseInt($("#race_maxLaps_" + ctrlDiv[1] + "_" + ctrlDiv[2]).val());
    var maxRow = parseInt($("#maxNoRows_" + ctrlDiv[1] + "_" + ctrlDiv[2]).val());

    for (var i = 0; i < maxRow; i++)
    {
        if (((currentShow + 2) <= maxLap))
        {
            var currentRowLapcount = $("#currentRowLapCount_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + i).val();
            if (currentRowLapcount > (currentShow + 2))
            {
                $("#right_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + i).show();
                $("#right_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + i).html("<img src='"+ imageLink +"Arrow_1.png' style=' height:13px; width:13px;' alt='Click here to see previous lap' /> ");
            }
            else
            {
                $("#right_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + i).hide();
                $("#right_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + i).html('');
            }
            if (i == 0)
            {

                $("#race_" + ctrlDiv[1] + "_Cat_" + ctrlDiv[2] + "_HLap_" + (currentShow - 1)).removeClass("Heading_Lap_show").addClass("Heading_Lap_Hide");
                $("#race_" + ctrlDiv[1] + "_Cat_" + ctrlDiv[2] + "_HLap_" + (currentShow + 1)).removeClass("Heading_Lap_Hide").addClass("Heading_Lap_show");
            }
            $("#Lap_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + i + "_" + (currentShow - 1)).removeClass("Div_Lap_Show").addClass("Div_Lap_Hide");
            $("#Lap_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + i + "_" + (currentShow + 1)).removeClass("Div_Lap_Hide").addClass("Div_Lap_Show");
            $("#left_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + i).html("<img src='"+ imageLink +"Arrow_3.png' style=' height:13px; width:13px;' alt='Click here to see previous lap' /> ");
            $("#left_" + ctrlDiv[1] + "_" + ctrlDiv[2] + "_" + i).css("cursor", "pointer");
        }
    }
    currentShow = currentShow + 1;
    $("#currentShowing_" + ctrlDiv[1] + "_" + ctrlDiv[2]).val(currentShow);
    event.stopPropagation();
}


function togglebyCategory(RaceNo, iCategoryNo, RowNo)
{
    var currentDiv = $(".Div_all_Laps_show");
    if (currentDiv[0] != null)
    {
        var currentDivID = currentDiv[0].id.split("_");
    }

    var isHidden = $("#isHidden_" + RaceNo + "_" + iCategoryNo + "_" + RowNo).val();
    if (isHidden == "0")
    {
        $("#span_" + RaceNo + "_" + iCategoryNo + "_" + RowNo).html("<img style=' height:13px; width:13px;' src='"+ imageLink +"Arrow2.png' alt=''>");
        $("#Div_all_laps_" + RaceNo + "_" + iCategoryNo + "_" + RowNo).removeClass("Div_all_Laps_Hide").addClass("Div_all_Laps_show");
        $("#isHidden_" + RaceNo + "_" + iCategoryNo + "_" + RowNo).val("1");
    }
    else
    {
        $("#span_" + RaceNo + "_" + iCategoryNo + "_" + RowNo).html("<img style=' height:13px; width:13px;' src='"+ imageLink +"Arrow_1.png' alt=''>");
        $("#Div_all_laps_" + RaceNo + "_" + iCategoryNo + "_" + RowNo).removeClass("Div_all_Laps_show").addClass("Div_all_Laps_Hide");
        $("#isHidden_" + RaceNo + "_" + iCategoryNo + "_" + RowNo).val("0");
    }

}

function IsDNF(ttCompetitorData)
{
    var lapsData = ttCompetitorData.laps;
    var lapLength = lapsData.length;
    var lastLap = lapsData[lapLength - 1].lapTime.split(':');
    var isDnf = parseFloat(lastLap[2]) >= 0 ? false : true;
    return isDnf;
}

function ByOrder()
{
    var resultStr = '';
    var subresultStr = '';
    var noOfRows = 0;
    var minumTime = '';
    var maxLaps = 0;
    var defaultShow = 2;

    if (ttEvent.tabCount == 0)
    {
        imageLink = "../images/";
    }
    else
    {
        imageLink = "../../images/";
    }

    var ttRaces = ttEvent.races;
    resultStr += "<div id='ByOrderResult'>";
    // For Finding all the Races : Loop1
    $.each(ttRaces, function (iRaceNo, ttRacesData)
    {
        var isAllTeam = CheckAllnonSoloByOrder(ttRacesData);
        resultStr += "<div class='Race_Title' style='float: left; width:300px;'>" + ttRacesData.title + "</div>"
        // Checking the competitors in Races : Loop 2
        if (ttRacesData.teams.length < 1)
        {
            resultStr += "<div style='clear:both;'></div>";
            resultStr += "<div class='Empty_Race'>Race not run</div>";

        }
        else
        {

            resultStr += "<div style='clear:both;' id='RaceNumber_" + iRaceNo + "'><div class='Div_Main_Div'><div class='Heading_Position'>Pos.</div> ";
            if (!isAllTeam)
            {
                resultStr += "<div class='Heading_Number'>No.</div> ";
            }
            resultStr += "<div class='Heading_Name'>Name/Club</div> <div class='Heading_Laps_Count'>Laps</div>";
            resultStr += "<div class='Heading_Time'>Time</div> <div class='Heading_Plus_Minus'>+/-</div>";
            resultStr += "<div class='Heading_Fastest_Lap'>Fastest Lap<span>&nbsp;</span></div><div class='Div_Image' style='cursor:default;'>&nbsp;</div>";
            if (!IsDNF(ttRacesData.teams[0]))
            {
                maxLaps = ttRacesData.teams[0].laps.length;
            }
            else
            {
                maxLaps = ttRacesData.teams[0].laps.length - 1;
            }
            for (var i = 0; i < maxLaps; i++)
            {
                if (i < defaultShow)
                {
                    resultStr += "<div class='Heading_Lap_show' id='race_" + iRaceNo + "_HLap_" + i + "' >Lap " + (i + 1) + " </div>";
                }
                else
                {
                    resultStr += "<div class='Heading_Lap_Hide' id='race_" + iRaceNo + "_HLap_" + i + "' >Lap " + (i + 1) + " </div>";
                }
            }
            resultStr += "<div class='Div_Image' style='cursor:default;' >&nbsp;</div><div style='clear:both;'></div></div><input type='hidden' id='race_maxLaps_" + iRaceNo + "' value='" + maxLaps + "' />";
            resultStr += "<input type='hidden' id='currentShowing_" + iRaceNo + "' value='1' />";
            //Getting info for each competitor : Loop 3
            $.each(ttRacesData.teams, function (iComptitorNo, ttCompetitorData)
            {

                var title = "Please click to see the laps for ";
                if (ttCompetitorData.club.length > 0)
                {
                    title += ttCompetitorData.name + " / " + ttCompetitorData.club;
                }
                else
                {
                    title += ttCompetitorData.name;
                }
                noOfRows = noOfRows + 1;
                if (iComptitorNo == 0)
                {
                    minumTime = ttCompetitorData.totalTime;
                    maxLaps = ttCompetitorData.laps.length;
                }
                if ((iComptitorNo % 2) != 0)
                {
                    resultStr += "<div class='Div_Odd' title='" + title + "' id='rowNo_" + iRaceNo + "_" + iComptitorNo + "' onClick='toggle(" + iRaceNo + ", " + iComptitorNo + ")' >";
                }
                else
                {
                    resultStr += "<div class='Div_Even' title='" + title + "' id='rowNo_" + iRaceNo + "_" + iComptitorNo + "' onClick='toggle(" + iRaceNo + ", " + iComptitorNo + ")'>";
                }
                if (!IsDNF(ttCompetitorData))
                {
                    resultStr += "<div class='Div_Position'>" + (iComptitorNo + 1) + "</div>";
                }
                else
                {
                    resultStr += "<div class='Div_Position'>DNF</div>";
                }
                if (!isAllTeam)
                {
                    if (ttCompetitorData.isSolo == 1)
                    {
                        resultStr += "<div class='Div_Number'>" + ttCompetitorData.raceNumber + "</div>";
                    }
                    else
                    {
                        resultStr += "<div class='Div_Number'> &nbsp;</div>";
                    }
                }
                if (ttCompetitorData.club.length > 0)
                {
                    resultStr += "<div class='Div_Name' title='" + ttCompetitorData.name + " / " + ttCompetitorData.club + " , Please click here to see the laps '><span class='Div_Name_Image'  id='span_" + iRaceNo + "_" + iComptitorNo + "'><img alt='' src='"+ imageLink +"Arrow_1.png' style='width:13px; height:13px;' /></span> <span class='Div_Name_span'> " + ttCompetitorData.name + "</span> / " + ttCompetitorData.club + "</div>";
                }
                else
                {
                    resultStr += "<div class='Div_Name' title='" + ttCompetitorData.name + " , Please click here to see the laps'><span class='Div_Name_Image' id='span_" + iRaceNo + "_" + iComptitorNo + "'><img alt='' src='" + imageLink + "Arrow_1.png' style='width:13px; height:13px;' /></span> <span class='Div_Name_span'> " + ttCompetitorData.name + "</span> </div>";
                }
                if (!IsDNF(ttCompetitorData))
                {
                    resultStr += "<div class='Div_Laps_Count'>" + ttCompetitorData.laps.length + "</div>";
                }
                else
                {
                    resultStr += "<div class='Div_Laps_Count'>" + (ttCompetitorData.laps.length - 1) + "</div>";
                }
                resultStr += "<div class='Div_Time'>" + ttCompetitorData.totalTime + "</div>";
                if (iComptitorNo == 0)
                {
                    resultStr += "<div class='Div_Plus_Minus'> 00:00:00</div>";
                }
                else
                {
                    if (!IsDNF(ttCompetitorData))
                    {
                        if (maxLaps == ttCompetitorData.laps.length)
                        {
                            resultStr += "<div class='Div_Plus_Minus'>" + TimeDiff(ttCompetitorData.totalTime, minumTime) + "</div>";
                        }
                        else
                        {
                            if ((maxLaps - ttCompetitorData.laps.length) > 1)
                            {
                                resultStr += "<div class='Div_Plus_Minus'> + " + (maxLaps - ttCompetitorData.laps.length) + " Laps</div>";
                            }
                            else
                            {
                                resultStr += "<div class='Div_Plus_Minus'> + " + (maxLaps - ttCompetitorData.laps.length) + " Lap</div>";
                            }
                        }
                    }
                    else
                    {
                        if (maxLaps == (ttCompetitorData.laps.length - 1))
                        {
                            resultStr += "<div class='Div_Plus_Minus'>" + TimeDiff(ttCompetitorData.totalTime, minumTime) + "</div>";
                        }
                        else
                        {
                            if ((maxLaps - (ttCompetitorData.laps.length - 1)) > 1)
                            {
                                resultStr += "<div class='Div_Plus_Minus'> + " + (maxLaps - (ttCompetitorData.laps.length - 1)) + " Laps</div>";
                            }
                            else
                            {
                                resultStr += "<div class='Div_Plus_Minus'> + " + (maxLaps - (ttCompetitorData.laps.length - 1)) + " Lap</div>";
                            }
                        }
                    }
                }
                resultStr += "<div class='Div_Fastest_Lap'>" + FastestLap(ttCompetitorData.laps) + "<span>&nbsp;</span></div>";
                resultStr += "<div class='Div_Image' onClick='shiftLeftByOrder(this,event);' style='cursor:default;'   id='left_" + iRaceNo + "_" + iComptitorNo + "'>&nbsp;</div>";

                subresultStr += "<div class='Div_all_Laps_Hide' id='Div_all_laps_" + iRaceNo + "_" + iComptitorNo + "'>";
                // Getting all the laps of competitior : Loop 4
                $.each(ttCompetitorData.laps, function (iLapNo, ttLapData)
                {
                    var iLapTime = ttLapData.lapTime.split(':');
                    if (iLapTime[2] >= 0)
                    {
                        if (iLapNo < defaultShow)
                        {
                            resultStr += "<div class='Div_Lap_Show' id='Lap_" + iRaceNo + "_" + iComptitorNo + "_" + iLapNo + "'>" + ttLapData.lapTime + "</div>";
                        }
                        else
                        {
                            resultStr += "<div class='Div_Lap_Hide' id='Lap_" + iRaceNo + "_" + iComptitorNo + "_" + iLapNo + "'>" + ttLapData.lapTime + "</div>";
                        }
                        if (ttLapData.competitorName == ttCompetitorData.name)
                        {
                            subresultStr += "<div class='Div_Block'> <div class='Div_Block_Heading'> Lap" + (iLapNo + 1) + "</div> <div class='Div_Block_Lap'>" + ttLapData.lapTime + "</div></div>";
                        }
                        else
                        {
                            subresultStr += "<div class='Div_Block' title = 'This Lap is run by " + ttLapData.competitorName + "'> <div class='Div_Block_Heading'> Lap" + (iLapNo + 1) + "</div> <div class='Div_Block_Lap'>" + ttLapData.lapTime + "</div></div>";
                        }
                    }
                });
                // End of Loop 4

                resultStr += "<div class='Div_Image' id='right_" + iRaceNo + "_" + iComptitorNo + "' onClick='ShiftRightByOrder(this,event)'>";
                if (ttCompetitorData.laps.length > defaultShow)
                {
                    resultStr += "<img   src='"+ imageLink +"Arrow_1.png' style=' height:13px; width:13px;' alt='Click here to see Next lap' />";
                }
                else
                {
                    resultStr += "&nbsp;";
                }
                resultStr += "</div>";
                subresultStr += "<input type='hidden' value='0' id='isHidden_" + iRaceNo + "_" + iComptitorNo + "' /> ";
                subresultStr += "<div class='Clear'></div> </div>";
                if (ttCompetitorData.isSolo == 0)
                {
                    subresultStr = "";
                    subresultStr += "<div class='Div_all_Laps_Hide' id='Div_all_laps_" + iRaceNo + "_" + iComptitorNo + "'>";
                    subresultStr += "<input type='hidden' value='0' id='isHidden_" + iRaceNo + "_" + iComptitorNo + "' /> ";
                    subresultStr += TeamLapDetail(ttCompetitorData.laps, iRaceNo, 0, iComptitorNo);
                    subresultStr += "</div>";
                }
                resultStr += "<div class='Clear'></div> </div>" + subresultStr + "<input type='hidden' value='" + ttCompetitorData.laps.length + "' id='currentRowLapCount_" + iRaceNo + "_" + iComptitorNo + "' />"; ;
                subresultStr = "";

            });
            // end of Loop 3
            resultStr += "<input type='hidden' value='" + noOfRows + "' id='maxNoRows_" + iRaceNo + "' /></div>";
            noOfRows = 0;

        }
        // end of Loop 2
        resultStr += "<div class='line9'>&nbsp;</div>";
    });
    // End of Loop1
    resultStr += "</div>";

    $("#mainRaceBody").html(resultStr);
}

function shiftLeftByOrder(ctrl, event)
{
    var ctrlDiv = ctrl.id.split('_');
    var currentShow = parseInt($("#currentShowing_" + ctrlDiv[1]).val());
    var maxLap = parseInt($("#race_maxLaps_" + ctrlDiv[1]).val());
    var maxRow = parseInt($("#maxNoRows_" + ctrlDiv[1]).val());

    for (var i = 0; i < maxRow; i++)
    {
        if (((currentShow + 2) <= maxLap) && ((currentShow) >= 1))
        {
            var currentRowLapcount = $("#currentRowLapCount_" + ctrlDiv[1] + "_" + i).val();
            if (currentRowLapcount > (currentShow))
            {
                $("#right_" + ctrlDiv[1] + "_" + i).show();
                $("#right_" + ctrlDiv[1] + "_" + i).html("<img src='"+ imageLink +"Arrow_1.png' style=' height:13px; width:13px;' alt='Click here to see previous lap' /> ");
            }
            else
            {
                $("#right_" + ctrlDiv[1] + "_" + i).hide();
                $("#right_" + ctrlDiv[1] + "_" + i).html('');
            }
            if (i == 0)
            {

                $("#race_" + ctrlDiv[1] + "_HLap_" + (currentShow - 1)).removeClass("Heading_Lap_Hide").addClass("Heading_Lap_show");
                $("#race_" + ctrlDiv[1] + "_HLap_" + (currentShow + 1)).removeClass("Heading_Lap_show").addClass("Heading_Lap_Hide");
            }
            $("#Lap_" + ctrlDiv[1] + "_" + i + "_" + (currentShow - 1)).removeClass("Div_Lap_Hide").addClass("Div_Lap_Show");
            $("#Lap_" + ctrlDiv[1] + "_" + i + "_" + (currentShow + 1)).removeClass("Div_Lap_Show").addClass("Div_Lap_Hide");
            if (currentShow > 1)
            {
                $("#left_" + ctrlDiv[1] + "_" + i).css("cursor", "pointer");
                $("#left_" + ctrlDiv[1] + "_" + i).html("<img src='"+ imageLink +"Arrow_3.png' style=' height:13px; width:13px;' alt='Click here to see previous lap' /> ");
            }
            else
            {
                $("#left_" + ctrlDiv[1] + "_" + i).html("");
                $("#left_" + ctrlDiv[1] + "_" + i).css("cursor", "default");
            }
        }
    }
    currentShow = currentShow - 1;
    if (currentShow < 1)
    {
        currentShow = 1;
    }
    $("#currentShowing_" + ctrlDiv[1]).val(currentShow);
    event.stopPropagation();
}

function ShiftRightByOrder(ctrl, event)
{
    var ctrlDiv = ctrl.id.split('_');
    var currentShow = parseInt($("#currentShowing_" + ctrlDiv[1]).val());
    var maxLap = parseInt($("#race_maxLaps_" + ctrlDiv[1]).val());
    var maxRow = parseInt($("#maxNoRows_" + ctrlDiv[1]).val());

    for (var i = 0; i < maxRow; i++)
    {
        if (((currentShow + 2) <= maxLap))
        {
            var currentRowLapcount = $("#currentRowLapCount_" + ctrlDiv[1] + "_" + i).val();
            if (currentRowLapcount > (currentShow + 2))
            {
                $("#right_" + ctrlDiv[1] + "_" + i).show();
                $("#right_" + ctrlDiv[1] + "_" + i).html("<img src='"+ imageLink +"Arrow_1.png' style=' height:13px; width:13px;' alt='Click here to see previous lap' /> ");
            }
            else
            {
                $("#right_" + ctrlDiv[1] + "_" + i).hide();
                $("#right_" + ctrlDiv[1] + "_" + i).html('');
            }
            if (i == 0)
            {

                $("#race_" + ctrlDiv[1] + "_HLap_" + (currentShow - 1)).removeClass("Heading_Lap_show").addClass("Heading_Lap_Hide");
                $("#race_" + ctrlDiv[1] + "_HLap_" + (currentShow + 1)).removeClass("Heading_Lap_Hide").addClass("Heading_Lap_show");
            }
            $("#Lap_" + ctrlDiv[1] + "_" + i + "_" + (currentShow - 1)).removeClass("Div_Lap_Show").addClass("Div_Lap_Hide");
            $("#Lap_" + ctrlDiv[1] + "_" + i + "_" + (currentShow + 1)).removeClass("Div_Lap_Hide").addClass("Div_Lap_Show");
            $("#left_" + ctrlDiv[1] + "_" + i).html("<img src='"+ imageLink +"Arrow_3.png' style=' height:13px; width:13px;' alt='Click here to see previous lap' /> ");
            $("#left_" + ctrlDiv[1] + "_" + i).css("cursor", "pointer");
        }
    }
    currentShow = currentShow + 1;
    $("#currentShowing_" + ctrlDiv[1]).val(currentShow);
    event.stopPropagation();
}

function FastestLap(a)
{
    var test = a;
    var LapArray = new Array();

    $.each(test, function (i, val)
    {
        var isDNF = val.lapTime.split(':')[2] >= 0 ? false : true;
        if (!isDNF)
        {
            LapArray[i] = val.lapTime;
        }
    });

    var resultarray = LapArray.sort();
    var result = resultarray[0];
    return result;


}

var ToogleByOrder = false;

function toggle(RaceNo, RowNo)
{

    var currentDiv = $(".Div_all_Laps_show");
    if (currentDiv[0] != null)
    {
        var currentDivID = currentDiv[0].id.split("_");
    }

    var isHidden = $("#isHidden_" + RaceNo + "_" + RowNo).val();
    if (isHidden == "0")
    {
        $("#span_" + RaceNo + "_" + RowNo).html("<img style=' height:13px; width:13px;' src='"+ imageLink +"Arrow2.png' alt=''>");
        $("#Div_all_laps_" + RaceNo + "_" + RowNo).removeClass("Div_all_Laps_Hide").addClass("Div_all_Laps_show");
        $("#isHidden_" + RaceNo + "_" + RowNo).val("1");
    }
    else
    {
        $("#span_" + RaceNo + "_" + RowNo).html("<img style=' height:13px; width:13px;' src='"+ imageLink +"Arrow_1.png' alt=''>");
        $("#Div_all_laps_" + RaceNo + "_" + RowNo).removeClass("Div_all_Laps_show").addClass("Div_all_Laps_Hide");
        $("#isHidden_" + RaceNo + "_" + RowNo).val("0");
    }


}



function TimeDiff(a, b)
{

    var time1 = Secs(a);
    var time2 = Secs(b);
    var diff = parseFloat(time1) - parseFloat(time2);
    var result = '';

    return diffResult(diff);
}

function diffResult(interval)
{
    var hours = Math.floor(interval / (60 * 60));
    interval -= hours * (60 * 60);

    var minutes = Math.floor(interval / 60);
    interval -= minutes * 60;

    var seconds = Math.floor(interval);
    interval -= seconds;

    var miliseconds = interval.toFixed(1);

    var milisecParts = miliseconds.toString().split(".");

    if (milisecParts[0] > 0)
        seconds = (parseInt(seconds) + parseInt(milisecParts)).toString();

    var milisecondsStr = milisecParts[1];

    lapTimeStr = getTwoDigits(hours) + ":" + getTwoDigits(minutes) + ":" + getTwoDigits(seconds) + "." + milisecondsStr;

    return lapTimeStr;
}

function getTwoDigits(n)
{
    var twoDig = "" + n;

    if (parseInt(n) < 10)
        twoDig = "0" + n;

    return twoDig;

}

function Secs(a)
{
    var vale = a.split(':');
    var total = '';
    total = parseFloat(vale[0]) * 60 * 60 + parseFloat(vale[1]) * 60 + parseFloat(vale[2]);
    return total;
}

// ----------- Here Start the new JS of compare by laps ------ //

var competitorArray = new Array(5);
var tlrRiders = null;
var tlrEvents = null;
var Colours = ['#242abf', '#44171d', '#a70cb5', '#0f6a14', '#f1061e'];
var maxRider = 5;
var maxSectionScaleWidth = 0;
var maxSectionTime = 0;
var pixelsPerSecond = 2;
var maxWidthAllowScroll = 0;
var maxSectionWidth = 150;
var lapContainer = 'lapcontainerHidden';
var lapScroll = 'divRightSelectLapContainer';
var blackFontsize = "font-size:13px;";

function Statics()
{
    var resultStr = "<div style='clear:both;font-family:helvetica, verdana, tahoma;" + blackFontsize + "'></div>";
    resultStr += "<div id='ResultStatistics' style='margin-top:10px; display:none;'>";
    resultStr += "<fieldset style='padding:5px;'>";
    resultStr += "<legend> Statistics </legend>";
    resultStr += "<div>";
    // Most Lap Div
    resultStr += "<div style='clear:both;padding:5px;' > ";
    resultStr += " <div style='float : left; width:200px;margin-bottom:3px; text-align:left;" + blackFontsize + "'> Most Laps</div> ";
    resultStr += "<div id='mostlapResult' style='float:left;  width:600px;text-align:left;" + blackFontsize + "'></div>";
    resultStr += "</div>";

    // Fastest lap
    resultStr += "<div style='clear:both;padding:5px;'>";
    resultStr += "<div style='float:left; width:200px;margin-bottom:3px; text-align:left;" + blackFontsize + ";'> Fastest Lap</div>";
    resultStr += "<div id='fastestlapResult' style='float:left; width:600px; text-align : left;" + blackFontsize + "'></div>";
    resultStr += "</div>";

    // Biggest Gap
    resultStr += "<div style='clear:both;padding:5px;'>";
    resultStr += "<div style='float:left; width:200px;margin-bottom:3px; text-align:left;" + blackFontsize + "'> Biggest Gap</div>";
    resultStr += "<div id='biggestlapResult' style='float:left; width:600px; text-align:left;" + blackFontsize + "'></div>";
    resultStr += "</div>";

    // Smallest Gap
    resultStr += "<div style='clear:both;padding:5px; margin-bottom:22px;'>";
    resultStr += "<div style='float:left; width:200px; text-align:left;" + blackFontsize + "'> Smallest Gap</div>";
    resultStr += "<div id='smallestlapResult' style='float:left; width:600px; text-align:left;" + blackFontsize + "'></div>";
    resultStr += "</div>";


    resultStr += "</div>";
    resultStr += "</fieldset>";
    resultStr += "</div>";
    return resultStr;
}

var scaleStyle = "padding:2px;font-family: helvetica, verdana, tahoma; font-size:13px; text-align:left;float:left;";

function Scale()
{
    var resultStr = "<div style='clear:both;font-family:helvetica, verdana, tahoma;font-size:14px;'></div>";
    resultStr += "<div style='margin-top:10px;display:none;'  id='ScaleContainer'>";
    resultStr += "<fieldset style='padding:5px;'>";
    resultStr += "<legend> Scale</legend>";
    resultStr += "<div style='padding-top:0px;margin-top:12px; display:none;" + blackFontsize + "' id='ScaleDiv'> ";
    resultStr += "<div style='padding-bottom:15px;padding-left:4px;'> <b>Time Gap</b></div>";
    resultStr += "<div style='clear:both;'>";
    resultStr += "<div style='" + scaleStyle + "; width:270px;'> 1 minute gap</div>";
    resultStr += "<div style='" + scaleStyle + "; position:relative;'> <img src='"+ imageLink +"racer.png' style='width:40px;left:0px;position:relative;' alt='' />  <img src='"+ imageLink +"racer.png' style='width:40px;margin-left:-11px; margin-top:0px;' alt='' /> </div>";
    resultStr += "<div style='clear:both;'></div>";
    resultStr += "</div>";

    resultStr += "<div  style='clear:both;'>";
    resultStr += "<div style='" + scaleStyle + "width:270px;'> 5 minutes gap</div>";
    resultStr += "<div style='" + scaleStyle + ";position:relative;'><img src='"+ imageLink +"racer.png' style='width:40px;left:0px;position:relative;' alt='' /> <img src='"+ imageLink +"racer.png' style='width:40px;margin-left:110px;margin-top:0px;' alt='' /></div>";
    resultStr += "<div style='clear:both;'></div>";
    resultStr += "</div>";


    resultStr += "<div  style='clear:both;margin-bottom:10px;'>";

    resultStr += "<div style='" + scaleStyle + "width:270px;'> 10 minutes gap</div>";
    resultStr += "<div style='" + scaleStyle + ";position:relative;'><img src='"+ imageLink +"racer.png' style='width:40px;left:0px;position:relative;' alt='' /> <img src='"+ imageLink +"racer.png' style='width:40px;margin-top:0px;margin-left:245px;' alt='' /></div>";
    resultStr += "<div style='clear:both;'></div>";
    resultStr += "</div>";



    resultStr += "</div>"
    resultStr += "</fieldset>";
    resultStr += "</div>";
    return resultStr;
}

function AllLegend()
{

    var resultStr = "<div style='clear:both;font-family:helvetica, verdana, tahoma;font-size:14px;'></div>";

    resultStr += "<div style='margin-top:10px;'>";
    resultStr += "<fieldset style='padding:5px;'>";
    resultStr += "<legend> Key </legend>"
    resultStr += "<ul style=\"font-family:helvetica, verdana, tahoma;" + blackFontsize + " line-height:16px;margin-top:0px; margin-left:-18px; list-style-image:url('"+ imageLink +"Rightarrow_15.png');\">";
    resultStr += "<li style='margin-top:5px;" + blackFontsize + " font-family:helvetica, verdana, tahoma;'>Final Position indicates the finishing position of the compared rider.</li>";
    resultStr += "<li style='margin-top:5px;" + blackFontsize + " font-family:helvetica, verdana, tahoma;'> The Rider Comparison Laps shows lap times are provided for each compared rider showing their individual lap times.</li>";
    resultStr += "<li style='margin-top:5px;" + blackFontsize + " font-family:helvetica, verdana, tahoma;'>The Rider Comparison Laps also shows the fastest lap for each compared rider, in bold underlined.</li>";
    resultStr += "<li style='margin-top:5px;" + blackFontsize + " font-family:helvetica, verdana, tahoma;'>Lap Indication is provided on the comparison graph as a cumulative lap time I.e. Lap 2 is the time for Lap 1 plus Lap 2.</li>";
    resultStr += "<li style='margin-top:5px;" + blackFontsize + " font-family:helvetica, verdana, tahoma;'> The Rider Comparison Graph shows the relative gaps and positions for each compared rider.</li>";
    resultStr += "<li style='margin-top:5px;" + blackFontsize + " font-family:helvetica, verdana, tahoma;'> A Relative Position Indicator is provided in the front wheel of each bike, showing the current position as compared to the other riders in the comparison.</li>";
    resultStr += "<li style='margin-top:5px;" + blackFontsize + " font-family:helvetica, verdana, tahoma;'> A Scale is provided to provide an indication of the gap between the last and first rider in the graph.</li>";
    resultStr += "<li style='margin-top:5px;" + blackFontsize + " font-family:helvetica, verdana, tahoma;'>A tooltip is provided when you hover your mouse over a rider in the graph. The tooltip shows the time difference between that rider and the rider currently in position 1 on the comparison graph (as provided by the Relative Position Indicator).</li>";
    resultStr += "</ul>";
    resultStr += "</fieldset>";
    resultStr += "</div>"
    return resultStr;
}

function CompareByLaps(iRaceNo)
{
    competitorArray = new Array(5);
    if (iRaceNo != "-1")
    {
        var resultStr = "";
        if (ttEvent.races[iRaceNo].teams.length > 2)
        {
            resultStr += "<p style='font-size:14px;font-family:helvetica, verdana, tahoma;'> <b>Race : </b> " + ttEvent.races[iRaceNo].title + " </p>";
            resultStr += "<p style='" + blackFontsize + ";font-family:helvetica, verdana, tahoma;' > Please select the riders that you wish to compare. " +
                          " </p> ";
            resultStr += "<div id='AllComparionContainer' style='clear:both; margin-bottom:10px;'>  " +
                       " <div id='divLeft' style='float:left; width:250px; vertical-align:top;'>  " +
                        " <div id='divLeftLap' style='padding-right:0px;height:20px; display:none;font-size:16px; text-align:left;color:#620E59;'><b> Rider Comparison Laps</b></div> " +
                        " <div id='divLeftSelectContainer' > ";
            for (var iIndex = 0; iIndex < maxRider; iIndex++)
            {
                var currColor = Colours[iIndex];
                resultStr += "<div style='background-color:#dcd2e6;height:30px;margin:2px; padding-top:7px; padding-left:7px;'> ";
                resultStr += "<select class='RaceNameSelect'  id='riderSelect_" + iIndex + "' onChange='OnPickRacer(this);' style='width:220px; color:" + currColor + "' >";
                resultStr += LoadRiderName(iRaceNo);
                resultStr += "</select></div>";
            }
            resultStr += "</div>  " +
                        " <div id='line20' style='height:38px; color:#620E59;font-size:16px; line-height:55px;'><b>Rider Comparison Graph</b></div> " +
                        " <div id='drawGraphleftHeader' style='background-color:#dcd2e6; padding:1px; width:245px;display:none;'></div> " +
                         " <div id='line17' style='height:3px;background-color:#dcd2e6;width:247px;display:none;'>&nbsp;</div> " +
                         "<div id='drawGraphleftCompetitorInfo' style='background-color:#dcd2e6;width:247px;display:none;'> " +
                         " <div id='DivGraphLeftCompetitorInfo1' style='min-height:30px;'>&nbsp;</div> " +
                         " <div id='DivGraphLeftCompetitorInfo2' style='min-height:30px;'>&nbsp;</div> " +
                         " <div id='DivGraphLeftCompetitorInfo3' style='min-height:30px;'>&nbsp;</div> " +
                         " <div id='DivGraphLeftCompetitorInfo4' style='min-height:30px;'>&nbsp;</div> " +
                          " <div id='DivGraphLeftCompetitorInfo5' style='min-height:30px;'>&nbsp;</div>" +
                        "  </div> " +
                        " </div> " +
                        " <div id='divRight'  style='float:left;vertical-align:top; width:630px;'> <div id='divRightScroll'>" +
                        "<div style='width:630px; clear:both;'>" +
                        " <div id='ScrollLeftUp' onmousedown=\"onXScrollStart(event, 'lapcontainerHidden', -25, 'divRightSelectLapContainer');\" onmouseup='clearIntervals();' onmouseout='clearIntervals();'   style='float:left; width:25px;  display:none; vertical-align:middle; text-align:center;cursor:pointer;'> &nbsp;<img src='"+ imageLink +"Arrow_3.png' style='width:15px;' /></div>" +
                        " <div id='lapcontainerHidden' style='width:570px; float:left; overflow:hidden;'>" +
                        "  <div id='divRightSelectLapContainer' style='left:0px;'   onmouseup=\"itemMouseUp(event,'lapcontainerHidden','divRightSelectLapContainer')\"  onmousedown=\"itemMouseDown(event,'lapcontainerHidden','divRightSelectLapContainer')\" onmousemove=\"itemMouseMove(event, 'lapcontainerHidden','divRightSelectLapContainer')\"> " +
                        "  <div id='divRightLap' style='height:20px; display:none;'></div> " +
                        "   <div id='divRightSelectLapData1' style='min-height:37px;padding-top:2px;'>&nbsp; </div> " +
                        "   <div id='divRightSelectLapData2'  style='min-height:37px;padding-top:2px;'>&nbsp;</div> " +
                        "   <div id='divRightSelectLapData3'  style='min-height:37px;padding-top:2px;'>&nbsp;</div> " +
                        "   <div id='divRightSelectLapData4'  style='min-height:37px;padding-top:2px;'>&nbsp;</div>" +
                        "   <div id='divRightSelectLapData5'  style='min-height:37px;padding-top:2px;'>&nbsp;</div>" +
                         " </div> " +
                         "</div>" +

                         " <div id='ScrollRightUp' onmousedown=\"onXScrollStart(event, 'lapcontainerHidden', 25, 'divRightSelectLapContainer');\" onmouseup='clearIntervals();' onmouseout='clearIntervals();'  style='float:left; width:25px; display:none; vertical-align:middle; text-align:center;cursor:pointer;'>&nbsp; <img src='"+ imageLink +"Arrow_1.png' style='width:15px;' /> </div>" +
                         "<div style='clear:both;'></div>" +
                         " </div> " +
                         " <div id='line9' style='height:40px;color:#620E59;line-height:50px;'>&nbsp;</div> " +
                        "<div id='ScrollConatinerDivAll' style='width:630px;'> " + // 3
            // Here Add
                         " <div id='ScrollLeftUp2' onmousedown=\"onXScrollStart(event, 'DivGrapgContainerForScrollParent', -25, 'DivGrapgContainerForssroll');\" onmouseup='clearIntervals();' onmouseout='clearIntervals();'   style='float:left;min-width:25px;  width:25px; vertical-align:middle; text-align:center;cursor:pointer;'> &nbsp;<img src='"+ imageLink +"Arrow_3.png' style='width:15px;' /></div>" +
                         "<div id='DivGrapgContainerForScrollParent' style='width:570px; float:left; overflow:hidden;'>" + // 2
                         "<div id='DivGrapgContainerForssroll' style='left:0px;'    onmouseup=\"itemMouseUp(event, 'DivGrapgContainerForScrollParent','DivGrapgContainerForssroll');\"  onmousedown=\"itemMouseDown(event,'DivGrapgContainerForScrollParent','DivGrapgContainerForssroll')\" onmousemove=\"itemMouseMove(event, 'DivGrapgContainerForScrollParent','DivGrapgContainerForssroll')\">" + // 1
                        " <div id='drawGraphrightHeader'></div> " +
                        " <div id='line10' style=''></div> " +
                        " <div id='drawGraphrightCompetitorInfo'> " +
                        "  <div id='DivGraphRightCompetitorInfo1'></div> " +
                        "  <div id='DivGraphRightCompetitorInfo2'></div> " +
                        "  <div id='DivGraphRightCompetitorInfo3'></div> " +
                        "  <div id='DivGraphRightCompetitorInfo4'></div> " +
                         " <div id='DivGraphRightCompetitorInfo5'></div> " +
                        " </div> " + // 1
                        "</div>" + // 2
                        "</div>" +
                          " <div id='ScrollRightUp2' onmousedown=\"onXScrollStart(event, 'DivGrapgContainerForScrollParent', 25, 'DivGrapgContainerForssroll');\" onmouseup='clearIntervals();' onmouseout='clearIntervals();'  style='float:left;min-width:25px; width:25px;  vertical-align:middle; text-align:center;cursor:pointer;'>&nbsp; <img src='"+ imageLink +"Arrow_1.png' style='width:15px;' /> </div>" +
                          "<div style='clear:both;'></div>" +
                         " </div> </div> " + // 3
                         " </div> </div> " +
                        "  </div> " +
                       "  </div> " +
            "</div>";
            resultStr += Scale();
            resultStr += Statics();
            resultStr += AllLegend();
            $("#MainDiv").html(resultStr);
        }
        else
        {
            $("#MainDiv").html('This Race was not Run');
        }
    }
    else
    {
        $("#MainDiv").html('Race is Not Valid');
    }
}


function LoadRiderName(iRaceNo)
{
    var resultStr = "<option style='font-size:14px; font-family:helvetica, verdana, tahoma;' value='" + iRaceNo + "_-1' > -- Choose Rider -- </option>";
    $.each(ttEvent.races[iRaceNo].teams, function (iPostion, tTeamData)
    {
        var isDNF = tTeamData.laps[tTeamData.laps.length - 1].lapTime.split(':')[2] >= 0 ? false : true;
        if (!isDNF)
        {
            resultStr += "<option style='font-size:14px; font-family:helvetica, verdana, tahoma;' value='" + iRaceNo + "_" + iPostion + "'> " + (iPostion + 1) + " " + tTeamData.name + " </option>";
        }
        else
        {
            resultStr += "<option style='font-size:14px; font-family:helvetica, verdana, tahoma;' value='" + iRaceNo + "_" + iPostion + "'> DNF " + tTeamData.name + " </option>";
        }
    });
    return resultStr;
}


function LoadAllLapsofRider(iRaceNo, iRiderNo, iIndex)
{

    var avgTime = diffResult(parseFloat(GetTimetoFloat(ttEvent.races[iRaceNo].teams[iRiderNo].totalTime) / ttEvent.races[iRaceNo].teams[iRiderNo].laps.length));

    var resultStr = "<div style='background-color:#DCD2E6; text-align:center;font-size:14px; font-family:helvetica, verdana, tahoma; width:120px;float:left;color:#53188a;height:35px;line-height:35px;margin:1px;'>" + avgTime + "</div>";
    $.each(ttEvent.races[iRaceNo].teams[iRiderNo].laps, function (iLapNo, ttLapData)
    {
        var fastestLap = parseInt(GetFastestLap(iRaceNo, iRiderNo));
        var isDNF = ttLapData.lapTime.split(':')[2] >= 0 ? false : true;
        if (!isDNF)
        {
            if (fastestLap == iLapNo)
            {
                resultStr += "<div style='background-color:#DCD2E6;font-size:14px; font-family:helvetica, verdana, tahoma; text-align:center; width:90px;float:left;color:#53188a;height:35px;line-height:35px;margin:1px;'><b><u>"
                                        + ttLapData.lapTime + "</u></b></div>";
            }
            else
            {
                resultStr += "<div style='background-color:#DCD2E6;font-size:14px;font-family:helvetica, verdana, tahoma; text-align:center; width:90px;float:left;color:#53188a;height:35px;line-height:35px;margin:1px;'>"
                                + ttLapData.lapTime + "</div>";
            }

        }
    });
    resultStr += "<div style='clear:both;'></div>";
    $("#divRightSelectLapData" + (parseInt(iIndex) + 1)).html(resultStr);
}

function GetFastestLap(iRaceNo, iRiderNo)
{
    var compareAlllap = new Array();
    $.each(ttEvent.races[iRaceNo].teams[iRiderNo].laps, function (ilapNo, ttLapData)
    {
        var isDNF = ttLapData.lapTime.split(':')[2] >= 0 ? false : true;
        if (!isDNF)
        {
            compareAlllap[ilapNo] = [ilapNo, GetTimetoFloat(ttLapData.lapTime)]
        }
    });
    compareAlllap.sort(sortMultiDimensional);
    return compareAlllap[0][0];
}

function CreateLapHeading(maxCount)
{
    var resultStr = "<div style='color:#620E59; text-align:center;margin:1px; width:120px;float:left;font-size:14px; font-family:helvetica, verdana, tahoma;'><b>Average Time</b></div>";
    for (var iIndex = 1; iIndex <= maxCount; iIndex++)
    {
        resultStr += "<div style='color:#620E59; margin:1px; text-align:center; width:90px;float:left;font-size:14px; font-family:helvetica, verdana, tahoma;'><b>" + iIndex + "</b></div>";
    }
    resultStr += "<div style='clear:both;'></div>";
    $("#divRightLap").html(resultStr);
    $("#divRightLap").show();
}



var headingLap = new Array();
var divisionLap = new Array();
function CreateDivGraphHeading(maxCount)
{
    headingLap = new Array();
    divisionLap = new Array();
    headingLap[0] = "<div class='DivLapCompareHeadPos' style='text-align:left;font-size:14px; font-family:helvetica, verdana, tahoma;'><b>Final Pos.</b></div> <div class='DivLapCompareHead' " +
                            " style='text-align:left;width:120px;font-size:14px; font-family:helvetica, verdana, tahoma;'><b>Name</b></div><div style='clear:both;'></div>";
    for (var iIndex = 1; iIndex <= maxCount; iIndex++)
    {
        headingLap[iIndex] = "<div class='DivCycleLapHeading' style='float:left; " +
                             "  color: #620E59;font-size:14px; font-family:helvetica, verdana, tahoma; background-color:#dcd2e6; font-weigth: 800px;text-align:center; line-height:20px; width:{Width_Set}px;'><b>Lap " + iIndex + "</b></div>";
        divisionLap[iIndex] = "<div style='height:8px;background-color:#eae3f0; font-size:14px; font-family:helvetica, verdana, tahoma; float:left;margin-bottom: 0px;padding-bottom: 0px; margin-right:5px; width:{Width_Set}px; '>&nbsp;</div>";
    }

}



var selectedArray = new Array(); 
var dropDowList = 4;
function DisableSeletedRider(ctrl)
{
    var dropDowList = 4;
    var currentSelectItem = $(ctrl)[0].id.split('_')[1];
    var completevalue = $(ctrl).val();
    var currentSelectItemVal = $(ctrl).val().split('_')[1];
    if (currentSelectItemVal >= 0 && currentSelectItemVal != -1)
    {
        ReleaseOption(ctrl);
        for (var iIndex = 0; iIndex <= dropDowList; iIndex++)
        {
            if (iIndex != currentSelectItem)
            {
                selectedArray[currentSelectItem] = completevalue;
                $("#riderSelect_" + iIndex + " option[value =" + completevalue + " ]").attr('disabled', 'disabled');
            }
        }
    }
    else
    {
        ReleaseOption(ctrl);
        selectedArray[currentSelectItem] = null;
    }
}

function ReleaseOption(ctrl)
{
    var currentSelectItem = $(ctrl)[0].id.split('_')[1];
    var valObtained = selectedArray[currentSelectItem];
    if (valObtained != undefined)
    {
        for (var iIndex = 0; iIndex <= dropDowList; iIndex++)
        {
            $("#riderSelect_" + iIndex + " option[value =" + valObtained + " ]").removeAttr('disabled');
        }
    }
}

var isRested = false;

function Reset()
{
    
        var valueList = $("#AllRaceInEvent").val();
        for (var iIndex = 0; iIndex < 5; iIndex++)
        {
            $("#DivGraphLeftCompetitorInfo" + (iIndex + 1)).html('');
            $("#DivGraphLeftCompetitorInfo" + (iIndex + 1)).hide();
            $("#riderSelect_" + iIndex).html(LoadRiderName(valueList));
            $("#DivGraphRightCompetitorInfo" + (iIndex + 1)).html('');
            $("#divRightSelectLapData" + (iIndex + 1)).html('');
            

        }
        $("#divLeftLap").hide();
        $("#divRightLap").hide();
        $("#ScrollLeftUp").hide();
        $("#ScrollRightUp").hide();
        $("#DivGraphHeading").hide();
        $("#drawGraphrightHeader").html('');
        $("#line10").html('');
        $("#line20").hide();
        $("#ScrollConatinerDivAll").hide();
        $("#ScaleDiv").hide();
        $("#ResultStatistics").hide();
        $("#ScaleContainer").hide();
        $("#drawGraphleftCompetitorInfo").hide();
        $("#drawGraphleftHeader").hide();
        $("#line17").hide();

        $("#reset_Anchor").html(" <img src='"+ imageLink +"Reset-click.png' />");
        $("#reset_Anchor").css("cursor", "default");
        competitorArray = new Array();
}

function CheckReset(arraySelectElementValue)
{
    var isBool = false;
    var count = 0;
    for (var iIndex = 0; iIndex < arraySelectElementValue.length; iIndex++)
    {
        if (arraySelectElementValue[iIndex] != 0)
        {
            count = count + 1;
        }
    }
    if (count > 0)
    {
        $("#reset_Anchor").html(" <img src='"+ imageLink +"Reset.png' />");
        $("#reset_Anchor").css("cursor", "pointer");
        isRested = true;
    }
    else
    {
        $("#reset_Anchor").html(" <img src='"+ imageLink +"Reset-click.png' />");
        $("#reset_Anchor").css("cursor", "default");
    }
}

function OnPickRacer(ctrl)
{
    for (var iIndex = 0; iIndex < 5; iIndex++)
    {
        $("#DivGraphLeftCompetitorInfo" + (iIndex + 1)).html('');

        $("#DivGraphRightCompetitorInfo" + (iIndex + 1)).html('');

    }

    DisableSeletedRider(ctrl);

    var arraySelectElementValue = new Array();
    var selectElementValue = ctrl.value.split('_');
    var calculateMaxLength = new Array();
    var maxLapCount = 0;
    for (var iIndex = 0; iIndex < maxRider; iIndex++)
    {
        if ($("#riderSelect_" + iIndex).val().split('_')[1] >= 0 ? true : false)
        {
            var isDNF = ttEvent.races[$("#riderSelect_" + iIndex).val().split('_')[0]].teams[$("#riderSelect_" +
                                         iIndex).val().split('_')[1]].laps[ttEvent.races[$("#riderSelect_" +
                                         iIndex).val().split('_')[0]].teams[$("#riderSelect_" +
                                         iIndex).val().split('_')[1]].laps.length - 1].lapTime.split(':')[2] >= 0 ? false : true;
            var arrayLength = 0;
            if (!isDNF)
            {
                arrayLength = ttEvent.races[$("#riderSelect_" + iIndex).val().split('_')[0]].teams[$("#riderSelect_" +
                                                  iIndex).val().split('_')[1]].laps.length;
            }
            else
            {
                arrayLength = ttEvent.races[$("#riderSelect_" + iIndex).val().split('_')[0]].teams[$("#riderSelect_" +
                                                 iIndex).val().split('_')[1]].laps.length - 1;
            }
            arraySelectElementValue[iIndex] = arrayLength
            if (maxLapCount < arrayLength)
            {
                maxLapCount = arrayLength;
            }
        }
        else
        {
            arraySelectElementValue[iIndex] = 0;
        }
    }
    arraySelectElementValue.sort();
    if (maxLapCount > 0)
    {
        $("#divLeftLap").show();
        CreateLapHeading(maxLapCount);
        $("#ScrollLeftUp").show();
        $("#ScrollRightUp").show();
    }
    else
    {
        $("#divLeftLap").hide();
        $("#divRightLap").hide();
        $("#ScrollLeftUp").hide();
        $("#ScrollRightUp").hide();
    }
    var selectElementid = ctrl.id.split('_')[1];
    var selectElementValue = ctrl.value.split('_');

    if ($("#riderSelect_" + selectElementid).val().split('_')[1] >= 0 ? true : false)
    {
        LoadAllLapsofRider(selectElementValue[0], selectElementValue[1], selectElementid)
    }
    else
    {
        $("#divRightSelectLapData" + (parseInt(selectElementid) + 1)).html('<div style="min-height:30px;margin:2px;">&nbsp;</div>');
    }

    CreateDivGraphHeading(maxLapCount);
    if (selectElementValue[1] >= 0)
    {
        competitorArray[ctrl.id.split('_')[1]] = ttEvent.races[selectElementValue[0]].teams[selectElementValue[1]];
        var compObj = competitorArray[ctrl.id.split('_')[1]];
        compObj.tLaps = new Array();
        var lapLength = ttEvent.races[selectElementValue[0]].teams[selectElementValue[1]].laps.length;
        var isDNF = ttEvent.races[selectElementValue[0]].teams[selectElementValue[1]].laps[lapLength - 1].lapTime.split(':')[2] >= 0 ? false : true;
        if (!isDNF)
        {
            compObj.finalPosition = parseInt(selectElementValue[1]) + 1;
        }
        else
        {
            compObj.finalPosition = "DNF";
        }
        var tLapTime = 0;

        $.each(compObj.laps, function (iIndex)
        {
            var lap = $(this)[0];
            var checkISDNF = lap.lapTime.split(':')[2] >= 0 ? false : true;
            if (!checkISDNF)
            {
                tLapTime += GetTimetoFloat(lap.lapTime);
                compObj.tLaps.push(tLapTime);
            }

        });

    }
    else
    {
        competitorArray[ctrl.id.split('_')[1]] = null;
    }

    $("#divRightSelectLapContainer").css("width", ((maxLapCount * 90) + 160));

    if ((((maxLapCount) * 90) + 160) < 570)
    {
        $("#ScrollLeftUp img").hide();
        $("#ScrollRightUp img").hide();
        $("#divRightSelectLapContainer").removeClass("handGrabCursor");
    }
    else
    {
        $("#ScrollLeftUp img").show();
        $("#ScrollRightUp img").show();
        $("#divRightSelectLapContainer").addClass("handGrabCursor");
    }
    CheckReset(arraySelectElementValue);
    if (CheckMoreThan2Rider(arraySelectElementValue))
    {
        $("#ScaleContainer").show();
        $("#line20").show();
        $("#ScrollConatinerDivAll").show();
        $("#ScaleDiv").show();
        CreateDivGraphHeading(maxLapCount);

        maxSectionScaleWidth = 0;
        maxSectionTime = 0;

        var minSectionwidth = Infinity;
        var maxTime = "";
        var staticsArray = new Array();
        var statticsSideArray = new Array();
        var countIndex = 0;
        $.each(competitorArray, function (iIndex, ttCompetitorData)
        {
            var maxWidth = 0;

            if (ttCompetitorData != undefined)
            {

                var competitorName = ttCompetitorData.name;

                var compHTML = "<div style='clear:both;' id='comp_" + iIndex + "'>";
                var compHTML2 = "<div class='DivLapCompareHeadPos' style=' height:30px; padding-top:7px;font-size:14px; font-family:helvetica, verdana, tahoma; text-align: center; color: "
                                 + Colours[iIndex] + "'> " + ttCompetitorData.finalPosition + "</div>";
                compHTML2 += "<div class='DivLapCompareHead' title='" + competitorName +
                             "' style='height:35px;font-size:14px; font-family:helvetica, verdana, tahoma; padding-top:7px; width:140px; text-align:left; color: "
                             + Colours[iIndex] + "' >" + competitorName + "</div>";
                compHTML2 += "<div style='clear:both;'></div>";
                var maxScale = 0;
                var compHTML3 = "";
                var lapDiffern = 0;
                $.each(ttCompetitorData.tLaps, function (lapIndex)
                {
                    lapDiffern = lapDiffern + 1;
                    var lap = $(this)[0];
                    var title = "";
                    var riderSectionDims = findRiderSectionDims(competitorArray, iIndex, lapIndex);

                    if (riderSectionDims.MaxIndex == iIndex)
                    {
                        title = competitorArray[iIndex].name + " was Leading in Lap " + (lapIndex + 1);
                    }
                    else
                    {
                        title = competitorArray[iIndex].name + " was " + riderSectionDims.interval +
                                " behind " + competitorArray[riderSectionDims.MaxIndex].name + " on  Lap " + (lapIndex + 1);
                    }
                    var sectionWidth = riderSectionDims.sectionWidth;
                    var sectionMargin = riderSectionDims.riderMargin;

                    if (sectionWidth < 50)
                    {
                        sectionWidth = sectionWidth * 1;
                        sectionMargin = sectionMargin * 1;
                    }

                    var topHEading = headingLap[(lapIndex + 1)];
                    headingLap[(lapIndex + 1)] = topHEading.replace("{Width_Set}", (parseInt(sectionWidth) + 65));
                    calculateMaxLength[lapIndex] = sectionWidth + 70;
                    var topdivision = divisionLap[(lapIndex + 1)];
                    divisionLap[(lapIndex + 1)] = topdivision.replace("{Width_Set}", (parseInt(sectionWidth) + 70));

                    staticsArray[countIndex] = [countIndex, (sectionMargin * pixelsPerSecond)];
                    statticsSideArray[countIndex] = [countIndex, riderSectionDims.MinIndex, riderSectionDims.MaxIndex, lapIndex, parseInt(riderSectionDims.currentPostion) + 1];
                    countIndex = countIndex + 1;
                    compHTML += "<div class='DivCycleContainer'  style='background-color:#eae3f0; width: " + (parseInt(sectionWidth) + 60) + "px; '>";

                    compHTML += "<img title='" + title + "'  style='width:40px; heigth:38px; ;margin-left:"
                                + (sectionMargin + 10) + "px;' src='"+ imageLink +"laprider_" + iIndex + "_"
                                 + (parseInt(riderSectionDims.currentPostion) + 1) + ".png'/> ";

                    compHTML += "</div>";
                });


                compHTML += "</div>";

                $("#DivGraphLeftCompetitorInfo" + (iIndex + 1)).html(compHTML2);
                $("#DivGraphRightCompetitorInfo" + (iIndex + 1)).html(compHTML);
                $("#DivGraphRightCompetitorInfo" + (iIndex + 1)).show();
                $("#DivGraphLeftCompetitorInfo" + (iIndex + 1)).show();



            }
            else
            {
                $("#DivGraphLeftCompetitorInfo" + (iIndex + 1)).html('');
                $("#DivGraphLeftCompetitorInfo" + (iIndex + 1)).hide();
                $("#DivGraphRightCompetitorInfo" + (iIndex + 1)).html('');
                $("#DivGraphRightCompetitorInfo" + (iIndex + 1)).hide();
            }
        });

        var headingHTML = "";
        var divisionHTML = "";
        for (var arIndex = 1; arIndex < headingLap.length; arIndex++)
        {
            divisionHTML += divisionLap[arIndex];
            headingHTML += headingLap[arIndex];
        }
        divisionHTML += "<div style='clear:both;'></div>";
        headingHTML += "<div style='clear:both;'></div>";
        $("#line10").html(divisionHTML);
        $("#drawGraphleftHeader").html(headingLap[0]);
        $("#drawGraphrightHeader").html(headingHTML);
        $("#drawGraphrightHeader").show();
        maxWidthAllowScroll = 0;
        for (var kIndex = 0; kIndex < calculateMaxLength.length; kIndex++)
        {
            maxWidthAllowScroll += parseInt(calculateMaxLength[kIndex]);
        }

        $("#DivGrapgContainerForssroll").css("width", ((maxWidthAllowScroll) + 530) + "px");




        var scaleHTML = "";
        if (maxSectionScaleWidth < 50)
        {
            maxSectionScaleWidth = maxSectionScaleWidth * 1;
        }
        $("#mostlapResult").html(maxLapCount);
       
        var fastestData = GetFastestLapAll(competitorArray);
        var convertedTime = diffResult(fastestData.Time);
        $("#fastestlapResult").html(fastestData.Name + " on Lap " + fastestData.Index + " in " + convertedTime);
      
        staticsArray.sort(sortMultiDimensional);
        var biggestGapResult = GetBiggestGap(staticsArray, statticsSideArray, competitorArray);
      
        $("#biggestlapResult").html(biggestGapResult);
       smallestgap = Infinity;
        smallestLapNo = 0;
      isNegative = false;
      
        var smallestGapResult = GetSmallestGap(competitorArray);
        $("#smallestlapResult").html(smallestGapResult);
        var countIndex = 0;
        $.each(competitorArray, function (icompetiorNo, tdata)
        {
            if (tdata != null)
            {
                countIndex = countIndex + 1;
            }
        });



        $("#ResultStatistics").show();
        RemoveWhiteSpace(competitorArray);
    }
    else
    {
        $("#DivGraphHeading").hide();
        $("#drawGraphrightHeader").html('');
        $("#line10").html('');
        $("#line20").hide();
        $("#ScrollConatinerDivAll").hide();
        $("#ScaleDiv").hide();
        $("#ResultStatistics").hide();
        $("#ScaleContainer").hide();
    }
}

function RemoveWhiteSpace(competitorArray)
{
    var maxLapCount = 0;
    var maxLapCountIndex = 0;
    $.each(competitorArray, function (iIndex, ttCompetitorData)
    {
        if (ttCompetitorData != null && ttCompetitorData != undefined)
        {
            if (maxLapCount < ttCompetitorData.laps.length)
            {
                maxLapCount = ttCompetitorData.laps.length;
                maxLapCountIndex = iIndex;
            }
        }
    });
    var MaxChildren = $("#DivGraphRightCompetitorInfo" + (maxLapCountIndex + 1) + " .DivCycleContainer");
    $.each(competitorArray, function (iIndex, ttCompetitorData)
    {
        if (ttCompetitorData != null && ttCompetitorData != undefined)
        {
            if (ttCompetitorData.laps.length < maxLapCount)
            {
                var resultStr = "";
                var difference = maxLapCount - ttCompetitorData.laps.length;
                for (var jIndex = 1; jIndex <= difference; jIndex++)
                {
                    var width = $(MaxChildren[(ttCompetitorData.laps.length + jIndex) - 1]).width();
                    resultStr += "<div class='DivCycleContainer' style='background-color:#eae3f0;height:31px;width:" + width + "px;'>&nbsp;</div>";
                }
                $("#comp_" + iIndex).append(resultStr);
            }
        }
    });


}


var smallestgap = Infinity;
var smallestLapNo = 0;
var isNegative = false;
var riderName = new Array();
function GetSmallestGap(competitorArray)
{
    $.each(competitorArray, function (iIndex, ttcompetitorData)
    {
        if (ttcompetitorData != null && ttcompetitorData != undefined)
        {
            $.each(ttcompetitorData.tLaps, function (ilapNo, lapData)
            {
                GetDifference(competitorArray, iIndex, ilapNo, lapData);
            });
        }
    });
    var test = smallestgap;
    var test2 = smallestLapNo;
    var test3 = riderName;

    var returnResult = diffResult(smallestgap) + " on Lap " + (smallestLapNo + 1) +
                       " between " + competitorArray[riderName[0]].name + " and " + competitorArray[riderName[1]].name;
    return returnResult;
}


function GetDifference(competitorArray, iIndex, lapIndex, lapTime)
{
    $.each(competitorArray, function (jIndex, ttcompData)
    {
        if (ttcompData != null && jIndex != iIndex)
        {
            var lap = ttcompData.tLaps[lapIndex]
            if (lap != undefined)
            {
                var difference = lapTime - lap;
                if (difference < 0)
                {
                    difference = difference * (-1);
                    isNegative = true;
                }
                if (difference < smallestgap)
                {
                    smallestgap = difference;
                    smallestLapNo = lapIndex;
                    if (isNegative)
                    { riderName = [jIndex, iIndex]; }
                    else
                    { riderName = [iIndex, jIndex]; }
                    isNegative = false;
                }
            }
        }
    });
}


function GetBiggestGap(staticsArray, statticsSideArray, competitorArray)
{
    var bigestIndex = staticsArray[staticsArray.length - 1];
    var biggestCompetitor = statticsSideArray[bigestIndex[0]];
    var lagcompetitorName = competitorArray[biggestCompetitor[1]].name;
    var leadingcompetitorName = competitorArray[biggestCompetitor[2]].name;
    var returnResult = diffResult(bigestIndex[1]) + " on Lap " + (parseInt(biggestCompetitor[3]) + 1) + " between " + leadingcompetitorName + " and " + lagcompetitorName;
    return returnResult;
}

function GetFastestLapAll(competitorArray)
{
    var fastestLapComatiner = new Array();
    var fastestLapInt = Infinity;
    var fastestLapRider = "";
    var fastestLapIndex = 0;
    $.each(competitorArray, function (icompetitorNo, ttcompetitorData)
    {
        if (ttcompetitorData != null && ttcompetitorData != undefined)
        {
            var ttCompData = GetFastestLapByCompetitor(ttcompetitorData);
            if (fastestLapInt > ttCompData[0][1])
            {
                fastestLapInt = ttCompData[0][1];
                fastestLapIndex = parseInt(ttCompData[0][0]) + 1;
                fastestLapRider = ttcompetitorData.laps[ttCompData[0][0]].competitorName;
            }
        }
    });
    return { "Name": fastestLapRider, "Time": fastestLapInt, "Index": fastestLapIndex };
}


function GetFastestLapByCompetitor(ttcompetitorData)
{
    var currentCompetitorLap = new Array();
    $.each(ttcompetitorData.laps, function (ilapno, ttlapData)
    {

        var isDNF = ttlapData.lapTime.split(':')[2] >= 0 ? true : false;
        if (isDNF)
        {
            currentCompetitorLap[ilapno] = [ilapno, GetTimetoFloat(ttlapData.lapTime)];
        }
    });
    currentCompetitorLap.sort(sortMultiDimensional);
    return currentCompetitorLap;
}

function IntToTime(intTime)
{
    var resultStr = "";
    var hours = Math.floor(intTime / (60 * 60));
    if (hours > 0)
    {
        resultStr += hours + " hrs ";
        intTime -= hours * (60) * (60);
    }

    var minutes = Math.floor(intTime / (60));
    if (minutes > 0)
    {
        if (minutes > 1)
        {
            resultStr += minutes + " minutes ";
        }
        else
        {
            resultStr += minutes + " minute ";
        }
        intTime -= minutes * (60);
    }

    var secs = Math.floor(intTime);
    if (secs > 0)
    {
        if (minutes > 1)
        {
            resultStr += secs + " secs ";
        }
        else
        {
            resultStr += secs + " sec ";
        }
    }
    return resultStr;

}


var isMultiply = false;
function findRiderSectionDims(competitorArray, cIndex, lapIndex)
{
    var rankArray = new Array();
    var maxLap = 0;
    var minLap = Infinity;
    var maxIndex = 0;
    var minIndex = 0;
    $.each(competitorArray, function (index, comp)
    {
        if (comp != undefined)
        {
            var lap = comp.tLaps[lapIndex];
            if (lap != undefined)
            {
                rankArray[index] = [index, lap];
            }
            else
            {
                rankArray[index] = [index, "999999999999"];
            }
            if (lap > maxLap)
            {
                maxLap = lap;
                minIndex = index;
            }
            if (minLap > lap)
            {
                minLap = lap;
                maxIndex = index
            }
        }
        else
        {
            rankArray[index] = [index, "999999999999"];
        }

    });
    rankArray.sort(sortMultiDimensional);
    var currentPostion;
    for (var iIndex = 0; iIndex < rankArray.length; iIndex++)
    {
        if (rankArray[iIndex][0] == cIndex)
        {
            currentPostion = iIndex;
        }
    }

    var selfComp = competitorArray[cIndex];
    var lap = selfComp.tLaps[lapIndex];
    var minGap = (minLap - lap) < 0 ? (minLap - lap) * (-1) : (minLap - lap);
    var gap = maxLap - lap;
    margin = Math.ceil(gap / pixelsPerSecond);
    sectionWidth = parseFloat((maxLap - minLap) / pixelsPerSecond);
    if (maxSectionScaleWidth < ((maxLap - minLap) / pixelsPerSecond))
    {
        maxSectionScaleWidth = ((maxLap - minLap) / pixelsPerSecond);
    }
    if (maxSectionTime < minGap)
    {
        maxSectionTime = minGap;
    }
//    if (isMultiply)
//    {
//        margin = margin * (2.5);
//        sectionWidth = sectionWidth * (2.5);
//    }

//    else
//    {
//        if ((minGap < 15))
//        {
//            margin = margin * (2.5);
//            sectionWidth = sectionWidth * (2.5);
//            isMultiply = true;
//        }
//    }

    return { "riderMargin": margin,"sectionWidth": sectionWidth, "interval": diffResult(minGap), "MaxIndex": maxIndex, "currentPostion": currentPostion, "MinIndex": minIndex };
}





function CheckMoreThan2Rider(arraySelectElementValue)
{
    var isBool = false;
    var count = 0;
    for (var iIndex = 0; iIndex < arraySelectElementValue.length; iIndex++)
    {
        if (arraySelectElementValue[iIndex] != 0)
        {
            count = count + 1;
        }
    }

    if (count >= 2)
    {
        $("#drawGraphleftHeader").show();
        $("#drawGraphleftCompetitorInfo").show();
        $("#line17").show();

        return isBool = true;
    }
    else
    {
        $("#drawGraphleftHeader").hide();
        $("#drawGraphleftCompetitorInfo").hide();
        $("#line17").hide();
        return isBool = false;
    }

}




function GetTimetoFloat(time)
{
    var timeIndex = time.split(':');
    var timeFloat = parseFloat(timeIndex[2]) + parseFloat(timeIndex[1] * 60) + parseFloat(timeIndex[0] * (60 * 60));
    return timeFloat;
}

function AddFloatTime(time1, time2)
{
    return time1 + time2;
}


//---------------------------//
var VERTICAL = 1;
var HORIZONTAL = 2;

var HSCROLLBUTTONWIDTH = 23;    //  19+margin of 4px
var HSCROLLBUTTONHEIGHT = 77;

var VSCROLLBUTTONWIDTH = 77;
var VSCROLLBUTTONHEIGHT = 23;


var RIGHTMOUSEBUTTON = 2;


var mousedownPositions = { x: 0, y: 0 };
var dragObject = null;
var mouseDown = false;
var LEFTMOUSEBUTTON = 1;
var RETURNKEY = 13;
var intervalID = null;

function $button(ev) { return ev.button || ev.which; }
function $target(ev) { return ev.target || ev.srcElement; }
function $event(ev) { return ev = ev || window.event; }


function stopSelection(ev)
{

    ev = $event(ev);
    var element = document.body;
    element.onselectstart = function () // ie
    {
        ev = $event(ev);
        var target = $target(ev);



        if (target.type != "text" && target.type != "select" && target.type != "input" && target.type != "select-one")
        {
            return false;
        }
    }
    element.onmousedown = function (ev) // mozilla
    {
        ev = $event(ev);
        var target = $target(ev);

        if (target.type != "text" && target.type != "select" && target.type != "input" && target.type != "select-one")
            return false;
    }
}



function clearIntervals()
{
   
    window.clearInterval(intervalID);
    intervalID = null;
    mouseDown = false;
    $("#divRightSelectLapContainer").addClass("handGrabCursor").removeClass("handGrabCursorHold");
    $("#DivGrapgContainerForssroll").addClass("handGrabCursor").removeClass("handGrabCursorHold");
}

function onXScrollStart(eventObject, scrollBox, direction, tabContainer)
{
  
    eventObject = $event(eventObject);

    var mouseButton = $button(eventObject)

    if (mouseButton == LEFTMOUSEBUTTON)
    {
        mouseDown = true;
        onScroll(scrollBox, direction, HORIZONTAL, tabContainer);
    }
}

function onYScrollStart(eventObject, scrollBox, direction, tabContainer)
{
    eventObject = $event(eventObject);

    var mouseButton = eventObject.button || eventObject.which;

    if (mouseButton == LEFTMOUSEBUTTON)
    {
        mouseDown = true;
        onScroll(scrollBox, direction, VERTICAL, tabContainer);
    }
}

function onScroll(scrollBox, direction, scrollType, tabContainer)
{
    if (mouseDown)
    {
        var scrollBoxObj = $("#" + scrollBox);

        if (scrollType == VERTICAL)
        {
            if (direction > 0)
            {
                var tabContainerObj = $("#" + tabContainer);
                var lastTab = tabContainerObj.lastChild;
                var bottom = lastTab.offsetTop + lastTab.offsetHeight;

                var scrollBoxObj = $("#" + scrollBox);
                var scrollBoxScrollTop = scrollBoxObj.scrollTop;
                var totalHeight = scrollBoxScrollTop + scrollBoxObj.offsetHeight;

//                if (totalHeight > bottom)
//                {
//                   // return false;
//                }
            }

            scrollBoxObj.scrollTop += direction;
        }
        else
        {
            if (direction > 0)
            {
                var tabContainerObj = $("#" + tabContainer);


                var right = $("#" + tabContainer).width();

                var scrollBoxObj = $("#" + scrollBox);
                var scrollBoxScrollLeft = scrollBoxObj[0].scrollLeft;
                var totalWidth = scrollBoxScrollLeft + scrollBoxObj[0].offsetWidth;

//                if (totalWidth > right)
//                {
//                  //  return false;
//                }
            }

            scrollBoxObj[0].scrollLeft += direction;
        }


        if (intervalID == null)
        {
            intervalID = window.setInterval("onScroll('" + scrollBox + "', " + direction + ", " + scrollType + ", '" + tabContainer + "')", 150);
        }
    }
    else
    {
        clearIntervals();
    }
}


function getLastChild(obj)
{
    var elem = obj.lastChild;
    while (elem.nodeType != 1)
    {
        elem = elem.previousSibling;
    }
    return elem;
}

function scrollWheelVertical(scrollBox, ev, tabContainer)
{
    scrollGallery(scrollBox, ev, VERTICAL, tabContainer);
}

function scrollWheelHorizontal(scrollBox, ev, tabContainer)
{
    scrollGallery(scrollBox, ev, HORIZONTAL, tabContainer);
}

function scrollGallery(scrollBox, ev, direction, tabContainer)
{
    var scrollBoxObj = document.getElementById(scrollBox);
    var delta = 0;

    ev = $event(ev);

    if (ev.wheelDelta)
    {
        delta = ev.wheelDelta / 120;

        if (window.opera)
            delta = -delta;

    }
    else if (ev.detail)
    {
        delta = -ev.detail / 3;
    }

    if (delta)
    {


        if (direction == HORIZONTAL)
        {
            if (delta < 0)
            {
                var tabContainerObj = $(tabContainer);
                var lastTab = tabContainerObj.lastChild;
                var right = lastTab.offsetLeft + lastTab.offsetWidth;

                var scrollBoxObj = $("#" + scrollBox);
                var scrollBoxScrollLeft = scrollBoxObj.scrollLeft;
                var totalWidth = scrollBoxScrollLeft + scrollBoxObj.offsetWidth;

                if (totalWidth > right)
                    return false;
            }

            scrollBoxObj.scrollLeft -= 20 * delta;
        }
        else
        {
            if (delta < 0)
            {
                var tabContainerObj = $(tabContainer);
                var lastTab = tabContainerObj.lastChild;
                var bottom = lastTab.offsetTop + lastTab.offsetHeight;

                var scrollBoxObj = $("#" + scrollBox);
                var scrollBoxScrollTop = scrollBoxObj.scrollTop;
                var totalHeight = scrollBoxScrollTop + scrollBoxObj.offsetHeight;

                if (totalHeight > bottom)
                    return false;
            }

            scrollBoxObj.scrollTop -= 20 * delta;
        }

    }
}

function itemMouseDown(ev, scrollBox, tabContainer, dir)
{
    $("#" + tabContainer).addClass("handGrabCursorHold").removeClass("handGrabCursor");
    ev = $event(ev);
    var target = $("#" + scrollBox);
    mousedownPositions = getMouseXY(ev);
    oldMouseXPos = mousedownPositions.x;

    var mouseButton = ev.button || ev.which;
    if (mouseButton == LEFTMOUSEBUTTON)
    {
        target.css("cursor", "w-resize");

        mouseDown = true;
    }
    stopSelection(ev);
}

var oldMouseXPos = 0;

function itemMouseMove(ev, scrollBox, tabContainer)
{
    ev = $event(ev);
    var scrollDir = 0;
    var mouseButton = ev.button || ev.which;
    var mousePos = getMouseXY(ev);

    if (mouseDown)
    {
        scrollDir = (mousePos.x - oldMouseXPos);
        
        onXScrollStart(ev, scrollBox, -scrollDir, tabContainer);
        oldMouseXPos = mousePos.x;
       
    }
    stopSelection(ev);
   
}

function itemMouseUp(ev, scrollBox, tabContainer)
{
    $("#" + tabContainer).addClass("handGrabCursor").removeClass("handGrabCursorHold");
    mouseDown = false;
    clearIntervals();
    stopSelection(ev);
}

function getMouseXY(eventObject)
{
    if (eventObject.pageX || eventObject.pageY)
    {
        return { x: eventObject.pageX, y: eventObject.pageY };
    }
    else
    {
        return { x: eventObject.clientX + document.body.scrollLeft - document.body.clientLeft,
            y: eventObject.clientY + document.body.scrollTop - document.body.clientTop
        };
    }
}
