var alturaCabecalhoGrid = 50;
var alturaItemGrid = 50;
var perPage;
var intervalFunction; // variavel que recebe funcao a ser executada de tempos em tempos (paginacao)
var intervaloPaginacao = 10000;

var parametro_proximas_chegadas = 5; //até quanto tempo é o filtro de proximas chegadas
var filtered;//matriz de dados filtrados para o rodapé
var intervalFunctionFooter;
var intervaloPaginacaoFooter = 7000;
var qtde_page_footer;
var indice_footer;//posicao atual da lista do rodape
var itemBgColor = "#46525c";

var horarioLayout; //guarda se o layout atual é de dia (0) ou noite (1)



$(document).ready(function () {

    //gridAdjust();

    relogio();

    frames();


    startAutoPagination();

    $(window).resize(function () {
        gridAdjust();
        updateFooter();
    });

    $(document).keydown(function (e) {
        if (e.which == 67 && e.ctrlKey && e.altKey) {
            //chama modal de configurações
            $('#modal-config').modal();
        }
    });

    $('.logo_inlog .options').click(function (e) {
        //chama modal de configurações
        $('#modal-config').modal();
    });

    //ajax pega obj config
    //verifica localstorage, se houver, salva no config
    
});

function gridAdjust() {
    $('#myGrid, .wrap-grid').height($(window).outerHeight() - $('header').outerHeight() - $('footer').outerHeight() - $('#pager').outerHeight());

    perPage = parseInt( ($('#myGrid').outerHeight() - alturaCabecalhoGrid ) / alturaItemGrid);
    dataView.setPagingOptions({ pageSize: perPage});

    grid.resizeCanvas();

    updatePagination(dataView.getPagingInfo().pageNum, dataView.getPagingInfo().totalPages);
}


// FUNCOES PARA A LISTAGEM ###########################################################################
function fliprow() {
    $('.slick-row').click(function () {
        $(this).children('.slick-cell').toggle("fade");
    });
}

function nextPage() {

    gridAdjust();   

    var delay = 50;
    
    if (dataView.getPagingInfo().totalPages > 1) {

        $('.slick-row').each(function (i, val) {

            //$(this).delay(delay * i).animate({ opacity: 0 }, 100, function () {
            //$(this).delay(delay * i).css({ transform: 'rotateX(180deg)', opacity: 0 });
            $(this).delay(delay * i).toggle('clip', 100, function () {
                //quando a animacao estiver concluida
                if ($('.slick-row').eq($('.slick-row').length - 1).css('display') == 'none') {

                    if (dataView.getPagingInfo().pageNum < dataView.getPagingInfo().totalPages - 1) {
                        dataView.setPagingOptions({ pageNum: dataView.getPagingInfo().pageNum + 1 });
                    } else {
                        dataView.setPagingOptions({ pageNum: 0 });
                    }

                    updatePagination(dataView.getPagingInfo().pageNum, dataView.getPagingInfo().totalPages);

                    $('.slick-row').hide();//('opacity', '0');

                    $('.slick-row').each(function (i, val) {
                        $(this).delay(delay * i).toggle('clip', 100);
                    });
                }
            });
        });
    }
}

function startAutoPagination() {
    intervalFunction = window.setInterval(nextPage, intervaloPaginacao);
}

function stopAutoPagination() {
    clearInterval(intervalFunction);
}

function updatePagination(npage, totpage) {
    $('header .pagination .pageNum').text(npage + 1);
    $('header .pagination .pageTot').text(totpage);
}
// ##################################################################################################



