$(document).ready(function() {
    var an = new Animation();
    $('#btnPlay').click(function() {
        an.Play();
        return false;
    });
    $('#btnPause').click(function() {
        an.Pause();
        return false;
    });
    $('#btnStop').click(function() {
        an.Clear();
        return false;
    });

    $('#teamShow').click(function() {
        $('.teams').toggle();
        return false;
    });

    $("img[src$='.png']", $(".controlBar")).ifixpng();
});

Animation = function() {
    var m_startTime;
    var m_endTime;
    var m_points;
    var m_teams;
    var m_curTime;
    var m_baseMapPanelId = 'map_panel';
    var m_xml;
    var m_speed = 10000;
    var that = this;
    var colors = new Array(14)
    var currentPicker = null;
    init();

    this.Play = function() {
        $("#" + m_baseMapPanelId).everyTime(10, "Teams", function() {
            m_curTime += m_speed;
            if (m_curTime > m_endTime) {
                that.Clear();
            }
            drawAllTeams(m_curTime);
        });
    }

    this.Pause = function() {
        $("#" + m_baseMapPanelId).stopTime("Teams");
    }

    this.Clear = function() {
        $("#" + m_baseMapPanelId).stopTime("Teams").find('.absDiv:not(.control)').remove();
        $("#" + m_baseMapPanelId).find('.teams').empty();
        initFunctions();
        setSliderValue(m_startTime);
    }

    function init() {
        colors[0] = "0"
        colors[1] = "1"
        colors[2] = "2"
        colors[3] = "3"
        colors[4] = "4"
        colors[5] = "5"
        colors[5] = "6"
        colors[6] = "7"
        colors[7] = "8"
        colors[8] = "9"
        colors[9] = "a"
        colors[10] = "b"
        colors[11] = "c"
        colors[12] = "d"
        colors[13] = "e"
        colors[14] = "f"
        $.ajax({
            type: "GET",
            url: "Moving.xml",
            dataType: "xml",
            success: function(xml) {
                m_xml = xml;
                initFunctions();
            }
        });
    }

    function drawAllTeams(_curTime) {
        setSliderValue(_curTime);
        for (var i = 0; i < m_teams.length; i++) {
            drawTeam(m_teams[i], _curTime);
        }
    }

    function initFunctions() {
        initSliders();
        m_points = new Number();
        initPoints();
        m_teams = new Array();
        initTeams();
        setImageSizes();
    }

    function drawTeam(team, _curTime) {

        if (_curTime > team.PointArray[team.GetCurrentItem()].Come) {
            if (team.PointArray.length - 1 > team.GetCurrentItem()) {
                if (_curTime >= team.PointArray[team.GetCurrentItem()].Leave) {
                    team.SetCurrentItem(team.GetCurrentItem() + 1, m_points);
                    drawRoute(team);
                    team.ClearK();
                }
                else {
                    return;
                }
            }
            else {
                return
            }
        }
        else if (_curTime < team.PointArray[team.GetCurrentItem() - 1].Leave) {
            if (team.PointArray[team.GetCurrentItem() - 1].Come && _curTime < team.PointArray[team.GetCurrentItem() - 1].Come) {
                if (team.GetCurrentItem() > 1) {
                    team.SetCurrentItem(team.GetCurrentItem() - 1, m_points);
                    drawRoute(team);
                    team.ClearK();
                }
                else {
                    return
                }
            }
            else {
                return
            }
        }

        var resSec = _curTime - team.PointArray[team.GetCurrentItem() - 1].Leave;

        var curPoint = m_points[team.PointArray[team.GetCurrentItem() - 1].PointId];

        var nextPoint = m_points[team.PointArray[team.GetCurrentItem()].PointId];
        if (nextPoint != null) {
            var xTemp = curPoint.X + Math.round(resSec * team.GetKx(nextPoint.X, curPoint.X));
            var yTemp = curPoint.Y + Math.round(resSec * team.GetKy(nextPoint.Y, curPoint.Y));

            team.GraphicPanel.clear();


            team.GraphicPanel.setFont("Times New Roman", "16px", Font.BOLD);
            team.GraphicPanel.drawString(team.Id, xTemp /*+ Math.floor(team.Id / 10)*/ - 20, yTemp /*+ Math.floor(team.Id / 10)*/ - 20);
            team.GraphicPanel.paint();



        }

    }

    function drawRoute(team) {
//        team.TrackPanel.clear();
//        var xArray = $.makeArray(team.GetXArray());
//        var yArray = $.makeArray(team.GetYArray());
//        if (xArray.length > 0) {
//            team.TrackPanel.drawPolyline(team.GetXArray(), team.GetYArray());
//        }

//        team.TrackPanel.drawLine(curPoint.X, curPoint.Y, xTemp, yTemp);
//        team.TrackPanel.paint();
    }

    function initSliders() {
        m_startTime = getMSFromDate($(m_xml).find('time > start').text());
        m_endTime = getMSFromDate($(m_xml).find('time > end').text());
        $("#slider").slider({
            value: 0,
            min: m_startTime,
            max: m_endTime,
            step: 1,
            slide: function(event, ui) {
                /*that.Pause();*/
                m_curTime = ui.value;
                recalculateCurrentItem(ui.value);
                drawAllTeams(ui.value);
            }
        });
        m_curTime = m_startTime;
        setSliderValue($("#slider").slider("value"));

        $("#speedSlider").slider({
            value: m_speed,
            min: 1000,
            max: 30000,
            step: 1,
            slide: function(event, ui) {
                m_speed = ui.value;
            }
        });
    }

    function recalculateCurrentItem(_curTime) {
        for (var i = 0; i < m_teams.length; i++) {
            for (var j = 0; j < m_teams[i].PointArray.length; j++) {
                if (m_teams[i].PointArray[j].Come > _curTime) {
                    m_teams[i].SetCurrentItem(j, m_points);
                    m_teams[i].ClearK();
                    break;
                }
            }
        }
    }

    function setSliderValue(time) {

        $('#slider').slider('option', 'value', time);
        $('.amount').html(getDatefromMS(time));

    }

    function initPoints() {
        $(m_xml).find('map > points > point').each(function() {
            var curItem = $(this);
            m_points[curItem.attr('id')] = new Point(parseInt(curItem.find('x').text()), parseInt(curItem.find('y').text()));
        });
    }

    function initTeams() {
        var basePanel = $('#' + m_baseMapPanelId);
        $(m_xml).find('teams > team').each(function() {
            var curItem = $(this);
            var teamId = parseInt(curItem.attr('id'));
            var team = new Team(teamId, basePanel, "#1F1F1F"/*getRandomColor()*/);
            team.Name = curItem.attr('name');
            curItem.find('point').each(function() {
                var pointItem = $(this);
                var pointTime = new PointTime(pointItem.attr('id'));
                pointTime.Come = getMSFromDate(pointItem.find('come').text());
                pointTime.Leave = getMSFromDate(pointItem.find('leave').text());
                team.PointArray.push(pointTime);

            });
            team.SetCurrentItem(1, m_points);
            m_teams.push(team)
        });
        initTeamControl();
    }

    function initTeamControl() {
        var teamDiv = $('.teams');
        for (var i = 0; i < m_teams.length; i++) {
            var pEl = $(document.createElement('p'));
            pEl.attr('id', 'teamP_' + i);
            var curEl = m_teams[i];
            pEl.html("<a href='#' class='element teamColor' style='color:" + curEl.GetColor() + "'>" + curEl.Id + "</a><span class='element'>" + curEl.Name + "</span>"); //<a class='run' href='#'><img id='img_track_" + curEl.Id + "' alt='track' src='theme/images/run_dis.png' /></a>
            teamDiv.append(pEl);
        }
        $("img[src$='.png']", teamDiv).ifixpng();
        $('.teamColor', teamDiv).each(function() {
            var aEl = $(this);
            aEl.ColorPicker({
                color: aEl.css('color'),
                onShow: function(colpkr) {
                    $(colpkr).show(500);
                    return false;
                },
                onHide: function(colpkr) {
                    $(colpkr).hide(500);
                    return false;
                },
                onChange: function(hsb, hex, rgb) {
                    currentPicker.css('color', '#' + hex);
                    m_teams[parseInt(currentPicker.parent('p').attr('id').replace('teamP_', ''))].SetColor('#' + hex);
                }
            });
        });
        $('.teamColor', teamDiv).click(function() {
            currentPicker = $(this);
        });

        $('.run', teamDiv).click(function() {
            var curEl = $('img', this);
            var divElId = '#divTrack_' + curEl.attr('id').replace('img_track_', '');
            if (curEl.hasClass('showTrack')) {
                curEl.removeClass('showTrack').attr('src', 'theme/images/run_dis.png').ifixpng();
                $(divElId).hide();
            }
            else {
                curEl.addClass('showTrack').attr('src', 'theme/images/run.png').ifixpng();
                $(divElId).show();
            }
            return false;
        });
    }
    function setImageSizes() {
        $('#' + m_baseMapPanelId + ', .absDiv').css('height', parseInt($(m_xml).find('map > image > height').text())).css('width', parseInt($(m_xml).find('map > image > width').text()));

    }

    function getRandomColor() {
        var digit = new Array(5)
        var color = ""
        for (i = 0; i < 6; i++) {
            digit[i] = colors[Math.round(Math.random() * 14)]
            color = color + digit[i]
        }
        return '#' + color;
    }

    function getMSFromDate(str) {
        if ($.trim(str) == '')
            return '';
        var timesplit = str.split(':');
        return timesplit[2] * 1000 + timesplit[1] * 60000 + timesplit[0] * 3600000;
    }


    function getDatefromMS(ms) {
        var hour = Math.floor(ms / 3600000);
        var min = Math.floor((ms - hour * 3600000) / 60000);
        var sec = Math.floor((ms - hour * 3600000 - min * 60000) / 1000);
        var hourStr = hour.toString();
        if (hourStr.length == 1)
            hourStr = "0" + hourStr;
        var minStr = min.toString();
        if (minStr.length == 1)
            minStr = "0" + minStr;
        var secStr = sec.toString();
        if (secStr.length == 1)
            secStr = "0" + secStr;
        return hourStr + ":" + minStr + ":" + secStr;
    }
};

