var simpleEncoding = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

function encodeRE(s) { return s.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1') }
TRIM_BOTH = 0;
TRIM_LEFT = 1;
TRIM_RIGHT = 2;
function trim(v, c, t)
{
	if (!t) 
		var t = TRIM_BOTH;
	if (!c) 
		var c = '\\s';
	else 
		c = encodeRE(c);

	var re;

	if (t == TRIM_BOTH)
		re = new RegExp('^' + c + '+|' + c + '+$', 'g');
	else if (t == TRIM_LEFT) 
		re = new RegExp('^' + c + '+');
	else if (t == TRIM_RIGHT) 
		re = new RegExp(c + '+$');
	return v.replace(re, '');
}
String.prototype.trim = function(c) { return trim(this, c, TRIM_BOTH); };
String.prototype.ltrim = function(c) { return trim(this, c, TRIM_LEFT); };
String.prototype.rtrim = function(c) { return trim(this, c, TRIM_RIGHT); };

function simpleEncode(datasets,maxValue)
{
	var chartData = ['s:'];
	for (var i = 0;i < datasets.length;i++)
	{
		var currentSet = datasets[i];
		for(var j = 0;j < currentSet.length;j++)
		{
			var currentValue = currentSet[j];
			if (!isNaN(currentValue) && currentValue >= 0)
			{
				chartData.push(simpleEncoding.charAt(Math.round((simpleEncoding.length-1) * currentValue / maxValue)));
			}
			else
			{
				chartData.push('_');
			}
		}
		chartData.push(',');
	}
	return chartData.join('').trim(',');
}

function buildURL(graphData)
{
	buildLineGraph(graphData);
}

function buildBarGraph(graphData)
{
	var chart_url = "http://chart.apis.google.com/chart?cht=bvg&chs=" + graphData.size + "&chbh=" + graphData.barSizes + "&chd=" + simpleEncode(graphData.data, graphData.maxValue) + "&chl=" + graphData.bottom + "&chdl=" + graphData.labels + "&chco=" + graphData.colors;
	
	if(graphData.showAxisNumbers != null)
	{
		var axisLabelsCount = 3;
		var increments = Math.round(graphData.maxValue / axisLabelsCount);
		
		chart_url += "&chxt=" + graphData.showAxisNumbers + "&chxl=0:|0";
		for(i=1; i <= axisLabelsCount; i++ )
		{
			var lv = increments * i;
			chart_url += "|" + lv;
		}
	}

	$("#" + graphData.id ).attr( 'src', chart_url );
}

function buildSmallLineGraph(graphData)
{

	var chart_url = "http://chart.apis.google.com/chart?cht=lc&chd=" + simpleEncode(graphData.data, graphData.max) + "&chxt=y&chxr=0,1," + graphData.max + "&chs=" +  graphData.size + "&chco=" + graphData.colors + "&chdl=" + graphData.labels + "&chl=" + graphData.bottom + "&chg=20,50,1,5&chf=c,ls,0,EEEEEE,0.1,FFFFFF,0.1";
	$("#" + graphData.id).attr( 'src', chart_url );
}

function buildLineGraph(graphData)
{

	var chart_url = "http://chart.apis.google.com/chart?cht=lc&chd=" + simpleEncode(graphData.data, graphData.max) + "&chxt=y&chxr=0,1," + graphData.max + "&chs=" +  graphData.size + "&chdl=" + graphData.labels + "&chl=" + graphData.bottom + "&chg=20,50,1,5&chf=c,ls,0,EEEEEE,0.1,FFFFFF,0.1";
	if(graphData.colors != "") {
		chart_url += "&chco=" + graphData.colors;
	}
	$("#" + graphData.id).attr( 'src', chart_url );
}