function relogio() {

    //sub-objeto relogio
    var relogio = {
        doisdigitos: true,
        segundos: false,
        icone: true
    }

    var result;

    //verifica qual layout deve ser exibido
    var hours = new Date().getHours();
    if (hours >= 6 && hours <= 18) { horarioLayout = 0; } else { horarioLayout = 1; }
    updateLayout();

    setInterval(function () {
        var seconds = new Date().getSeconds();
        var minutes = new Date().getMinutes();
        hours = new Date().getHours();

        //testa se o horario mudou para dia/noite, se mudou, atualiza o layout
        if (hours >= 6 && hours <= 18) {
            if (horarioLayout != 0) {
                horarioLayout = 0;
                updateLayout();
            }
        } else {
            if (horarioLayout != 1) {
                horarioLayout = 1;
                updateLayout();
            }
        }

        if (relogio.doisdigitos) {
            hours = (hours < 10 ? "0" : "") + hours;
            minutes = (minutes < 10 ? "0" : "") + minutes;
            seconds = (seconds < 10 ? "0" : "") + seconds;
        } 
        
        result = hours + ":" + minutes + (relogio.segundos ? ':' + seconds : '');

        $("header .clock .time").html(result);

        //mostra/oculta o icone
        if (relogio.icone) {
            $('.clock svg').show();
        } else {
            $('.clock svg').hide();
        }

    }, ((relogio.segundos)?1000:3000) );
}



// FUNCOES PARA O RODAPÉ ###########################################################################
function frames() {
    //var svg = $("<svg xmlns:dc='https://purl.org/dc/elements/1.1/' xmlns:cc='https://creativecommons.org/ns#' xmlns:rdf='https://www.w3.org/1999/02/22-rdf-syntax-ns#' xmlns:svg='https://www.w3.org/2000/svg' xmlns='https://www.w3.org/2000/svg' xmlns:sodipodi='http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd' xmlns:inkscape='https://www.inkscape.org/namespaces/inkscape' id='svg2' version='1.1' inkscape:version='0.48.4 r9939' sodipodi:docname='frame.svg'><g inkscape:label='Layer 1' inkscape:groupmode='layer' id='layer1'><path style='/* fill:#ffffff; */stroke:none' d='M 34.06589,45.691142 1.0239674,346.37264 c 0,0 -3.5155679,16.69838 5.5069863,29.73772 10.0555033,14.53215 29.7377303,14.31817 29.7377303,14.31817 l 628.897926,-2.2028 c 0,0 17.84382,1.28285 28.63632,-12.11537 13.1557,-16.33199 13.21678,-30.83913 13.21678,-30.83913 L 741.16302,50.096731 c 0,0 3.22839,-19.287997 -4.40559,-33.041926 C 727.86454,1.0326777 709.2225,0.53385271 709.2225,0.53385271 L 77.020388,1.6352473 c 0,0 -16.702342,-1.72264157 -33.041922,18.7237527 -9.651514,12.077343 -9.912576,25.332142 -9.912576,25.332142 z' id='path3032' inkscape:connector-curvature='0' sodipodi:nodetypes='ccsccsccsccsc'/></g></svg>");
    var svg = $('<svg xmlns="https://www.w3.org/2000/svg" xmlns:xlink="https://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="230" height="120" viewBox="0 0 230 125" enable-background="new 0 0 100 100" xml:space="preserve"> <g>  <title>Layer 1</title>  <path fill="#ffffff" id="svg_5" d="m11.75882,16.03977l-10.12129,92.69273c0,0 -1.07688,5.14771 1.68688,9.1674c3.08017,4.4799 9.10917,4.41393 9.10917,4.41393l192.64197,-0.67908c0,0 5.46585,0.39548 8.77179,-3.73481c4.02982,-5.03476 4.04849,-9.50696 4.04849,-9.50696l10.45868,-90.99504c0,0 0.98892,-5.94602 -1.34952,-10.18602c-2.72403,-4.93922 -8.43439,-5.093 -8.43439,-5.093l-193.65409,0.33954c0,0 -5.11621,-0.53105 -10.1213,5.77207c-2.95642,3.72315 -3.03638,7.80928 -3.03638,7.80928l0,-0.00001l-0.00002,0l0.00001,0l0,-0.00001l0,-0.00001l0,-0.00001l0,-0.00001z"/> </g></svg>');

    $('.bg-frame').each(function (i, val) {
        if (!$(this).children('svg').length) {
            svg.children('g').children('path').css('fill', $(this).attr('bg'));
            svg.clone().appendTo($(this));
        } else {
            $(this).children('svg').children('g').children('path').css('fill', $(this).attr('bg'));
        }
    });
}

