$j(function(){ loadGraph(configURL); });

function loadGraph(configURL) {
	$j.getJSON(configURL,function(json){			
		loadHTML(json);
	});
}

function loadHTML (json) {
	$j(json.target).load('cf_elements/graph/structure.htm',function(){ setGraph(json); });
}

var decSep = '.';
var thouSep = ',';

function setGraph(json) {
	//remove any non-digits from the values and convert to a number			
	var currentValue = Number(json.current.replace(/[^\d\.]/g,'')); //current value
	var goalValue = Number(json.goal.replace(/[^\d\.]/g,'')); // goal value
	var startValue = Number(json.start.replace(/[^\d\.]/g,'')); // start value
	
	var usePercent = json.display_current_as_percentage;
	var percentValue = Math.round(currentValue/goalValue * 100); //find current percent of total
	
	if (json.useCSS3 == "y") { $j(json.target).addClass('css3') };
	
	//display beginning and end values
	$j('.fsGraphGoal',json.target).html(json.prefix + json.goal + json.suffix + "&nbsp;");
	$j('.fsGraphStart',json.target).html(json.prefix + json.start + json.suffix + "&nbsp;");
	
	//grab font size to use for overlap checking
	var fontSize = Number($j('.fsGraph',json.target).css('font-size').replace(/[^\d\.]/g,''));

	var graphHeight = $j('.fsGraph',json.target).height();
	var overFlow = false;
	var barHeight;

	//if barHeight > graphHeight it's an overflow state (current value is greater than goal value)
	if (currentValue > goalValue) {
		overFlow = true;
		var diff = Math.ceil(graphHeight * goalValue/currentValue);
		
		$j('.fsGraphGoal',json.target).css('top',graphHeight - diff+'px'); //set position of goal number
		$j('.fsGraphFill',json.target).css('height',diff +'px' ); //reduce the fill height to allow for the overflow
		$j('.fsGraphOver',json.target).css('bottom',diff+"px"); //postion overflow at top of fill bar
		$j('.fsGraphOver',json.target).css('height',graphHeight - diff+"px"); //set over flow height
		barHeight = graphHeight; // <-- bar height will always be the graph height if it's "overflowing"
	}else{
		barHeight = Math.ceil(currentValue/(goalValue/graphHeight));
	}
	
	if (json.animate_on_open) {
		//this is the animated version
		
		var countUp_time = json.countUp_time * 1000; //convert to milliseconds
		var heightCount = 0;
		
		var heightInt = barHeight/countUp_time * 16;
		var hVals = new Array();
		
		//cache the height values to use in the animation
		for (var i=0; heightCount < barHeight - heightInt; i++) {
			heightCount += heightInt;
			hVals[i] = heightCount;
		};

		if(usePercent){ //display current value as percentage
			var countInt = percentValue/countUp_time * 16;
			var countUp = 0;
			var currentPrefix = "";
			var currentSuffix = "%";
			currentValue = percentValue;
		}else{
			var countUp = startValue; //start current display value from the set start value
			var countInt = Math.ceil(currentValue/countUp_time * 16); //how much to increment the
			var currentPrefix = json.prefix;
			var currentSuffix = json.suffix;
		}

		var n = 0;
		var counting = setInterval( function(){
			if(countUp < currentValue - countInt){
				countUp = countUp + countInt; //this is where the number is incremented
				if(usePercent){ displayValue = Math.round(countUp); }else{ displayValue = addCommas(countUp); }
				$j('.fsGraphCurrent',json.target).html(currentPrefix + displayValue + currentSuffix + "&nbsp;");
					
					// if currentValue is too low move above start value
					if(hVals[n] < fontSize*1.5){
						$j('.fsGraph',json.target).addClass('fsGraphLowValue');
					}else{ $j('.fsGraph',json.target).removeClass('fsGraphLowValue'); }
					
					//move current value text under the line when nearing the top
					if(hVals[n] > (graphHeight/1.25)) { $j('.fsGraph',json.target).addClass('fsGraphOverhalf'); };				

					if(!overFlow){
						// move the text if it's close to the top
						if (hVals[n] > (graphHeight - fontSize*2)) {
							$j('.fsGraph',json.target).removeClass('fsGraphOverhalf').addClass('fsGraphOverlap');
						};
					}
				$j('.fsGraphMask',json.target).css('height',hVals[n] + "px");
				$j('.fsGraphCurrent',json.target).css('bottom',hVals[n] + "px");
				n++;
			
			}else{
				//reached the current value, stop the animation
				clearInterval(counting);
				// set the final values
				$j('.fsGraphCurrent',json.target).html(currentPrefix + addCommas(currentValue) + currentSuffix + "&nbsp");
				$j('.fsGraphMask',json.target).css('height',barHeight + "px");
				$j('.fsGraphCurrent',json.target).css('bottom',barHeight + "px");
				
				if (currentValue == goalValue) { //current number = goal, hide the current and add bold
					$j('.fsGraphCurrent',json.target).hide();
					$j('.fsGraphGoal',json.target).css('font-weight','bold');
				};
			}
		},16);
				
	}else{ //this is the static version
		//set the current value text
		if(json.display_current_as_percentage){
			$j('.fsGraphCurrent',json.target).html(percentValue + "%");
		}else{
			$j('.fsGraphCurrent',json.target).html(json.prefix + json.current + json.suffix + "&nbsp;");
		} 
		
		//set the current value position
		$j('.fsGraphCurrent',json.target).css('bottom',barHeight);
		// if currentValue is too low move above start value
		if(barHeight < fontSize*1.5){
			$j('.fsGraph',json.target).addClass('fsGraphLowValue');
		}else{ $j('.fsGraph',json.target).removeClass('fsGraphLowValue'); }
		
		//move current value text under the line when nearing the top
		if(barHeight > (graphHeight/1.25)) { $j('.fsGraph',json.target).addClass('fsGraphOverhalf'); };				

		if(!overFlow){
			// move the text if it's close to the top
			if (barHeight > (graphHeight - fontSize*2)) {
				$j('.fsGraph',json.target).removeClass('fsGraphOverhalf').addClass('fsGraphOverlap');
			};
		}
		$j('.fsGraphMask',json.target).css('height',barHeight); //set the fill height
	}		
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split(decSep);
	x1 = x[0];
	x2 = x.length > 1 ? decSep + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + thouSep + '$2');
	}
	return x1 + x2;
}


