/**
 * JS per il widget LocationsReport.
 *
 * @author Daniele De Nobili
 * @copyright (c) Web Agency Meta Line - metaline.it
 */

/*jslint plusplus: true, browser: true, indent: 4, unparam: true */


// Controllo delle dipendenze
if (window.google === undefined || window.google.visualization === undefined) {
	throw 'Google JS Api not loaded!';
}

if (window.jQuery === undefined) {
	throw 'jQuery not loaded!';
}

if (window.widget === undefined || window.widget.locationsreport === undefined) {
	throw 'Options not defined!';
}

(function ($, google, o) {
	'use strict';

	var content = $('#locationsreport-chart'),
		table,
		chart,
		data;

	/**
	 * Prepara il grafico
	 */
	function prepareChart() {
		if (data === undefined || data.stats === undefined) {
			return;
		}

		table = google.visualization.arrayToDataTable(data.stats);
		chart = new google.visualization.PieChart(content.get(0));
	}

	/**
	 * Disegna il grafico
	 */
	function drawChart() {
		if (data === undefined) {
			return;
		}

		chart.draw(table, {
			width: 450,
			height: 250,
			chartArea: {
				left: 0,
				top: 30,
				width: '100%',
				height: '100%'
			}

		});
	}

	/**
	 * Inizializza l'applicazione.
	 */
	function onLoad() {
		$.ajaxSetup({
			timeout: 30000
		});

		$.getJSON(o.url, function (response) {
			content.removeClass('loading');

			if (response.error) {
				content.addClass('alert').text(response.error);

				return;
			}

			data = response;
			prepareChart();
			drawChart();
		});
	}

	google.setOnLoadCallback(onLoad);
}(window.jQuery, window.google, window.widget.locationsreport));