function updateFooter() {
    stopAutoPaginationFooter();

    var result = dataView.getItems();
    filtered = result.filter(function (x) { return parseInt(x['previsto'].replace(' min', "")) <= parametro_proximas_chegadas; });
    filtered.sort(function (a, b) {
        a = parseInt(a['previsto'].replace(' min', ""));
        b = parseInt(b['previsto'].replace(' min', ""));
        return a == b ? 0 : (a < b ? -1 : 1);
    });
    
    var e = $('.list-nexts');
    e.html('');
    filtered.forEach(function (i) {
        var item = $('<div class="item"><div class="bg-frame" bg="'+itemBgColor+'"></div><div class="item-content"><div class="title">' + i['linha'] + '</div><div class="veiculo">' + i['veiculo'] + '</div><div class="pltf">' + i['plataforma'] + '</div><div class="previsto">' + i['previsto'] + '</div></div></div>');
        e.append(item);
    });
    frames();

    qtde_page_footer = parseInt( ($('.list-nexts').width() - 460) / 230);//calcula a quantidade de itens que cabem no rodapé
    $('.list-nexts .item').removeClass('active').hide();
    $('.list-nexts .item').slice(0, qtde_page_footer).addClass('active').show();

    indice_footer = qtde_page_footer;
    
    startAutoPaginationFooter();
}

function startAutoPaginationFooter() {
    intervalFunctionFooter = window.setInterval(nextPageFooter, intervaloPaginacaoFooter);
}

function stopAutoPaginationFooter() {
    clearInterval(intervalFunctionFooter);
}

function nextPageFooter() {
    var delay = 100;

    if ($('.list-nexts .item').length > qtde_page_footer) {//se houver mais de uma página

        $($('.list-nexts .item.active').get().reverse()).each(function (i, val) {

            //$(this).hide('slide',{direction: 'right'}, 100, function () {
            //$(this).delay(delay * i).hide('slide', {direction: 'right'}, 200, function () {
            //$(this).delay(delay * i).fadeOut(25, function () {
            $(this).fadeOut(200, function () {

                if ($('.list-nexts .item.active').first().css('display') == 'none') {//quando a animacao estiver concluida

                    $('.list-nexts .item.active').hide();
                    $('.list-nexts .item.active').removeClass('active');

                    //exibe os proximos itens
                    if (indice_footer >= filtered.length) {
                        indice_footer = 0;
                    }

                    $('.list-nexts .item').slice(indice_footer, indice_footer + qtde_page_footer).each(function (i, val) {
                        //$(this).addClass('active').delay(delay * i).show('slide', { direction: 'left' }, 200);
                        $(this).addClass('active').delay(delay * i).fadeIn(200);
                    });

                    indice_footer += qtde_page_footer;
                }
            });
        });
    }
}
//#################################################################################################



