$(document).ready(function () {
    $("#clearProduct").on('click', clearProduct);
    $("#selectProduct").on('click', selectProduct);
	$("#clearAccount").on('click', clearAccount);
    $("#selectAccount").on('click', selectAccount);
	$("#myTable").tablesorter({
        theme: 'blue',
        widgetOptions: {
            zebra: ["normal-row", "alt-row"]
        }
    });
});

function pdfExport() {
    var url = $(location).attr('href');
    url = url + "&toPDF=1&to_pdf=1";
    window.open(url);
}

function clearProduct() {
    console.log('Czyszczenie wybranego produktu');
    $('#productId').val('');
    $('#productName').val('');
	console.log('Gotowe!');
}

function selectProduct() {
    open_popup('EcmProducts', 600, 400, '', true, false, {'call_back_function': 'set_return', 'form_name': 'AnalysisProductSale', 'field_to_name_array': {'id': 'productId', 'name': 'productName'}}, 'single', true);
}

function selectAccount() {
    open_popup('Accounts', 600, 400, '', true, false, {'call_back_function': 'set_return', 'form_name': 'AnalysisProductSale', 'field_to_name_array': {'id': 'accountId', 'name': 'accountName'}}, 'single', true);
}

function clearAccount() {
    console.log('Czyszczenie zaznaczonego kontrahenta');
    $('#accountId').val('');
    $('#accountName').val('');
}


google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);



function drawChart() {
	var a = new Array();
	var html = "";
	var table = document.getElementById("myTable");
	for (var i = 0, row; row = table.rows[i]; i++) {
		a[i] = new Array();
		for (var j = 0, col; col = row.cells[j]; j++) {
			a[i][j]=row.cells[j].textContent;
			if(j>0 && i > 0){
				a[i][j] = a[i][j].replace(".", "").replace(".", "");
				a[i][j] = parseFloat(a[i][j].replace(",", "."));
			}
			
		}
	}
	// Calculate the width and height of the Array
	var w = a.length ? a.length : 0,
	 h = a[0] instanceof Array ? a[0].length : 0;

	// In case it is a zero matrix, no transpose routine needed.
	if(h === 0 || w === 0) { t=[]; }

	/**
	* @var {Number} i Counter
	* @var {Number} j Counter
	* @var {Array} t Transposed data is stored in this array.
	*/
	var i, j, t = [];
	// Loop through every item in the outer array (height)
	for(i=0; i<h-1; i++) {
		// Insert a new row (array)
		t[i] = [];
		// Loop through every item per item in outer array (width)
		for(j=0; j<w-1; j++) {
			// Save transposed data.
			t[i][j] = a[j][i];
		}
	}

  var data = google.visualization.arrayToDataTable(t);
  	formatter = new google.visualization.NumberFormat({
		suffix: ' zł',
		fractionDigits: '2',
		decimalSymbol: ',',
		groupingSymbol: '.',
	});
	for (i = 1; i < data.getNumberOfColumns(); i++) {  
		formatter.format(data, i);
	}
  var options = {
    title: 'Wykres porównawczy',
    
  };
  var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
  chart.draw(data, options);
}