var g_stbGoogleChartsApiIsLoaded = false;
var g_stbGoogleCharts = [];
(function ($, app) {
    $(document).ready(function () {
		google.charts.load('current', {packages: ['corechart']});
        google.charts.setOnLoadCallback(function() {
			g_stbGoogleChartsApiIsLoaded = true;
		});
		drawCharts();

		$(window).bind('resize', redrawCharts);
		$(window).bind('orientationchange', redrawCharts);
    });
}(window.jQuery, window.SupsysticTables));

function drawCharts(charts, id, onlyNew) {
	if(g_stbGoogleChartsApiIsLoaded) {
		charts = charts instanceof jQuery ? charts : jQuery('.supsystic-table-diagram'+(typeof onlyNew != 'undefined' ? ':not(.supsystic-drawn-chart)' : ''));
		if(typeof(id) == 'undefined') id = false;

		charts.each(function () {
			var $this = jQuery(this),
				params = {
					id: $this.data('id'),
					viewId: $this.data('view-id'),
					htmlId: $this.attr('id'),
					chartType: $this.data('charttype'),
					chartData: $this.data('chartdata')
				};

			if (params.chartType == 'google') {
				var chart = stbGetChartByViewId(params.viewId);
				if(id !== false) {
					googleChartRender(params, id);
				} else if(chart) {
					redrawCharts(null, chart);
				} else {
					googleChartRender(params);
				}

			} else if (params.chartType == 'jqplot') {
				jqplotChartRender(params.chartData, params.htmlId);
			} else if(params.chartType == 'zing') {
				zingChartRender(params.chartData, params.htmlId);
			}
			$this.prev('.supsystic-diagram-loader').hide();
			$this.addClass('supsystic-drawn-chart');
		});
	} else {
		setTimeout(function() {
			drawCharts(charts);
		}, 100);
	}
}

function jqplotChartRender(chartData, htmlId) {
	var lineChart = new window.SupsysticTables.LineChart(
		chartData.rangeData,
		chartData.selection.from.row,
		chartData.selection.from.col,
		chartData.selection.to.row,
		chartData.selection.to.col
	);

	lineChart.render(htmlId);
}

function googleChartRender(params, id) {
	if(typeof(id) == 'undefined') id = false;
	if(id !== false) {
		if(g_stbGoogleCharts.length <= id || params.htmlId != g_stbGoogleCharts[id].htmlId) return;
	}
	var options = params.chartData.options;


	params.data = new google.visualization.arrayToDataTable(params.chartData.rangeData);

	if (params.chartData.type != 'PieChart') {

		var rows = params.data.getNumberOfRows();
		var cols = params.data.getNumberOfColumns();

		var formatter = new google.visualization.NumberFormat({
		  pattern:'#,##%'
		});

		if (params.chartData.options.vAxis.format == "#.##%" || params.chartData.options.vAxis.format == "##.##%") {
			for (var i = 0; i < cols; i++) {
				formatter.format(params.data, i);
			}
		}

		if (params.chartData.options.hAxis.format == "#.##%" || params.chartData.options.hAxis.format == "##.##%") {
			for (var i = 0; i < rows; i++) {
				formatter.format(params.data, i);
			}
		}

	}

	params.chart = new google.visualization[params.chartData.type](document.getElementById(params.htmlId));
	params.chart.draw(params.data, options);

	if(options.legend && options.legend.position && options.legend.toggling
			&& options.legend.position != 'none' && options.legend.position != 'labeled' && options.legend.toggling == 'remove') {
		drawGoogleChartWithToggling(params.chart, params.data, options, params.chartData.type);
	}

	if(id === false) {
		g_stbGoogleCharts.push(params);
	} else {
		g_stbGoogleCharts[id] = params;
	}
}
function getGoogleChartDefColors() {
	return ['#3366cc', '#dc3912', '#ff9900', '#109618', '#990099', '#0099c6', '#dd4477', '#6a0', '#b82e2e', '#316395', '#3366cc', '#994499', '#22aa99', '#aaaa11', '#6633cc'];
}
function drawGoogleChartWithToggling(chart, chartData, options, chartId) {
	var serieRow = (chartId == 'PieChart'),
		nullFunc = function() {return null;},
		series = [],
		begin = serieRow ? 0 : 1,
		dataView = new google.visualization.DataView(chartData),
		colors = options.colors ? options.colors : getGoogleChartDefColors(),
		serieRow = (chartId == 'PieChart'),
		cntSeries = serieRow ? dataView.getNumberOfRows() : dataView.getNumberOfColumns();

	for(var i = 0; i < cntSeries; i++) {
		var key = i - begin;
		series.push({
			color: (key < 0 || typeof(colors[key]) == 'undefined' ? '#000000' : colors[key]),
			disabledColor: '#cccccc',
			visible: true,
			type: serieRow ? '' : dataView.getColumnType(i),
			label: serieRow ? '' : dataView.getColumnLabel(i),
			value: serieRow ? dataView.getValue(i, 1) : ''
		});
	}
	// Toggle visibility of data series on click of legend.
	google.visualization.events.addListener(chart, 'click', function (target) {
		var index = -1;
		if(target.targetID == 'legend') {
			index = cntSeries - 1;
		} else if (target.targetID.match(/^legendentry#\d+$/)) {
			index = parseInt(target.targetID.slice(12)) + begin;
		}
		if(index >= 0) {
			series[index].visible = !series[index].visible;
			var visibleSerieIndexes = serieRow ? [] : [0],
				values = [],
				colors = [];

			for(var i = begin; i < series.length; i++) {
				if(series[i].visible) {
					colors.push(series[i].color);
					visibleSerieIndexes.push(i);
					values[i] = series[i].value;
				} else {
					colors.push(series[i].disabledColor);
					if(serieRow) {
						visibleSerieIndexes.push(i);
						values[i] = 0;
					} else {
						visibleSerieIndexes.push({
							calc: nullFunc,
							type: series[i].type,
							label: series[i].label,
						});
					}
				}
			}
			var defColors = options.colors;
			options.colors = colors;
			if(serieRow) {
				dataView.setRows(visibleSerieIndexes);
				dataView.setColumns([0, {
					calc:(function (vals) {return function (data, row) {return vals[row];}})(values),
					type: 'number',
					label: '' }]);
				options.sliceVisibilityThreshold = 0;
			} else {
				dataView.setColumns(visibleSerieIndexes);
			}
			chart.draw(dataView, options);
			options.colors = defColors;
		}
	});
}
function redrawCharts(e, chart) {
	chart = chart ? chart : false;

	if(typeof chart == 'object' && chart.data && chart.chartData && chart.chartData.options) {
		chart.chart.draw(chart.data, chart.chartData.options);
	} else {
		for(var i = 0; i < g_stbGoogleCharts.length; i++) {
			g_stbGoogleCharts[i].chart.draw(g_stbGoogleCharts[i].data, g_stbGoogleCharts[i].chartData.options);
		}
	}
}
function stbGetChartByViewId(viewId) {
	for(var i = 0; i < g_stbGoogleCharts.length; i++) {
		if(g_stbGoogleCharts[i].viewId == viewId) {
			return g_stbGoogleCharts[i];
		}
	}
	return false;
}

function zingChartRender(chartData, chartId) {
	// type list: hbar3d, ring3d, pie3d
	// plot list: "bar", "cylinder", "cone", 'pyramid'
	if(!chartData.chartConfig['height']) {
		chartData.chartConfig['height'] = '300px';
	}
	jQuery('#' + chartId).zingchart(chartData.chartConfig);
}