// CONFIGURAÇÕES - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function updateLayout() {

    var i = 4;
    
    var layout = {
        op: [ {
                stdHeaderBgcolor: '#aecee5',
                stdHeaderTxcolor: '#000',
                stdHeaderPagecolor: '#fff',
                ftrBgcolor: '#343d44',
                ftrItemBgcolor: '#46525c',
                ftrItemTitlecolor: '#fff600',
                ftrItemTxcolor: '#fff',
                lstHeaderBgcolor: 'transparent',
                lstHeaderTxcolor: '#fff',
                lstBodyBgcolorA: '#606060',
                lstBodyBgcolorB: '#383838',
                lstBodyTxcolor: '#fff600',
                lstBodyTxsize: 28
            },
            {
                stdHeaderBgcolor: '#002299',
                stdHeaderTxcolor: '#847',
                stdHeaderPagecolor: '#192',
                ftrBgcolor: '#cda',
                ftrItemBgcolor: '#876',
                ftrItemTitlecolor: '#123',
                ftrItemTxcolor: '#456',
                lstHeaderBgcolor: '#098',
                lstHeaderTxcolor: '#028',
                lstBodyBgcolorA: '#376',
                lstBodyBgcolorB: '#111',
                lstBodyTxcolor: '#746',
                lstBodyTxsize: 20
            }
        ]
    };

    $('.proxchegadas .bg-frame, .logo_inlog .bg-frame').attr('bg', layout.op[horarioLayout].stdHeaderBgcolor);
    $('.list-nexts .item .bg-frame').attr('bg', layout.op[horarioLayout].ftrItemBgcolor);
    itemBgColor = layout.op[horarioLayout].ftrItemBgcolor;
    frames();

    document.styleSheets[i].rules[0].style.background = layout.op[horarioLayout].stdHeaderBgcolor; //cor de fundo cabecalho
    document.styleSheets[i].rules[1].style.color = layout.op[horarioLayout].stdHeaderTxcolor; //cor do texto cabecalho
    document.styleSheets[i].rules[2].style.fill = layout.op[horarioLayout].stdHeaderTxcolor; //cor do icone do relogio
    document.styleSheets[i].rules[3].style.color = layout.op[horarioLayout].stdHeaderPagecolor; // cor do texto da paginacao
    document.styleSheets[i].rules[4].style.backgroundColor = layout.op[horarioLayout].ftrBgcolor; //cor de fundo do rodapé
    document.styleSheets[i].rules[5].style.color = layout.op[horarioLayout].ftrItemTitlecolor; //cor do título dos itens
    document.styleSheets[i].rules[6].style.color = layout.op[horarioLayout].ftrItemTxcolor; //cor do texto dos itens
    document.styleSheets[i].rules[7].style.background = layout.op[horarioLayout].lstHeaderBgcolor; //cor de fundo do cabeçalho da tabela
    document.styleSheets[i].rules[7].style.color = layout.op[horarioLayout].lstHeaderTxcolor; //cor da fonte do cabeçalho da tabela
    document.styleSheets[i].rules[8].style.background = layout.op[horarioLayout].lstBodyBgcolorA; //cor de fundo A
    document.styleSheets[i].rules[9].style.background = layout.op[horarioLayout].lstBodyBgcolorB; //cor de fundo B
    document.styleSheets[i].rules[10].style.color = layout.op[horarioLayout].lstBodyTxcolor; //cor da fonte da listagem
    document.styleSheets[i].rules[10].style.fontSize = layout.op[horarioLayout].lstBodyTxsize + 'px'; //tamanho da fonte da listagem
    document.styleSheets[i].rules[11].style.fontSize = layout.op[horarioLayout].lstBodyTxsize + 'px'; //tamanho da fonte da listagem

}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 


var dataView;
var grid;
var pager;

