// called to test if thresholds mus be visible or not
// if it contains NaN values, display is not correct
Array.prototype.containsNaN = function() {

    for(var i = 1; i < this.length; i++)
    {
        if(isNaN(this[i]))
            return false;
    }

    return true;
} 

$( document ).ready(function() {
	
	/**
	 * // to change color palette
	Highcharts.setOptions({
	 colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4']
	});
	*/
	
	if(lang == 'fr') {
		Highcharts.setOptions({
			lang: {
				decimalPoint: ',',
				thousandsSep: ' '
			}
		});
	}

	if(input['viz_type'] === 'line') input['viz_type'] = 'spline';
	
	/** We must populate the chart 
	*	We get values from array
	*/
	var dates = [];
	var thresholds = [];
	var values = [];
	
	// we get values to populate charts 
	$('#indicator-values tr td').each(function()
	{
		if($(this).hasClass('date')) dates.push($(this).attr('data-date'));
		if($(this).hasClass('threshold')) thresholds.push(parseFloat($(this).attr('data-threshold')));
		if($(this).hasClass('value')) values.push(parseFloat($(this).attr('data-value')));
	});
	
	// if multiple values
	if ( $( "#indicator-values tr td p.indicator-multivalue" ).length ) {
		
		var jsonObj = [];
		var alabels = [];
		
		// we search for all labels available and populate labels array
		$('#indicator-values tr td p.indicator-multivalue span.value-label').each(function() {
			if($.inArray($(this).attr('data-label'), alabels) == -1) {
				alabels.push($(this).attr('data-label'));				
			}
		});
		
		// we loop again on labels
		for (i = 0; i < alabels.length; i++) {
			
			var labels_values = [];
			$('#indicator-values tr td p.indicator-multivalue span.value-label').each(function() {
				// if the label exists we take associated values, if the label does not exists, we set value to null
				if($(this).attr('data-label') === alabels[i]) {
					labels_values.push(parseFloat($(this).next("span.value-value").attr('data-value')));
				} else {
					// @todo gérer les valeurs nulles @simo
					//console.log($(this).parent().find('[data-label="'+alabels[i]+'"]').length);
					//if($(this).parent().find('[data-label="'+alabels[i]+'"]').length === 0) labels_values.push(null);
				}
				
				
			});
			item = {}
			item ["name"] = alabels[i];
			item ["data"] = labels_values.reverse();
			jsonObj.push(item);
			// console.log(labels_values);
		}

	
	// finally we add threshold as spline
	if(thresholds.length > 0) {
		item = {}
		marker = {}
		marker ['lineWidth'] = 2;
		marker ['lineColor'] = Highcharts.getOptions().colors[3];
		marker ['fillColor'] = 'white';
		item ["type"] = 'spline';
		item ["name"] = input['threshold_name'];
		item ["data"] = thresholds.reverse();
		item ["color"] = Highcharts.getOptions().colors[3],
		item ["dashStyle"] = 'ShortDot';
		item ["marker"] = marker;
		jsonObj.push(item);
	}

			

	
	} // closing test - if multiple values

	/**
	console.log(alabels);
	console.log(dates);
	console.log(thresholds);
	console.log(values);
	*/
	if(input['viz_vtype']  === 'unique') {
		
		// see api : http://api.highcharts.com/highcharts
		$('#main-chart-container').highcharts({
			title: {
				text: input['viz_title'],
				align: 'left',
				style:  { "color": "#777777" }
			},
			legend: {
				align: 'right',
				verticalAlign: 'top',
				layout: 'horizontal',
				// x: -100,
				y: 50
			},
			chart: {
				type: 'column',
				// margin: 75,
				marginTop: 120,
			},
			credits: false ,
			xAxis: {
				categories: dates.reverse()
			},
			yAxis: {
				title: {
					text: input['yAxis_title']
				}
			},
			labels: {
				items: [{
				   // html: '<?php echo $result_sdii[0]['sdii_name']; ?>',
					style: {
						left: '50px',
						top: '18px',
						color: (Highcharts.theme && Highcharts.theme.textColor) || 'black'
					}
				}]
			},
			tooltip: {
				headerFormat: '<b>{series.name}</b><br/>',
				pointFormat: '{point.y}',
			},
			series: [{
				type: input['viz_type'],
				name: input['serie_name'],
				data: values.reverse(),
				color: '#95CEFF'
			}, {
				type: 'spline',
				name: input['threshold_name'],
				data: thresholds.reverse(),
				color: Highcharts.getOptions().colors[3],
				dashStyle: 'ShortDot',
				visible: thresholds.containsNaN(),
				marker: {
					lineWidth: 2,
					lineColor: Highcharts.getOptions().colors[3],
					fillColor: 'white'
				}
			}]
		});
    
	} // closing input['viz_vtype']  === 'unique' test
	
	
		if(input['viz_vtype']  === 'multiple') {
		// see api : http://api.highcharts.com/highcharts
		$('#main-chart-container').highcharts({
			title: {
				text: input['viz_title'],
				align: 'left',
				style:  { "color": "#777777" }
			},
			legend: {
				align: 'right',
				verticalAlign: 'top',
				layout: 'horizontal',
				// x: -100,
				y: 50
			},
			chart: {
				type: 'column',
				// margin: 75,
				marginTop: 120,
			},
			credits: false,
			xAxis: {
				categories: dates.reverse()
			},
			yAxis: {
				title: {
					text: input['yAxis_title']
				},
				stackLabels: {
					enabled: true,
					style: {
						fontWeight: 'bold',
						color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
					}
				}
			},
			plotOptions: {
				column: {
					stacking: 'normal', // 'percent'
					dataLabels: {
						enabled: true,
						color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
						style: {
							textShadow: 'none'
						}
					}
				}
			},
			tooltip: {
				headerFormat: '<b>{point.x}</b><br/>',
				pointFormat: '{series.name}: {point.y} ({point.percentage:,.2f} %)',
				// valueDecimals: 2
			},
			series: jsonObj
		});
    
	} // closing input['viz_vtype']  === 'multiple' test
	
	
	// Generate Pie charts for a given year
	$('a.ajaxload').click(function( event ) {
		
		var cdate = $(this).attr('data-date');
		// console.log($(this).attr('data-pie'));
		
		var stack = $(this).attr('data-pie');
		var els = stack.split("||");
		var serie = [];
		for (i = 0; i < els.length -1; i++) {
			var a = [];
			tmp = els[i].split("=");
			// negative values are not included 
			// also possible to get absolute value Math.abs(parseFloat(tmp[1]))
			if(parseFloat(tmp[1]) > 0) {
				a.push(tmp[0]);
				a.push(parseFloat(tmp[1]));
				serie.push(a);
			}
			// console.log(tmp[0] + ' ' + tmp[1]);
		}
		
		$( "body" ).append('<div id="pie-chart-container"><div id="pie-chart"><\/div><\/div>');

		$('#pie-chart-container').colorbox({href:'#pie-chart-container', width:"800px", height:"600px", inline:true, open:true});
		
		 $('#pie-chart').highcharts({
			chart: {
				type: 'pie',
			},
			credits: false,
			title: {
				text: input['viz_title'] + ' ' +  cdate
			},
			subtitle: {
				text: input['yAxis_title'] + ' ' + input['negative_notice'] 
			},
			tooltip: {
				pointFormat: '<b>{series.name}</b> : {point.y} ({point.percentage:,.2f} %)'
			},
			plotOptions: {
				pie: {
					allowPointSelect: true,
					cursor: 'pointer',
					depth: 35,
					dataLabels: {
						enabled: true,
						format: '{point.name}<br /><span style="color:#8C8C8C">{point.percentage:,.2f} %</span>',
						style: {
							textShadow: 'none'
		                }
					}
				}
			},
			series: [{
				type: 'pie',
				name: input['yAxis_title'],
				data: serie
			}]
		});
		
		return false;
		
    }); // Closing onclick

});