/**
 * JS per il widget VisitsReport.
 *
 * @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.visitsreport === undefined) {
	throw 'Options not defined!';
}

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

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

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

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

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

		chart.draw(table, {
			width: '100%',
			height: 180,
			title: data.title,
			colors: ['#058dc7', '#e6f4fa'],
			areaOpacity: 0.1,
			hAxis: {
				textPosition: 'in',
				showTextEvery: 5,
				slantedText: false,
				textStyle: {
					color: '#058dc7',
					fontSize: 10
				}
			},
			vAxis: {
				minValue: 0,
				maxValue: data.max,
				textPosition: 'in',
				showTextEvery: 5,
				slantedText: false,
				textStyle: {
					color: '#058dc7',
					fontSize: 10
				}
			},
			pointSize: 5,
			legend: 'none',
			chartArea: {
				left: 0,
				top: 30,
				width: '100%',
				height: '100%'
			}
		});
	}

	/**
	 * Scrive le metriche
	 */
	function drawMetrics() {
		if (data === undefined || data.metrics === undefined) {
			return;
		}

		var metrics = $('<div id="visitsreport-metrics" />'),
			vars = ['visits', 'visitors', 'pageviews', 'avgTimeOnSite', 'visitBounceRate', 'percentNewVisits'],
			code = '';

		$.each(vars, function (index, value) {
			if (data.metrics[value] === undefined) {
				return;
			}

			code += '<div class="visitsreport-metric"><span class="label">' + data.metrics[value][0] + '</span><strong>' + data.metrics[value][1] + '</strong></div>';
		});

		metrics.html(code).insertAfter(content);
	}

	/**
	 * 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();
			drawMetrics();
			drawChart();
		});
	}

	google.setOnLoadCallback(onLoad);

	// Responsivo
	$(window).resize(function () {
		drawChart();
	});

}(window.jQuery, window.google, window.widget.visitsreport));