//Team
Team = function(teamId, basePanel, colour) {
    this.PointArray = new Array();
    this.Id = teamId;
    this.Name;
    var m_currentItem;
    var xArray;
    var yArray;
    this.Kx = null;
    this.Ky = null;

    this.GraphicPanel;
    this.TrackPanel;
    var that = this;
    var color = colour;
    init();

    function init() {
        setGraphicPanel();
    }

    this.GetXArray = function() {
        return xArray;
    }

    this.GetYArray = function() {
        return yArray;
    }

    this.SetCurrentItem = function(newValue, points) {
        if (m_currentItem != newValue) {
            m_currentItem = newValue;
            xArray = new Array();
            yArray = new Array();
            for (var i = 0; i < newValue; i++) {
                var point = points[that.PointArray[i].PointId];
                xArray.push(point.X);
                yArray.push(point.Y);
            }
        }
    }
    this.GetCurrentItem = function() {
        return m_currentItem;
    }

    this.GetKx = function(firstX, secondX) {
        if (that.Kx == null) {
            that.Kx = (firstX - secondX) / (that.PointArray[that.GetCurrentItem()].Come - that.PointArray[that.GetCurrentItem() - 1].Leave);
        }
        return that.Kx;
    }

    this.GetKy = function(firstY, secondY) {
        if (that.Ky == null) {
            that.Ky = (firstY - secondY) / (that.PointArray[that.GetCurrentItem()].Come - that.PointArray[that.GetCurrentItem() - 1].Leave);
        }
        return that.Ky;
    }

    this.ClearK = function() {
        that.Kx = null;
        that.Ky = null;
    }

    function setGraphicPanel() {
        var divEl = $(document.createElement('div'));
        divEl.addClass('absDiv');
        divEl.css('z-index', 1000 + that.Id);
        divEl.attr('id', 'team_' + that.Id);
        basePanel.append(divEl);
        that.GraphicPanel = new jsGraphics(divEl.attr('id'));
        that.GraphicPanel.setColor(colour);

        divEl = $(document.createElement('div'));
        divEl.addClass('absDiv');
        divEl.css('z-index', that.Id);
        divEl.css('display', 'none');
        divEl.attr('id', 'divTrack_' + that.Id);
        basePanel.append(divEl);
        that.TrackPanel = new jsGraphics(divEl.attr('id'));
        that.TrackPanel.setColor(colour);
        that.TrackPanel.setStroke(2);
    }

    this.SetColor = function(colour) {
        that.GraphicPanel.setColor(colour);
        that.TrackPanel.setColor(colour);
        color = colour;
    }

    this.GetColor = function() {
        return color;
    }
};

//PointTime
PointTime = function(id) {
    this.PointId = id;
    this.Come;
    this.Leave;
};

//Point
Point = function(x, y) {
    this.X = x;
    this.Y = y;
}