$(function () {
    // Função para alterar o formato do valor das células
    function formatter(row, cell, value, columnDef, dataContext) {
        return value;
    }

    // Configura as opções da grid
    var options = {
        enableAddRow: false,
        enableCellNavigation: true,
        asyncEditorLoading: true,
        enableCellNavigation: false,
        enableColumnReorder: true,
        forceFitColumns: true,
        syncColumnCellResize: true,
        multiColumnSort: true,
        headerRowHeight: alturaCabecalhoGrid,
        rowHeight: alturaItemGrid,
        //forceSyncScrolling: true,
        enableAsyncPostRender: true
    }

    //enableAddRow: true,
    //enableCellNavigation: true,
    //asyncEditorLoading: true,
    //topPanelHeight: 25

    // Array com os valores das células do cabeçalho
    var columns = [
        { id: "veiculo", name: "Veículo", field: "veiculo", formatter: formatter, sortable: true, width: 150 },
        { id: "access", name: "<img src='../Content/img/sinter/access.png' alt='' width='38' style='margin-left: 3px;' />", field: "access", formatter: formatter, sortable: true, width: 70 },
        { id: "linha", name: "Linha", field: "linha", sortable: true, width: 200 },
        { id: "previsto", name: "Previsto", field: "previsto", sortable: true },
        { id: "plataforma", name: "Plataforma", field: "plataforma", formatter: formatter, sortable: true, cssClass: 'plataforma-cell', width: 100 },
        { id: "proxterminal", name: "Próximo Terminal", field: "proxterminal", sortable: true, width: 180 },
        { id: "horario", name: "AVL", field: "avl", formatter: formatter, sortable: true, width: 100 },
        { id: "origem", name: "Ignição", field: "ignicao", formatter: formatter, sortable: true, width: 100 },
        { id: "distancia", name: "Data/Hora", field: "datahora", sortable: true, width: 120 },
        { id: "destino", name: "Destino", field: "destino", sortable: true, width: 180 }
    ];

    // Função que mostra os valores das células na grid
    $(function () {
        var data = [];

        for (var i = 0; i < 100; i++) {

            var tempo_previsto = tempoPrevisto();

            data[i] = {
                id: 'id_'+i,
                veiculo: numOnibus() + ' <img src="../Content/img/bus/bus-' + imgBus() + '.png" alt="" />',
                access: "<img src='../Content/img/sinter/access.png' alt='' width='44' />",
                linha: nomeLinha(),
                previsto: (tempo_previsto < 10 ? '0'+tempo_previsto : tempo_previsto) + " min",
                plataforma: plataforma(),
                proxterminal: destino(),
                destino: destino()
            };
        }

        dataView = new Slick.Data.DataView({ inlineFilters: true });
        dataView.setItems(data);
        grid = new Slick.Grid("#myGrid", dataView, columns, options);
        pager = new Slick.Controls.Pager(dataView, grid, $("#pager"));

        updateFooter();// atualiza a listagem do rodapé

        gridAdjust();//ajusta a altura da grid de acordo com a tela

        updatePagination(dataView.getPagingInfo().pageNum, dataView.getPagingInfo().totalPages);

        columnpicker = new Slick.Controls.ColumnPicker(columns, grid, options);

        grid.onSort.subscribe(function (e, args) {
            var cols = args.sortCols;

            data.sort(function (dataRow1, dataRow2) {
                for (var i = 0, l = cols.length; i < l; i++) {
                    var field = cols[i].sortCol.field;
                    var sign = cols[i].sortAsc ? 1 : -1;
                    var value1 = dataRow1[field], value2 = dataRow2[field];
                    var result = (value1 == value2 ? 0 : (value1 > value2 ? 1 : -1)) * sign;

                    if (result != 0) {
                        return result;
                    }
                }

                return 0;
            });

            grid.invalidate();
            grid.render();
        });

        // wire up model events to drive the grid
        dataView.onRowCountChanged.subscribe(function (e, args) {
            grid.updateRowCount();
            grid.render();
        });

        dataView.onRowsChanged.subscribe(function (e, args) {
            grid.invalidateRows(args.rows);
            grid.render();
        });

        dataView.onPagingInfoChanged.subscribe(function (e, pagingInfo) {
            var isLastPage = pagingInfo.pageNum == pagingInfo.totalPages - 1;
            var enableAddRow = isLastPage || pagingInfo.pageSize == 0;
            var options = grid.getOptions();

            if (options.enableAddRow != enableAddRow) {
                //grid.setOptions({ enableAddRow: enableAddRow });
            }
        });

    });





    // FUNÇÕES PARA GERAR CONTEUDO RANDOMICO
    function imgBus() {
        var min = 1;
        var max = 11;
        var r = Math.floor(Math.random() * (max - min + 1) + min);

        return r;
    }

    function numOnibus() {
        return Math.floor(Math.random() * 90000) + 10000;
    }

    function nomeLinha() {
        var arr = ["CARA CARA", "DER", "MARIA OTILIA", "OURO VERDE", "PORTO SEGURO", "SANTA MARIA", "T. CENTRAL/T. OFICINAS", "CIPA VIA JD. AMALIA"];
        return arr[Math.floor(Math.random() * 8)];
    }

    function plataforma() {
        var arr = [
            ["A", "#0fa100"],
            ["B", "#ff6000"],
            ["C", "#ffa800"],
            ["D", "#007eff"],
            ["E", "#ff003c"],
            ["F", "#5a00ff"]            
        ];
        var num = Math.floor(Math.random() * 6);
        return '<div class="plataforma" style="background-color: ' + arr[num][1] + '">' + arr[num][0] + '</div>';
    }

    function tempoPrevisto () {
        return Math.floor(Math.random() * 59);
    }

    function destino() {
        var arr = ["TERM. OFICINAS", "PF. CARA CARA", "TERM. CENTRAL", "TERM. N. RUSSIA", "PF. JD. AMALIA", "PF. SANTA MARIA"];
        return arr[Math.floor(Math.random() * 6)];
    }

});