var chart = new Object();


chart.toolTipBackground = '#70838c';
chart.toolTipBorderWidth = '2px';
chart.toolTipBorderColor = ' solid #ffffff';
chart.toolTipFontFamily = 'Trebuchet MS';
chart.toolTipFontColor = '#ffffff';
chart.toolTipFontWeight = 'normal';
chart.toolTipFontSize = '14px';
chart.toolTipLetterSpacing = '0.09em';
chart.toolTipPadding = '6px 12px 6px 12px';
chart.previousPoint=null;


config.loadComponents( {
	jquery:[
	  'flot/excanvas.compiled.js',
	  'flot/jquery.flot.js',
	  'flot/jquery.flot.orderBars.js',
	  'flot/jquery.flot.navigate.js'
	]
});

	
	/* *******************************************************
	  * START :::
	  *   on successful JSON request, plot the chart
	******************************************************* */
	chart.buildChart = function(settings) {
		
		if (settings['data'].data.graphType == 'bars') {
			options = {
				show_lines: false,
				show_bars: true,
				show_points: false,
				show_pies: false,
				min_xaxis: -1,
				auto_margin: 1
			}
			
		} else if (settings['data'].data.graphType == 'lines') {
			options = {
				show_lines: true,
				show_bars: false,
				show_points: settings['points'],
				show_pies: false,
				min_xaxis: 0,
				auto_margin: 0
			}
		}
	
	
	
			chart.suffixFormatter = function (val, axis) {
				
				dec = typeof(axis.tickDecimals) == 'undefined'?axis:axis.tickDecimals;
				if (typeof(axis.tickDecimals) != 'undefined') {
				if (val >= 100000000)
					return (val / 1000000) + " M";
				else if (val >= 10000000)
					return (val / 10000000) + " M";
				else if (val >= 1000000)
					return (val / 1000000) + " M";
				else if (val > 1000)
					return (val / 1000) + " K";
				else
					return val.toFixed(axis.tickDecimals) + "";
				} else {
					if (val >= 100000000)
						return (val / 100000000).toFixed(3) + " M";
					else if (val >= 10000000)
						return (val / 10000000).toFixed(3) + " M";
					else if (val >= 1000000)
						return (val / 1000000).toFixed(3) + " M";
					else if (val > 1000)
						return (val / 1000).toFixed(3) + " K";
					else
						return val.toFixed(0);
					
				}
			}
/*
		$.plot(chart.display, chart.data.data.metrics,{
			series: {
				stack: false,
				lines: { show: options.show_lines, fill: true, steps: true },
				bars: { show: options.show_bars, order: 1, barWidth: 0.01 }
			},
			points: { show: options.show_points },
			grid: { hoverable: true, clickable: true, autoHighlight: 1 },
			legend: { show: true, container: chart.legend, noColumns: 5 },
			xaxis: { ticks: chart.data.data.ticks },
			yaxis: { min: 0, tickFormatter: chart.suffixFormatter  }
		});
*/
		$.plot(settings['display'], settings['data'].data.metrics,{
			series: {
				stack: false,
				lines: { show: options.show_lines, fill: false },
				bars: { show: options.show_bars, order: 1, barWidth: 0.3 }
			},
			points: { show: options.show_points },
			grid: { hoverable: true, clickable: true, autoHighlight: 1 },
			legend: { show: true, container: settings['legend'], noColumns: 10 },
			xaxis: { ticks: settings['data'].data.ticks, autoscaleMargin: options.auto_margin },
			yaxis: { tickDecimals: 0, tickFormatter: chart.suffixFormatter },
			zoom: {
				animate: true,
				interactive: true
			},
			pan: {
				animate: true,
				interactive: true
			}
		});
		
		
		// Bind plot hover to tooltip
		settings['display'].bind("plothover", function (event, pos, item) {
			$("#x").text(pos.x.toFixed(2));
			$("#y").text(pos.y.toFixed(2));
				if (item) {
					if (chart.previousPoint != item.datapoint) {
						chart.previousPoint = item.datapoint;
						
						$("#tooltip").remove();
						var x = item.datapoint[0].toFixed(0);
						var y = item.datapoint[0].toFixed(0);
						//y = suffixFormatter(y,0);
						
						tipNum = chart.addCommas(item.datapoint[1]);
						
						textFormat = tipNum + '<br />' + item.series.label;
						
						chart.showTooltip( item.pageX, item.pageY, textFormat );
					}
				
				} else {
					$("#tooltip").remove();
					chart.previousPoint = null;            
				}
		});
			
			// Function for setting up Tooltips
			chart.showTooltip = function(x, y, contents) {
				$('<div id="tooltip">' + contents + '</div>').css( {
					'font-weight': chart.toolTipFontWeight,
					'font-family': chart.toolTipFontFamily,
					'font-size': chart.toolTipFontSize,
					'letter-spacing': chart.toolTipLetterSpacing,
					'text-align': 'left',
					color: chart.toolTipFontColor,
					position: 'absolute',
					display: 'none',
					top: y + 15,
					left: x + 15,
					'border-width': chart.toolTipBorderWidth,
					'border-style': 'solid',
					'border-color': chart.toolTipBorderColor,
					padding: chart.toolTipPadding,
					'background-color': chart.toolTipBackground
				}).appendTo("body").fadeIn(200);
			}
			
			chart.addCommas = function (nStr) {
				nStr += '';
				x = nStr.split('.');
				x1 = x[0];
				x2 = x.length > 1 ? '.' + x[1] : '';
				var rgx = /(\d+)(\d{3})/;
				while (rgx.test(x1)) {
				x1 = x1.replace(rgx, '$1' + ',' + '$2');
				}
				return x1 + x2;
			}

		

		chart.plotChoices = function(settings) {			
			var data = [];
			count = 0;
		
			if (settings['data'].data.graphType == 'bars') {
				options = {
					show_lines: false,
					show_bars: true,
					show_points: settings['points'],
					show_pies: false
				}
				
			} else if (settings['data'].data.graphType == 'lines') {
				options = {
					show_lines: true,
					show_bars: false,
					show_points: settings['points'],
					show_pies: false,
					min_xaxis: 0,
					auto_margin: 0
				}
			}
			
			settings['choices'].find("input").each(function () {
				var key = count;
				if ($(this).is(':checked') && settings['data'].data.metrics[key]) {
					data.push(settings['data'].data.metrics[key]);
				}
				
				count++;
			});
			
			if (data.length > 0) {
				$.plot(settings['display'], data,{
					grid: { 
						color: '#58543f',
						backgroundColor: { colors: ['#ebe9df','#ffffff'] },
						borderColor: '#e1dfd7',
						tickColor: '#e1dfd7',
						hoverable: true, 
						clickable: true 
					},
					series: {
						stack: false,
						lines: { 
							show: options.show_lines, 
							fill: false, 
							steps: false
						},
						bars: { 
							show: options.show_bars, 
							order: 1, 
							barWidth: 0.3 
						}
					},
					points: { show: settings['points'] },
					legend: { show: true, container: settings['legend'], noColumns: 5 },
					xaxis: { ticks: settings['data'].data.ticks },
					yaxis: { min: 0, tickFormatter: chart.suffixFormatter  },
					zoom: {
						animate: true,
						interactive: true
					},
					pan: {
						animate: true,
						interactive: true
					}
						});
					}
		}
		
		chart.plotChoices(settings);
		settings['choices'].find("input").click(function() {
			chart.plotChoices(settings)
		});

		
		// END bind
		
	}
	/* *******************************************************
	  * END ::: onDataReceived
	******************************************************* */
