var grid;

$(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 = {
		enableCellNavigation: false,
		enableColumnReorder: true,
		forceFitColumns: true,
		syncColumnCellResize: true,
		multiColumnSort: true,
		headerRowHeight: 25,
		rowHeight: 25,
		//forceSyncScrolling: true,
		enableAsyncPostRender: true
	}
	
	// Array com os valores das células do cabeçalho
	var columns = [
        {id: "tipo", name: "Tipo", field: "tipo", formatter: formatter, sortable: true, width: 100},
        {id: "identificador", name: "Identificador", field: "identificador", sortable: true, width: 100},
        {id: "veiculo", name: "Veículo", field: "veiculo", sortable: true, width: 200},
        {id: "placa", name: "Placa", field: "placa", sortable: true},
        {id: "serie", name: "Nº de série", field: "serie", sortable: true},
        {id: "linha", name: "Linha", field: "linha", sortable: true},
        {id: "operacao", name: "Operação", field: "operacao", sortable: true},
        {id: "avl", name: "AVL", field: "avl", formatter: formatter, sortable: true, width: 100},
        {id: "ignicao", name: "Ignição", field: "ignicao", formatter: formatter, sortable: true, width: 100},
        {id: "datahora", name: "Data/Hora", field: "datahora", sortable: true, width: 120},
        {id: "vel", name: "Vel", field: "vel", sortable: true},
        {id: "pendentes", name: "Pendentes", field: "pendentes", sortable: true},
        {id: "acao", name: "Ação", field: "acao", formatter: formatter, sortable: false}
    ];
	
    // Função que mostra os valores das células na grid
    $(function () {
	    var data = [];
		
	    for (var i = 0; i < 5000; i++) {
        data[i] = {
        tipo: '<img src="../Content/img/bus/bus-' + imgBus() + '.png" alt="" />',
			    identificador: "GA116",
			    veiculo: "VOLVO B12M VERMELHO 2007",
			    placa: "AKE-8892",
			    serie: "A0008017",
			    linha: i,
			    operacao: "OP URBANA",
			    avl: showStatus('<span class="green"><span class="glyphicon glyphicon-ok-sign"></span> Conectado</span>', '<span class="red"><span class="glyphicon glyphicon-exclamation-sign"></span> Desconectado</span>'),
			    ignicao: showStatus('<span class="green"><span class="glyphicon glyphicon-off"></span> Ligado</span>', '<span class="red"><span class="glyphicon glyphicon-off red"></span> Desligado</span>'),
			    datahora: "31/07/2014 20:36:30",
			    vel: 0,
			    pendentes: imgBus(),
			    acao: '<button type="button" class="btn-acao"><img src="../Content/img/svg/icon_detalhe.svg" width="16" />Detalhes</button>'
        };
    }
		
    grid = new Slick.Grid("#myGrid", data, columns, options);
    // gridAdjust(); //ajusta a altura da grid de acordo com a tela
    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();
        });
    });
	
	function imgBus() {
		var min = 1;
		var max = 11;
		var r = Math.floor(Math.random() * (max - min + 1) + min);
		
		return r;
	}
	
	function showStatus(str1, str2) {
		var min = 1;
		var max = 4;
		var str1 = str1;
		var str2 = str2;
		var res = Math.floor(Math.random() * (max - min + 1) + min);
		
		if(res == 1 || res == 3) {
			return str1;
		} else {
			return str2;
		}
	}
	
	$(".table-head").toggle(
		function() {
			$("footer").css({"top" : "auto", "height" : "auto"});
			$(".wrap-grid").hide();
			$("#menu, #mapa, #barra-alarmes").css({ "bottom" : "20px" });
		}, function() {
		    $(".wrap-grid").show();

            // Ajusta o menu de acordo com a altura da grid
		    var h = $("footer").outerHeight();
		    $("#menu, #barra-alarmes").css({ "bottom" : +h + "px" });
		}
	);
	
	$('.grid-footer').resizable({
		alsoResize: ".slick-viewport, .wrap-grid, #myGrid",
		animate: false,
		minHeight: 171,
		handles: "n",
		stop: function (event, ui){
			grid.resizeCanvas();
		}
	});
});