$(document).ready(function () {
    //PointerEventsPolyfill.initialize({});
    //FastClick.attach(document.body);

//    var debug = new createDebug();

    var grid = new grid(20, 15);

    /* affichage de la grille */
    grid.displayGrid('#box-wrapper');
    grid.displayStart();



    $("#recommencer").click(function(e){
        e.preventDefault();
        if (!animState) grid.reset();
        //$("#continuer").hide();
        $("#imprimer").hide();
        $("#tester").show();
    });

    $("#tester").click(function(e){
       e.preventDefault();
//       if (!animState) launchAnimation(9);
       if (!animState)grid.check();
    });

    $(".pole").click(function (e) {
        e.preventDefault();
    });

    //var elId = 1;//par defaut un poteau
    var elId = 1;//sous-station

    var pathId = 1;//on initialise le path a 1

    var animState = 0;//pour savoir si l'animation est en cours ou pas

    //launchAnimation(5);

    //box events
    $(".box.selectable").click(function (e) {
        var aId = e.target.id.split("-");
        var boxColumn = aId[1];
        var boxLine = aId[2];

        grid.process(boxColumn, boxLine, elId);

//        debug.show('#pan1', '<p>colonne : ' + boxColumn + ' - ligne : ' + boxLine + '</p>');
//        debug.show('#pan3-1', grid.showDebugStateMatrix());
//        debug.show('#pan3-2', grid.showDebugElMatrix('el'));
//        debug.show('#pan3-3', grid.showDebugElMatrix('pathId'));
    });

    $('.box.selectable').mouseover(function () {
        $(this).addClass('hover');
    });

    $('.box.selectable').mouseout(function () {
        $(this).removeClass('hover');
    });

    // el panel selector
    $("#panel .selector").click(function () {
        if ($(this).parent().hasClass('off')) {
            switch ($(this).attr('id')) {
                case 'panel-pole-selector':
                    elId = 1;
                    break;
                case 'panel-ss1-selector':
                    elId = 2;
                    break;
                case 'panel-ss2-selector':
                    elId = 3;
                    break;
                case 'panel-at-selector':
                    elId = 4;
                    break;
            }
            $('#panel').children().removeClass('on').addClass('off');
            $(this).parent().removeClass('off').addClass('on');
        }
    });

    $("#dialog-pole-help").dialog({
        autoOpen: false,
        title: '<span id="picto-pole" class="picto"></span>Pylone',
        width: 500,
        modal: true,
        create: function(event, ui) {
            var widget = $(this).dialog("widget");
            $(".ui-dialog-titlebar-close span", widget).remove();

        }
    });

    $("#dialog-ss1-help").dialog({
        autoOpen: false,
        title: '<span id="picto-ss1" class="picto"></span>Sous station 400 000 V – 90 000 V',
        width: 500,
        modal: true,
        create: function(event, ui) {
            var widget = $(this).dialog("widget");
            $(".ui-dialog-titlebar-close span", widget).remove();

        }
    });

    $("#dialog-ss2-help").dialog({
        autoOpen: false,
        title: '<span id="picto-ss2" class="picto"></span>Sous station 90 000 V – 25 000 V',
        width: 500,
        modal: true,
        create: function(event, ui) {
            var widget = $(this).dialog("widget");
            $(".ui-dialog-titlebar-close span", widget).remove();

        }
    });

    $("#dialog-at-help").dialog({
        autoOpen: false,
        title: '<span id="picto-at" class="picto"></span>Autotransformateur',
        width: 500,
        modal: true,
        create: function(event, ui) {
            var widget = $(this).dialog("widget");
            $(".ui-dialog-titlebar-close span", widget).remove();

        }
    });

    $("#panel .help").click(function () {
        switch ($(this).attr('id')) {
            case 'panel-pole-help':
                $("#dialog-pole-help").dialog("open");
                break;
            case 'panel-ss1-help':
                $("#dialog-ss1-help").dialog("open");
                break;
            case 'panel-ss2-help':
                $("#dialog-ss2-help").dialog("open");
                break;
            case 'panel-at-help':
                $("#dialog-at-help").dialog("open");
                break;
        }
    });

    function grid(nbCol, nbLine) {
        // point de depart
        this.startPoint = [11, 12];
        // point d'arrivee
        this.endPointA = [18,1];
        this.endPointB = [6,1];
        // tableau de coordonnees non selectable
        this.aCoordsNotAllowed = [[4, 1], [3, 2], [2, 3], [1, 4], [1, 5], [2, 6], [3, 7], [4, 8], [5, 9], [6, 10], [7, 11], [8, 12], [9, 13], [10, 14], [11, 13], [11, 14], [11, 15], [12, 14], [13, 13], [14, 12], [15, 11], [16, 10], [17, 9], [18, 8], [19, 7], [20, 6]];

        this.xOrig = -175;
        this.yOrig = 414;

        // tableau de chemin
        this.path = [];

        //state : 1 : possible de rajouter un element, 0 : impossible . Par defaut toutes les cases sont possibles.
        this.gridElMatrix = initGrid(nbCol, nbLine);

        this.process = function (col, line, el) {
            col = +col;
            line = +line;
            var indexX = col - 1;
            var indexY = line - 1;

            //nouvel objet
            if (this.gridElMatrix[indexX][indexY].el == 0) {
                if (this.allow(col, line, el)) {
                    var currentPathId = this.gridElMatrix[indexX][indexY].state;
                    this.path[currentPathId] = (typeof this.path[currentPathId] != 'undefined' && this.path[currentPathId] instanceof Array) ? this.path[currentPathId] : [];
                    this.displayEl(col, line, el, currentPathId);
                    if (el == 4) {
                        this.gridElMatrix[indexX][indexY].el = el;
                        this.gridElMatrix[indexX][indexY].state = 0;
                    } else {
                        this.updateState('add', col, line, el, currentPathId);
                    }
                    if (el == 1) {
                        var currentEl = [col, line];
                        this.path[currentPathId].push(currentEl);
                        this.gridElMatrix[indexX][indexY].pathId = currentPathId;
                    }
                }
            }
            // effacement d'un objet
            else {
                switch (this.gridElMatrix[indexX][indexY].el) {
                    //auto-transformateur
                    case 4:

                            $('#at-' + col + '-' + line).remove();
                            this.gridElMatrix[indexX][indexY].el = 0;
                            this.gridElMatrix[indexX][indexY].type = '';

                        break;
                        //ss2
                    case 3:

                            var isConnected = false;
                            var previousCol = col;
                            var previousLine = line;
                            switch (this.gridElMatrix[indexX][indexY].type) {
                                case 'ss2-up':
                                    previousLine = line + 1;
                                    break;
                                case 'ss2-down':
                                    previousLine = line - 1;
                                    break;
                                case 'ss2-right':
                                    previousCol = col - 1;
                                    break;
                                case 'ss2-left':
                                    previousCol = col + 1;
                                    break;
                                default:
                                    isConnected = true;
                                    break;
                            }

                            if (!isConnected) {
                                $('#ss2-' + col + '-' + line).remove();
                                this.updateState('remove', col, line, 3);
                                this.gridElMatrix[indexX][indexY].el = 0;
                                this.gridElMatrix[indexX][indexY].type = '';
                                var previousPathId = this.gridElMatrix[previousCol - 1][previousLine - 1].pathId;
                                this.replacePreviousPole(previousPathId);
                                this.updateState('add', previousCol, previousLine, 1, previousPathId);
                            }

                        break;
                        // sous1
                    case 2:

                            var isConnected = false;
                            var previousCol = col;
                            var previousLine = line;
                            switch (this.gridElMatrix[indexX][indexY].type) {
                                case 'ss1-up':
                                    previousLine = line + 1;
                                    break;
                                case 'ss1-down':
                                    previousLine = line - 1;
                                    break;
                                case 'ss1-right':
                                    previousCol = col - 1;
                                    break;
                                case 'ss1-left':
                                    previousCol = col + 1;
                                    break;
                                default:
                                    isConnected = true;
                                    break;
                            }
                            if (!isConnected) {
                                $('#ss1-' + col + '-' + line).remove();
                                this.updateState('remove', col, line, 2);
                                this.gridElMatrix[indexX][indexY].el = 0;
                                this.gridElMatrix[indexX][indexY].type = '';
                                var previousPathId = this.gridElMatrix[previousCol - 1][previousLine - 1].pathId;
                                this.replacePreviousPole(previousPathId);
                                this.updateState('add', previousCol, previousLine, 1, previousPathId);
                            }

                        break;
                        // poteau
                    case 1:

                            var currentPathId = this.gridElMatrix[indexX][indexY].pathId;

                            var currentPathLength = this.path[currentPathId].length;

                            //on verifie qu'on est en bout de ligne et qu'il n'y a pas un autre element connecte
                            if (this.path[currentPathId][currentPathLength - 1][0] == col && this.path[currentPathId][currentPathLength - 1][1] == line && !this.isConnected(1, col, line)) {

                                $("#pole-" + currentPathId + "-" + (this.path[currentPathId].length - 1)).remove();
                                // on change l'image du depart
                                if (col == this.startPoint[0] && line == this.startPoint[1])
                                    $('#start').removeClass('on').addClass('off');

                                this.updateState('remove', col, line, 1, currentPathId);

                                this.gridElMatrix[indexX][indexY].el = 0;
                                this.gridElMatrix[indexX][indexY].pathId = 0;

                                //on met a jour la grille d'etat
                                this.path[currentPathId].pop();
                                //on met a jour la taille du tableau
                                currentPathLength = this.path[currentPathId].length;

                                //cas ou le precedent element est un pilone
                                if (currentPathLength > 0) {
                                    this.replacePreviousPole(currentPathId);
                                    var previousCol = this.path[currentPathId][currentPathLength - 1][0];
                                    var previousLine = this.path[currentPathId][currentPathLength - 1][1];
                                    this.updateState('add', previousCol, previousLine, 1, currentPathId);
                                }
                                //cas ou le precedent element est une station
                                if (this.path[currentPathId].length == 0 && currentPathId > 1) {
                                    //on determine l'emplacement de la station par le type de l'element
                                    var previousCol = col;
                                    var previousLine = line;

                                    switch (this.gridElMatrix[indexX][indexY].type) {
                                        case 'pole-strup-right':
                                            previousCol = col - 1;
                                            break;
                                        case'pole-strup-left':
                                            previousLine = line + 1;
                                            break;
                                        case'pole-strdown-right':
                                            previousLine = line - 1;
                                            break;
                                        case'pole-strdown-left':
                                            previousCol = col + 1;
                                            break;
                                    }

                                    this.replacePreviousSs(col, line, previousCol, previousLine);
                                    this.updateState('add', previousCol, previousLine, 2);

                                }

                                this.gridElMatrix[indexX][indexY].type = '';
                            }

                        break;
                }


            }
        };

        this.isConnected = function (el, col, line) {

            // cas du pilone
            if (el == 1) {
                var indexX = col - 1;
                var indexY = line - 1;
                var nextCol = col;
                var nextLine = line;
                var aUp = ['ss2-up', 'ss1-up', 'ss1-down-left', 'ss1-strup-left', 'ss1-right-up', 'ss1-strup-left-left', 'ss1-strup-left-left', 'ss1-down-left-up'];
                var aDown = ['ss2-down', 'ss1-down', 'ss1-up-right', 'ss1-strdown-right', 'ss1-left-down', 'ss1-strdown-right-left', 'ss1-strdown-right-right', 'ss1-up-right-down'];
                var aRight = ['ss2-right', 'ss1-right', 'ss1-left-up', 'ss1-strup-right', 'ss1-down-right', 'ss1-strup-right-left', 'ss1-strup-right-right', 'ss1-left-up-down'];
                var aLeft = ['ss2-left', 'ss1-left', 'ss1-right-down', 'ss1-strdown-left', 'ss1-up-left', 'ss1-strdown-left-left', 'ss1-strdown-left-right', 'ss1-right-down-up'];
                switch (this.gridElMatrix[indexX][indexY].type) {
                    case 'pole-strup-right':
                        nextCol = col + 1;
                        if (nextCol>nbCol)//cas ou on est au bout en haut a droite
                            return false;
                        if ($.inArray(this.gridElMatrix[nextCol - 1][nextLine - 1].type, aRight) == -1)
                            return false;
                        break;
                    case 'pole-strdown-left':
                        nextCol = col - 1;
                        if (nextCol == 0)
                            return false;
                        if (nextCol > 0 && $.inArray(this.gridElMatrix[nextCol - 1][nextLine - 1].type, aLeft) == -1)
                            return false;
                        break;
                    case 'pole-strdown-right':
                        nextLine = line + 1;
                        if (nextLine < nbLine && $.inArray(this.gridElMatrix[nextCol - 1][nextLine - 1].type, aDown) == -1)
                            return false;
                        break;
                    case 'pole-strup-left':
                        nextLine = line - 1;
                        if (nextLine == 0)
                            return false;
                        if (nextLine > 0 && $.inArray(this.gridElMatrix[nextCol - 1][nextLine - 1].type, aUp) == -1)
                            return false;
                        break
                }

                return true;
            }
        };

        this.displayEl = function (col, line, el, pathId) {

            var indexX = col - 1;
            var indexY = line - 1;

            var currentEl = {'pole': 'pole-strup-left'};
            var currentPathLength = this.path[pathId].length;

            switch (el) {
                case 1:
                case 2:
                case 3:
                    //on change le poteau precedent si besoin
                    if (currentPathLength > 0) {
                        var previousPolePath = this.path[pathId][currentPathLength - 1];
                        var previousIndexX = previousPolePath[0] - 1;
                        var previousIndexY = previousPolePath[1] - 1;
                        var previousPathLength = currentPathLength - 1
                        //4 cas
                        if (previousPolePath[0] > col) {//1
                            if ($('#pole-' + pathId + '-' + previousPathLength).hasClass('pole-strup-left')) {
                                $('#pole-' + pathId + '-' + previousPathLength).removeClass('pole-strup-left').addClass('pole-down-left');
                                this.gridElMatrix[previousIndexX][previousIndexY].type = 'pole-down-left';
                            }
                            if ($('#pole-' + pathId + '-' + previousPathLength).hasClass('pole-strdown-right')) {
                                $('#pole-' + pathId + '-' + previousPathLength).removeClass('pole-strdown-right').addClass('pole-left-down');
                                this.gridElMatrix[previousIndexX][previousIndexY].type = 'pole-down-down';
                            }


                            if (previousPolePath[1] == line)
                                currentEl = {'pole': 'pole-strdown-left', 'ss1': 'ss1-left', 'ss2': 'ss2-left'};
                        }
                        if (previousPolePath[0] < col) {//2
                            if ($('#pole-' + pathId + '-' + previousPathLength).hasClass('pole-strup-left')) {
                                $('#pole-' + pathId + '-' + previousPathLength).removeClass('pole-strup-left').addClass('pole-right-up');
                                this.gridElMatrix[previousIndexX][previousIndexY].type = 'pole-right-up';
                            }

                            if ($('#pole-' + pathId + '-' + previousPathLength).hasClass('pole-strdown-right')) {
                                $('#pole-' + pathId + '-' + previousPathLength).removeClass('pole-strdown-right').addClass('pole-up-right');
                                this.gridElMatrix[previousIndexX][previousIndexY].type = 'pole-up-right';
                            }

                            if (previousPolePath[1] == line)
                                currentEl = {'pole': 'pole-strup-right', 'ss1': 'ss1-right', 'ss2': 'ss2-right'};
                        }
                        if (previousPolePath[1] > line) {//3
                            if ($('#pole-' + pathId + '-' + previousPathLength).hasClass('pole-strdown-left')) {
                                $('#pole-' + pathId + '-' + previousPathLength).removeClass('pole-strdown-left').addClass('pole-up-left');
                                this.gridElMatrix[previousIndexX][previousIndexY].type = 'pole-up-left';
                            }

                            if ($('#pole-' + pathId + '-' + previousPathLength).hasClass('pole-strup-right')) {
                                $('#pole-' + pathId + '-' + previousPathLength).removeClass('pole-strup-right').addClass('pole-left-up');
                                this.gridElMatrix[previousIndexX][previousIndexY].type = 'pole-left-up';
                            }

                            if (previousPolePath[0] == col)
                                currentEl = {'pole': 'pole-strup-left', 'ss1': 'ss1-up', 'ss2': 'ss2-up'};
                        }
                        if (previousPolePath[1] < line) {//4
                            if ($('#pole-' + pathId + '-' + previousPathLength).hasClass('pole-strdown-left')) {
                                $('#pole-' + pathId + '-' + previousPathLength).removeClass('pole-strdown-left').addClass('pole-right-down');
                                this.gridElMatrix[previousIndexX][previousIndexY].type = 'pole-right-down';
                            }

                            if ($('#pole-' + pathId + '-' + previousPathLength).hasClass('pole-strup-right')) {
                                $('#pole-' + pathId + '-' + previousPathLength).removeClass('pole-strup-right').addClass('pole-down-right');
                                this.gridElMatrix[previousIndexX][previousIndexY].type = 'pole-down-right';
                            }

                            if (previousPolePath[0] == col)
                                currentEl = {'pole': 'pole-strdown-right', 'ss1': 'ss1-down', 'ss2': 'ss2-down'};
                        }

                    }
                    else if (pathId > 1) {
                        // cas de connection avec une sous-station (currentPathLength = 0 et pathId>1)

                        //gauche de la ss
                        if (this.gridElMatrix[indexX + 1][indexY].el == 2) {
                            var previousSs = $('#ss1-' + (col + 1) + '-' + line);
                            var previousSsEl = this.gridElMatrix[indexX + 1][indexY];
                            //cas ou la ss a deja une connection
                            if (previousSs.hasClass('ss1-up')) {
                                previousSs.removeClass('ss1-up').addClass('ss1-down-left');
                                previousSsEl.type = 'ss1-down-left';
                            }
                            if (previousSs.hasClass('ss1-left')) {
                                previousSs.removeClass('ss1-left').addClass('ss1-strdown-left');
                                previousSsEl.type = 'ss1-strdown-left';
                            }
                            if (previousSs.hasClass('ss1-down')) {
                                previousSs.removeClass('ss1-down').addClass('ss1-left-down');
                                previousSsEl.type = 'ss1-left-down';
                            }
                            //cas ou la ss a deja 2 connections
                            if (previousSs.hasClass('ss1-strup-left')) {
                                previousSs.removeClass('ss1-strup-left').addClass('ss1-strup-left-left');
                                if (col + 2 < nbCol)
                                    this.gridElMatrix[indexX + 2][indexY].state = 0;
                                previousSsEl.type = 'ss1-strup-left-left';
                            }
                            if (previousSs.hasClass('ss1-right-up')) {
                                previousSs.removeClass('ss1-right-up').addClass('ss1-down-left-up');
                                if (line - 1 > 0)
                                    this.gridElMatrix[indexX + 1][indexY - 1].state = 0;
                                previousSsEl.type = 'ss1-down-left-up';
                            }
                            if (previousSs.hasClass('ss1-strdown-right')) {
                                previousSs.removeClass('ss1-strdown-right').addClass('ss1-strdown-right-right');
                                if (col + 2 < nbCol)
                                    this.gridElMatrix[indexX + 2][indexY].state = 0;
                                previousSsEl.type = 'ss1-strdown-right-right';
                            }
                            if (previousSs.hasClass('ss1-up-right')) {
                                previousSs.removeClass('ss1-up-right').addClass('ss1-up-right-down');
                                if (line + 1 < nbLine)
                                    this.gridElMatrix[indexX + 1][indexY + 1].state = 0;
                                previousSsEl.type = 'ss1-up-right-down';
                            }
                            if (previousSs.hasClass('ss1-up-left')) {
                                previousSs.removeClass('ss1-up-left').addClass('ss1-strdown-left-right');
                                if (line + 1 < nbLine)
                                    this.gridElMatrix[indexX + 1][indexY + 1].state = 0;
                                previousSsEl.type = 'ss1-strdown-left-right';
                            }
                            if (previousSs.hasClass('ss1-right-down')) {
                                previousSs.removeClass('ss1-right-down').addClass('ss1-strdown-left-left');
                                if (line - 1 > 0)
                                    this.gridElMatrix[indexX + 1][indexY - 1].state = 0;
                                previousSsEl.type = 'ss1-strdown-left-left';
                            }
                            currentEl = {'pole': 'pole-strdown-left', 'ss1': 'ss1-left'};
                        }
                        //en haut de la ss
                        if (this.gridElMatrix[indexX][indexY + 1].el == 2) {
                            var previousSs = $('#ss1-' + col + '-' + (line + 1));
                            var previousSsEl = this.gridElMatrix[indexX][indexY + 1];
                            //cas ou la ss a deja une connection
                            if (previousSs.hasClass('ss1-up')) {
                                previousSs.removeClass('ss1-up').addClass('ss1-strup-left');
                                previousSsEl.type = 'ss1-strup-left';
                            }
                            if (previousSs.hasClass('ss1-left')) {
                                previousSs.removeClass('ss1-left').addClass('ss1-up-left');
                                previousSsEl.type = 'ss1-up-left';
                            }
                            if (previousSs.hasClass('ss1-right')) {
                                previousSs.removeClass('ss1-right').addClass('ss1-left-up');
                                previousSsEl.type = 'ss1-left-up';
                            }
                            //cas ou la ss a deja 2 connections
                            if (previousSs.hasClass('ss1-down-left')) {
                                previousSs.removeClass('ss1-down-left').addClass('ss1-strup-left-left');
                                if (col + 2 < nbCol)
                                    this.gridElMatrix[indexX + 1][indexY + 1].state = 0;
                                previousSsEl.type = 'ss1-strup-left-left';
                            }
                            if (previousSs.hasClass('ss1-right-up')) {
                                previousSs.removeClass('ss1-right-up').addClass('ss1-strup-left-right');
                                if (col - 1 > 0)
                                    this.gridElMatrix[indexX - 1][indexY + 1].state = 0;
                                previousSsEl.type = 'ss1-strup-left-right';
                            }
                            if (previousSs.hasClass('ss1-strup-right')) {
                                previousSs.removeClass('ss1-strup-right').addClass('ss1-strup-right-left');
                                if (line + 2 < nbLine)
                                    this.gridElMatrix[indexX][indexY + 2].state = 0;
                                previousSsEl.type = 'ss1-strup-right-left';
                            }
                            if (previousSs.hasClass('ss1-down-right')) {
                                previousSs.removeClass('ss1-down-right').addClass('ss1-left-up-down');
                                if (col + 1 < nbCol)
                                    this.gridElMatrix[indexX + 1][indexY + 1].state = 0;
                                previousSsEl.type = 'ss1-left-up-down';
                            }
                            if (previousSs.hasClass('ss1-strdown-left')) {
                                previousSs.removeClass('ss1-strdown-left').addClass('ss1-strdown-left-right');
                                if (line + 2 < nbLine)
                                    this.gridElMatrix[indexX][indexY + 2].state = 0;
                                previousSsEl.type = 'ss1-strdown-left-right';
                            }
                            if (previousSs.hasClass('ss1-right-down')) {
                                previousSs.removeClass('ss1-right-down').addClass('ss1-right-down-up');
                                if (col - 1 > 0)
                                    this.gridElMatrix[indexX - 1][indexY + 1].state = 0;
                                previousSsEl.type = 'ss1-right-down-up';
                            }
                            currentEl = {'pole': 'pole-strup-left', 'ss1': 'ss1-up'};
                        }
                        //a droite de la ss
                        if (this.gridElMatrix[indexX - 1][indexY].el == 2) {
                            var previousSs = $('#ss1-' + (col - 1) + '-' + line);
                            var previousSsEl = this.gridElMatrix[indexX - 1][indexY];
                            //cas ou la ss a deja une connection
                            if (previousSs.hasClass('ss1-up')) {
                                previousSs.removeClass('ss1-up').addClass('ss1-right-up');
                                previousSsEl.type = 'ss1-right-up';
                            }
                            if (previousSs.hasClass('ss1-right')) {
                                previousSs.removeClass('ss1-right').addClass('ss1-strup-right');
                                previousSsEl.type = 'ss1-strup-right';
                            }
                            if (previousSs.hasClass('ss1-down')) {
                                previousSs.removeClass('ss1-down').addClass('ss1-up-right');
                                previousSsEl.type = 'ss1-up-right';
                            }
                            //cas ou la ss a deja 2 connections
                            if (previousSs.hasClass('ss1-down-left')) {
                                previousSs.removeClass('ss1-down-left').addClass('ss1-down-left-up');
                                if (line - 1 > 0)
                                    this.gridElMatrix[indexX - 1][indexY - 1].state = 0;
                                previousSsEl.type = 'ss1-down-left-up';
                            }
                            if (previousSs.hasClass('ss1-strup-left')) {
                                previousSs.removeClass('ss1-strup-left').addClass('ss1-strup-left-right');
                                if (line - 2 > 0)
                                    this.gridElMatrix[indexX][indexY - 2].state = 0;
                                previousSsEl.type = 'ss1-strup-left-right';
                            }
                            if (previousSs.hasClass('ss1-left-up')) {
                                previousSs.removeClass('ss1-left-up').addClass('ss1-strup-right-left');
                                if (line + 1 < nbLine)
                                    this.gridElMatrix[indexX - 1][indexY + 1].state = 0;
                                previousSsEl.type = 'ss1-strup-right-left';
                            }
                            if (previousSs.hasClass('ss1-down-right')) {
                                previousSs.removeClass('ss1-down-right').addClass('ss1-strup-right-right');
                                if (col - 1 > 0)
                                    this.gridElMatrix[indexX - 1][indexY - 1].state = 0;
                                previousSsEl.type = 'ss1-strup-right-right';
                            }
                            if (previousSs.hasClass('ss1-strdown-right')) {
                                previousSs.removeClass('ss1-strdown-right').addClass('ss1-strdown-right-left');
                                if (col - 2 > 0)
                                    this.gridElMatrix[indexX - 2][indexY].state = 0;
                                previousSsEl.type = 'ss1-strdown-right-left';
                            }
                            if (previousSs.hasClass('ss1-left-down')) {
                                previousSs.removeClass('ss1-left-down').addClass('ss1-up-right-down');
                                if (line + 1 < nbLine)
                                    this.gridElMatrix[indexX - 1][indexY + 1].state = 0;
                                previousSsEl.type = 'ss1-up-right-down';
                            }
                            currentEl = {'pole': 'pole-strup-right', 'ss1': 'ss1-right'};
                        }
                        //en bas de la ss
                        if (this.gridElMatrix[indexX][indexY - 1].el == 2) {
                            var previousSs = $('#ss1-' + col + '-' + (line - 1));
                            var previousSsEl = this.gridElMatrix[indexX][indexY - 1];
                            //cas ou la ss a deja une connection
                            if (previousSs.hasClass('ss1-down')) {
                                previousSs.removeClass('ss1-down').addClass('ss1-strdown-right');
                                previousSsEl.type = 'ss1-strdown-right';
                            }
                            if (previousSs.hasClass('ss1-right')) {
                                previousSs.removeClass('ss1-right').addClass('ss1-down-right');
                                previousSsEl.type = 'ss1-down-right';
                            }
                            if (previousSs.hasClass('ss1-left')) {
                                previousSs.removeClass('ss1-left').addClass('ss1-right-down');
                                previousSsEl.type = 'ss1-right-down';
                            }
                            //cas ou la ss a deja 2 connections
                            if (previousSs.hasClass('ss1-strup-right')) {
                                previousSs.removeClass('ss1-strup-right').addClass('ss1-strup-right-right');
                                if (line - 2 > 0)
                                    this.gridElMatrix[indexX][indexY - 2].state = 0;
                                previousSsEl.type = 'ss1-strup-right-right';
                            }
                            if (previousSs.hasClass('ss1-left-up')) {
                                previousSs.removeClass('ss1-left-up').addClass('ss1-left-up-down');
                                if (col + 1 < nbCol)
                                    this.gridElMatrix[indexX + 1][indexY - 1].state = 0;
                                previousSsEl.type = 'ss1-left-up-down';
                            }
                            if (previousSs.hasClass('ss1-left-down')) {
                                previousSs.removeClass('ss1-left-down').addClass('ss1-strdown-right-right');
                                if (col + 1 < nbCol)
                                    this.gridElMatrix[indexX + 1][indexY - 1].state = 0;
                                previousSsEl.type = 'ss1-strdown-right-right';
                            }
                            if (previousSs.hasClass('ss1-up-right')) {
                                previousSs.removeClass('ss1-up-right').addClass('ss1-strdown-right-left');
                                if (line - 1 > 0)
                                    this.gridElMatrix[indexX - 1][indexY - 1].state = 0;
                                previousSsEl.type = 'ss1-strdown-right-left';
                            }
                            if (previousSs.hasClass('ss1-up-left')) {
                                previousSs.removeClass('ss1-up-left').addClass('ss1-right-down-up');
                                if (col - 1 > 0)
                                    this.gridElMatrix[indexX - 1][indexY - 1].state = 0;
                                previousSsEl.type = 'ss1-right-down-up';
                            }
                            if (previousSs.hasClass('ss1-strdown-left')) {
                                previousSs.removeClass('ss1-strdown-left').addClass('ss1-strdown-left-left');
                                if (line - 2 > 0)
                                    this.gridElMatrix[indexX][indexY - 2].state = 0;
                                previousSsEl.type = 'ss1-strdown-left-left';
                            }
                            currentEl = {'pole': 'pole-strdown-right', 'ss1': 'ss1-down'};
                        }
                    }
                    break;
                case 4:
                    currentEl = {'at': 'at'};
                    break;
            }

            switch (el) {
                case 1:
                    $("#obj-wrapper").append($('<div/>').addClass('pole ' + currentEl.pole).attr('id', 'pole-' + pathId + '-' + currentPathLength).css({
                        left: this.getX(col, line),
                        top: this.getY(col, line)
                    }));
                    this.gridElMatrix[indexX][indexY].type = currentEl.pole;
                    break;
                case 2:
                    $("#obj-wrapper").append($('<div/>').addClass('ss ' + currentEl.ss1).attr('id', 'ss1-' + col + '-' + line).css({
                        left: this.getX(col, line),
                        top: this.getY(col, line)
                    }));
                    this.gridElMatrix[indexX][indexY].type = currentEl.ss1;
                    break;
                case 3:
                    $("#obj-wrapper").append($('<div/>').addClass('ss ' + currentEl.ss2).attr('id', 'ss2-' + col + '-' + line).css({
                        left: this.getX(col, line),
                        top: this.getY(col, line)
                    }));
                    this.gridElMatrix[indexX][indexY].type = currentEl.ss2;
                    break;
                case 4:
                    $("#obj-wrapper").append($('<div/>').addClass('at ' + currentEl.at).attr('id', 'at-' + col + '-' + line).css({
                        left: this.getX(col, line),
                        top: this.getY(col, line)
                    }));
                    this.gridElMatrix[indexX][indexY].type = currentEl.at;
                    break;
            }

        }

        this.updateState = function (action, col, line, el, pathId) {
            var indexX = col - 1;
            var indexY = line - 1;
            var value;
            switch (el) {
                case 1:
                    value = pathId;
                    break;
                case 2:
                    value = -1;
                    break;
                case 3:
                    value = 0;
                    break;
            }
            // on enleve le pathId de la grille d'etat
            this.initGridState(pathId);
            switch (action) {
                case 'add':
                    // top
                    if (line > 1) {
                        if (this.gridElMatrix[indexX][indexY - 1].el == 0)
                            this.gridElMatrix[indexX][indexY - 1].state = value;
                    }
                    // left
                    if (col > 1) {
                        if (this.gridElMatrix[indexX - 1][indexY].el == 0)
                            this.gridElMatrix[indexX - 1][indexY].state = value;
                    }
                    // right
                    if (col < nbCol) {
                        if (this.gridElMatrix[indexX + 1][indexY].el == 0)
                            this.gridElMatrix[indexX + 1][indexY].state = value;
                    }
                    // bottom
                    if (line < nbLine) {
                        if (this.gridElMatrix[indexX][indexY + 1].el == 0)
                            this.gridElMatrix[indexX][indexY + 1].state = value;
                    }

                    this.gridElMatrix[indexX][indexY].el = el;
                    break;
                case 'remove':
                    switch (el) {
                        case 1:
                            // top
                            if (line > 1) {
                                if (this.gridElMatrix[indexX][indexY - 1].state == pathId)
                                    this.gridElMatrix[indexX][indexY - 1].state = 0;
                            }
                            // left
                            if (col > 1) {
                                if (this.gridElMatrix[indexX - 1][indexY].state == pathId)
                                    this.gridElMatrix[indexX - 1][indexY].state = 0;
                            }
                            // right
                            if (col < nbCol) {
                                if (this.gridElMatrix[indexX + 1][indexY].state == pathId)
                                    this.gridElMatrix[indexX + 1][indexY].state = 0;
                            }
                            // bottom
                            if (line < nbLine) {
                                if (this.gridElMatrix[indexX][indexY + 1].state == pathId)
                                    this.gridElMatrix[indexX][indexY + 1].state = 0;
                            }
                            break;
                        case 2:
                        case 3:
                            // top
                            if (line > 1) {
                                if (this.gridElMatrix[indexX][indexY - 1].state == -1)
                                    this.gridElMatrix[indexX][indexY - 1].state = 0;
                            }
                            // left
                            if (col > 1) {
                                if (this.gridElMatrix[indexX - 1][indexY].state == -1)
                                    this.gridElMatrix[indexX - 1][indexY].state = 0;
                            }
                            // right
                            if (col < nbCol) {
                                if (this.gridElMatrix[indexX + 1][indexY].state == -1)
                                    this.gridElMatrix[indexX + 1][indexY].state = 0;
                            }
                            // bottom
                            if (line < nbLine) {
                                if (this.gridElMatrix[indexX][indexY + 1].state == -1)
                                    this.gridElMatrix[indexX][indexY + 1].state = 0;
                            }
                            break;
                    }
                    break;
            }
            return;
        };

        this.allow = function (col, line, el) {
            var indexX = col - 1;
            var indexY = line - 1;
            if (inArrayCoords(col, line, this.aCoordsNotAllowed))
                return false;
            switch (el) {
                case 1:
                    //premier poteau
                    if (this.isEmpty()) {
                        if (col == this.startPoint[0] && line == this.startPoint[1]) {
                            this.gridElMatrix[indexX][indexY].state = 1;
                            $('#start').removeClass('off').addClass('on');
                            return true;
                        }
                        return false;
                    }
                    //poteau connecte a une sous station
                    //on peut connecter un poteau a un emplacement valide apres une sous-station ( gridElMatrix.state = -1 )
                    if (this.gridElMatrix[indexX][indexY].state < 0) {
                        //on incremente le pathId
                        pathId++;
                        this.gridElMatrix[indexX][indexY].state = pathId;
                        return true;
                    }
                    //si le state est >0 alors on peut ( gridElMatrix.state = pathId )
                    return (this.gridElMatrix[indexX][indexY].state > 0) ? true : false;
                    break;
                case 2:
                case 3:
                    //on peut connecter une sous-station a un emplacement valide apres un poteau ( gridElMatrix = 1 )
                    return (this.gridElMatrix[indexX][indexY].state > 0) ? true : false;
                    break;
                case 4:
                    return (this.gridElMatrix[indexX][indexY].el == 0) ? true : false;
                    break;
            }

        }

        this.replacePreviousPole = function (pathId) {
            var currentPathLength = this.path[pathId].length;

            //on change le poteau precedent si besoin
            if (currentPathLength > 0) {
                var previousPolePath = this.path[pathId][currentPathLength - 1];
                var previousIndexX = previousPolePath[0] - 1;
                var previousIndexY = previousPolePath[1] - 1;
                var previousPole = $('#pole-' + pathId + '-' + (currentPathLength - 1));

                if (previousPole.hasClass('pole-up-right')) {
                    previousPole.removeClass('pole-up-right').addClass('pole-strdown-right');
                    this.gridElMatrix[previousIndexX][previousIndexY].type = 'pole-strdown-right';
                }

                if (previousPole.hasClass('pole-up-left')) {
                    previousPole.removeClass('pole-up-left').addClass('pole-strdown-left');
                    this.gridElMatrix[previousIndexX][previousIndexY].type = 'pole-strdown-left';
                }

                if (previousPole.hasClass('pole-right-down')) {
                    previousPole.removeClass('pole-right-down').addClass('pole-strdown-left');
                    this.gridElMatrix[previousIndexX][previousIndexY].type = 'pole-strdown-left';
                }

                if (previousPole.hasClass('pole-right-up')) {
                    previousPole.removeClass('pole-right-up').addClass('pole-strup-left');
                    this.gridElMatrix[previousIndexX][previousIndexY].type = 'pole-strup-left';
                }

                if (previousPole.hasClass('pole-down-left')) {
                    previousPole.removeClass('pole-down-left').addClass('pole-strup-left');
                    this.gridElMatrix[previousIndexX][previousIndexY].type = 'pole-strup-left';
                }

                if (previousPole.hasClass('pole-down-right')) {
                    previousPole.removeClass('pole-down-right').addClass('pole-strup-right');
                    this.gridElMatrix[previousIndexX][previousIndexY].type = 'pole-strup-right';
                }

                if (previousPole.hasClass('pole-left-up')) {
                    previousPole.removeClass('pole-left-up').addClass('pole-strup-right');
                    this.gridElMatrix[previousIndexX][previousIndexY].type = 'pole-strup-right';
                }

                if (previousPole.hasClass('pole-left-down')) {
                    previousPole.removeClass('pole-left-down').addClass('pole-strdown-right');
                    this.gridElMatrix[previousIndexX][previousIndexY].type = 'pole-strdown-right';
                }

            }

        }

        this.replacePreviousSs = function (previousCol, previousLine, col, line) {
            var indexX = col - 1;
            var indexY = line - 1;
            // on a supprime le poteau haut-gauche
            var aUp = {
                'ss1-strup-left': 'ss1-up',
                'ss1-strup-left-left': 'ss1-down-left',
                'ss1-strup-left-right': 'ss1-right-up',
                'ss1-left-up': 'ss1-right',
                'ss1-strup-right-left': 'ss1-strup-right',
                'ss1-left-up-down': 'ss1-down-right',
                'ss1-up-left': 'ss1-left',
                'ss1-strdown-left-right': 'ss1-strdown-left',
                'ss1-right-down-up': 'ss1-right-down'
            };
            // on a supprime le poteau bas-droite
            var aDown = {
                'ss1-down-right': 'ss1-right',
                'ss1-strup-right-right': 'ss1-strup-right',
                'ss1-left-up-down': 'ss1-left-up',
                'ss1-strdown-right': 'ss1-down',
                'ss1-strdown-right-left': 'ss1-up-right',
                'ss1-strdown-right-right': 'ss1-left-down',
                'ss1-right-down': 'ss1-left',
                'ss1-strdown-left-left': 'ss1-strdown-left',
                'ss1-right-down-up': 'ss1-up-left'
            };
            //on a supprime le poteau haut-droite
            var aRight = {
                'ss1-right-up': 'ss1-up',
                'ss1-strup-left-right': 'ss1-strup-left',
                'ss1-down-left-up': 'ss1-down-left',
                'ss1-strup-right': 'ss1-right',
                'ss1-strup-right-left': 'ss1-left-up',
                'ss1-strup-right-right': 'ss1-down-right',
                'ss1-up-right': 'ss1-down',
                'ss1-strdown-right-left': 'ss1-strdown-right',
                'ss1-up-right-down': 'ss1-left-down'
            };
            //on a supprime le poteau bas-gauche
            var aLeft = {
                'ss1-down-left': 'ss1-up',
                'ss1-strup-left-left': 'ss1-strup-left',
                'ss1-down-left-up': 'ss1-right-up',
                'ss1-left-down': 'ss1-down',
                'ss1-strdown-right-right': 'ss1-strdown-right',
                'ss1-up-right-down': 'ss1-up-right',
                'ss1-strdown-left': 'ss1-left',
                'ss1-strdown-left-left': 'ss1-right-down',
                'ss1-strdown-left-right': 'ss1-up-left'
            };
            var ssDiv = $('#ss1-' + col + '-' + line);
            var oldType = this.gridElMatrix[indexX][indexY].type;
            var newType;
            if (previousCol < col)
                newType = aLeft[oldType];
            if (previousCol > col)
                newType = aRight[oldType];
            if (previousLine < line)
                newType = aUp[oldType];
            if (previousLine > line)
                newType = aDown[oldType];
            ssDiv.removeClass(oldType).addClass(newType);
            this.gridElMatrix[indexX][indexY].type = newType;
        }

        this.isEmpty = function () {
            for (var i = 0; i < nbLine; i++) {
                for (var j = 0; j < nbCol; j++) {
                    if (this.gridElMatrix[j][i].el == 1)
                        return false;
                }
            }
            return true;
        };

        this.initGridState = function (pathId) {
            for (var i = 0; i < nbCol; i++) {
                for (var j = 0; j < nbLine; j++) {
                    if (this.gridElMatrix[i][j].state == pathId)
                        this.gridElMatrix[i][j].state = 0;
                }
            }
        };

        this.reset = function(){
          //on cache la fumee
          $("#fumee").hide();
          $("#cables").removeClass('red').removeClass('greenA').removeClass('green');
          //efface tous les objets
          $("#obj-wrapper").empty();
          //on affiche le depart
          grid.displayStart();
          //on remet le train au depart
          $("#train").css({top:-121,left:649});
          //on reinitialise les chemins
          this.path = [];
          //on reinitialise la matrice
          this.gridElMatrix = initGrid(nbCol, nbLine);
        };

        //affiche la grille
        this.displayGrid = function (div) {
            for (var i = 1; i < nbLine + 1; i++) {
                for (var j = 1; j < nbCol + 1; j++) {
                    $(div).append('<div class="box ' + (j == 1 ? 'clear-box' : '') + ((i + j) % 2 == 0 ? ' even' : ' odd') + (inArrayCoords(j, i, this.aCoordsNotAllowed) ? '' : ' selectable ') + '" id="box-' + j + '-' + i + '"></div>' + "\n");
                }
            }
        };

        this.displayStart = function(){
            //affiche le point de depart
            $("#obj-wrapper").append($('<div/>').addClass('off').attr('id', 'start').css({
                left: this.getX(this.startPoint[0] - 1, this.startPoint[1] + 1),
                top: this.getY(this.startPoint[0] - 1, this.startPoint[1] + 1) - 1
            }));
        };

        this.check = function(){
            var statut = this.getWorkingStatut();
            launchAnimation(statut);
        };

        //retourne un statut sur le fonctionnement du train
        this.getWorkingStatut = function(){
            //on teste le point A et B
            //A et B est vide
            var elA = this.gridElMatrix[this.endPointA[0]-1][this.endPointA[1]-1].el;
            var elB = this.gridElMatrix[this.endPointB[0]-1][this.endPointB[1]-1].el;
            //statut 1
            //il n'y a pas de ligne ou de ss2 sur A ET B
            if ((elA==0 || elA==4) && (elB==0  || elB==4))
                return this.getLineStatut();

//                return 1;
            //un poteau sur A ou B ou les 2
            if (elA==1 || elB==1 || elA==2 || elB==2)
                return 2;
            //une ss2 sur A mais pas sur B
            if (elA==3 && elB!=3){
                //si pas de ss1
                if (this.countEl(2)==0 || this.countEl(2)>1)
                    return 6;
                if (this.countEl(2)==1)
                    return 4;
            }
            //une ss2 sur B mais pas sur A
            if (elB==3 && elA!=3){
                //si pas de ss1
                if (this.countEl(2)==0 || this.countEl(2)>1)
                    return 6;
                if (this.countEl(2)==1)
                    return 4;
            }
            //on a plus d'une ss1
            if (this.countEl(2)>1)
                return 6;
            //on a bien une ss2 sur A et B
            if (elA==3 && elB==3){
                switch (this.getAtStatut()){
                    case -1:
                        return 5;
                        break;
                    case 0:
                    case 2:
                        return 7;
                        break;
                    case 1:
                        return 9;
                        break;
                    case 3:
                        return 8;
                        break;
                }
            }
            return 0;
        };

        this.getLineStatut = function(){
            var result = 1;
            var countss2=0;
            var thisGridElMatrix = this.gridElMatrix;
            var aTrackPoint = [[17,1],[16,1],[15,1],[14,1],[13,1],[12,1],[11,1],[10,1],[9,1],[8,1],[7,1]];
            $.each(aTrackPoint, function(index,value){
                if (thisGridElMatrix[value[0]-1][value[1]-1].el==1 || thisGridElMatrix[value[0]-1][value[1]-1].el==2){
                    result=2;
                    return false;
                }
            });
            if (result){
                $.each(aTrackPoint, function(index,value){
                    if (thisGridElMatrix[value[0]-1][value[1]-1].el==3)countss2++;
                });
                if (countss2==1 || countss2==2){
                    //on a pas de ss1
                    if (this.countEl(2)==0 || this.countEl(2)>1)
                        result = 6;
                    if (this.countEl(2)==1)
                        result = 3;
                }
                if (countss2>2)
                    result = 6;
            }
            return result;
        };

        this.getAtStatut = function(){
            //retourne -1: aucun, 0:pas assez, 1:OK, 2:irregulier, 3:trop
            //points sur la voie sans A et B
            var aTrackPoint = [[17,1],[16,1],[15,1],[14,1],[13,1],[12,1],[11,1],[10,1],[9,1],[8,1],[7,1]];
            var countAt=0;
            var thisGridElMatrix = this.gridElMatrix;
            $.each(aTrackPoint, function(index,value){
                if (thisGridElMatrix[value[0]-1][value[1]-1].el==4)countAt++;
            });
            if (countAt==0)return -1;
            if (countAt>5)return 3;
            if (countAt<3)return 0;
            if (countAt==3 && thisGridElMatrix[14][0].el==4 && thisGridElMatrix[11][0].el==4 && thisGridElMatrix[8][0].el==4) return 1;
            if (countAt==4 && thisGridElMatrix[14][0].el==4 && thisGridElMatrix[12][0].el==4 && thisGridElMatrix[10][0].el==4 && thisGridElMatrix[8][0].el==4) return 1;
            if (countAt==5 && thisGridElMatrix[15][0].el==4 && thisGridElMatrix[13][0].el==4 && thisGridElMatrix[11][0].el==4 && thisGridElMatrix[9][0].el==4 && thisGridElMatrix[7][0].el==4) return 1;
            return 2;
        };

        this.showDebugElMatrix = function (matrix) {
            var ret = '';
            for (var i = 0; i < nbLine; i++) {
                ret += '<p>';
                for (var j = 0; j < nbCol; j++) {
                    switch (matrix) {
                        case 'el':
                            ret += this.gridElMatrix[j][i].el + ' ';
                            break;
                        case 'pathId':
                            ret += this.gridElMatrix[j][i].pathId + ' ';
                            break;
                    }

                }
                ret += '</p>';
            }
            return ret;
        };

        this.showDebugStateMatrix = function () {
            var ret = '';
            for (var i = 0; i < nbLine; i++) {
                ret += '<p>';
                for (var j = 0; j < nbCol; j++) {
                    ret += this.gridElMatrix[j][i].state + ' ';
                }
                ret += '</p>';
            }
            return ret;
        };

        this.getX = function (col, line) {
            return (this.xOrig + (col - 1) * 50) + (line - 1) * 50;

        }

        this.getY = function (col, line) {
            return (this.yOrig + (line - 1) * 25) - (col - 1) * 25;
        }

        this.countEl=function (el){
            var count = 0;
            for (var i = 0; i < nbLine; i++) {
                for (var j = 0; j < nbCol; j++) {
                    if (this.gridElMatrix[j][i].el == el) count++;
                }
            }
            return count;
        };
    }

    function createDebug() {
        $("#debug").show();
        this.show = function (pan, str) {
            $(pan).html(str);
        }
    }

    function initGrid(nbCol, nbLine) {
        var x = new Array(nbCol);
        for (var i = 0; i < nbCol; i++) {
            x[i] = new Array(nbLine);
        }
        for (var i = 0; i < nbLine; i++) {
            for (var j = 0; j < nbCol; j++) {
                x[j][i] = {el: 0, pathId: 0, type: '', state: 0};
            }
        }
        return x;
    }

    function inArrayCoords(col, line, arrCoords) {
        var filtered = $(arrCoords).filter(function () {
            var thisX = this[0];
            var thisY = this[1];
            return col == thisX && line == thisY;
        });
        if (filtered.length > 0) {
            return true
        }
        return false;
    }

    function displayModal(statut){
        switch(statut){
            case 0:
                $.modal("<div class='modal-content red'>Rien ne se passe.</div>");
                break;
            case 1:
                $.modal("<div class='modal-content red'>L’électricité doit arriver jusqu’à la voie ferrée.</div>");
                break;
            case 2:
                $.modal("<div class='modal-content red'>La tension électrique est trop importante. La tension doit être abaissée.</div>",{onClose:function(dialog){
                    $('#fumee').fadeOut("slow");
                    $("#cables").removeClass('red');
                    $.modal.close(); // must call this!
                }});
                break;
            case 3:
                $.modal("<div class='modal-content red'>La voie ferrée doit être régulièrement alimentée en électricité.</div>");
                break;
            case 4:
                $.modal("<div class='modal-content red'>la voie ferrée doit être régulièrement alimentée en électricité.</div>",{onClose:function(dialog){
                    //on remet le train au depart
                    $("#train").css({top:-121,left:649});
                    $("#cables").removeClass('greenA');
                    $.modal.close(); // must call this!
                }});
                break;
            case 5:
                $.modal("<div class='modal-content orange'>Comment résoudre ce problème de ralentissement en milieu de parcours ? L’un de vos outils permet de garantir une alimentation électrique régulière tout au long du parcours.</div>",{onClose:function(dialog){
                    //on remet le train au depart
                    $("#train").css({top:-121,left:649});
                    $("#cables").removeClass('greenAB');
                    $.modal.close(); // must call this!
                }});
                break;
            case 6:
                $.modal("<div class='modal-content orange'>La tension électrique doit être correctement abaissée par les différentes sous-stations.</div>");
                break;
            case 7:
                $.modal("<div class='modal-content orange'>L’un de vos outils doit être implanté de façon régulière tout au long du parcours pour  garantir une alimentation électrique régulière sur toute la voie ferrée.</div>",{onClose:function(dialog){
                    //on remet le train au depart
                    $("#train").css({top:-121,left:649});
                    $.modal.close(); // must call this!
                }});
                break;
            case 8:
                $.modal("<div class='modal-content orange'>Trop de autotransformateurs ont été implantés.</div>",{onClose:function(dialog){
                    //on remet le train au depart
                    $("#train").css({top:-121,left:649});
                    $.modal.close(); // must call this!
                }});
                break;
            case 9:
                $.modal("<div class='modal-content green'>Bravo ! Votre voie ferrée dispose d’une alimentation électrique régulière, fiable et performante pour la circulation des trains.</div>",{onClose:function(dialog){
                    $("#tester").hide();
                   // $("#continuer").show();
                    $("#imprimer").show();
                        //on remet le train au depart
                    $("#train").css({top:-121,left:649});
                    $("#cables").removeClass('green');
                    $.modal.close(); // must call this!
                }});
                break;
        }
    }
    function displaySpeedAnimation(statut){
        switch(statut){
            case 4:
                case 9:
                $("#speed").countTo({
                   from: 0,
                   to:320,
                   speed:1500,
                   refreshInterval: 10,
                   onComplete: function(){
                        $("#speed").countTo({
                           from: 320,
                           to:0,
                           speed:1500,
                           refreshInterval: 10,
                        });
                   }
                });
                break;
            case 7:
                $("#speed").countTo({
                   from: 0,
                   to:250,
                   speed:1400,
                   refreshInterval: 10,
                   onComplete: function(){
                        $("#speed").countTo({
                           from: 250,
                           to:0,
                           speed:1400,
                           refreshInterval: 10,
                           onComplete: function(){
                                $("#speed").countTo({
                                   from: 0,
                                   to:250,
                                   speed:1400,
                                   refreshInterval: 10,
                                   onComplete: function(){
                                        $("#speed").countTo({
                                           from: 250,
                                           to:0,
                                           speed:1400,
                                           refreshInterval: 10,
                                        });
                                   }
                                });
                           }
                        });
                   }
                });
                break;
        }
    }


    function launchAnimation(statut){
        switch(statut){
            case 2:
                $("#cables").addClass('red');
                animState = 1;
                $('#fumee').fadeIn("slow",function(){
                    setTimeout(function () {
                        animState = 0;
                        displayModal(statut);
                        return;
                    }, 1000);
                });
                break;
            case 4:
                $("#cables").addClass('greenA');
                animState = 1;
                displaySpeedAnimation(4);
                $("#train").animate({
                    left: "-=300",
                    top: "+=150"
                }, 3000, function () {
                    setTimeout(function () {
                        animState = 0;
                        displayModal(statut);
                        return;
                    }, 1000);
                });
                break;
            case 5:
                $("#cables").addClass('greenAB');
                animState = 1;
                displaySpeedAnimation(7);
                $("#train").animate({
                    left: "-=300",
                    top: "+=150"
                }, 3000, function () {
                    $("#train").animate({
                        left: "-=300",
                        top: "+=150"
                    }, 3000, function () {
                        setTimeout(function () {
                            animState = 0;
                            displayModal(statut);
                            return;
                        }, 1000);
                    });
                });
                break;
            case 7:
                animState = 1;
                displaySpeedAnimation(7);
                $("#train").animate({
                    left: "-=300",
                    top: "+=150"
                }, 3000, function () {
                    $("#train").animate({
                        left: "-=300",
                        top: "+=150"
                    }, 3000, function () {
                        setTimeout(function () {
                            animState = 0;
                            displayModal(statut);
                            return;
                        }, 1000);
                    });
                });
                break;
            case 8:
            case 9:
                displaySpeedAnimation(9);
                $("#cables").addClass('green');
                animState = 1;
                $("#train").animate({
                    left: "-=600",
                    top: "+=300"
                }, 3000, function () {
                    animState = 0;
                    displayModal(statut);
                    return;
                });
                break;
            default:
                displayModal(statut);
                return;
                break;

        }

    }
});
