/* Create a dynamic thermometer 
TLB
April 14, 2011
*/
(function( $ ){
    $.fn.wmThermometer = function(options) {
	function addCommas(val){
	    return String(val).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"); 
	}
	
	return this.each(function() {
	    var tOptions = jQuery.extend( {
		currentVal: 50,
		goal: 100,
		maxHeight: 100,
		prepend: "$",
		goalText: "Goal: ",
		duration: 2000,
		easingType: "linear",
		startingValue: 0,
		useCommas: true
	    }, options);
	    var eltName = $(this).attr("id");
	    var pctComplete = ((tOptions.currentVal - tOptions.startingValue) / tOptions.goal);
	    if (pctComplete > 1.0) {
	    	pctComplete = 1.0;
	    }
	    var curHeight = (pctComplete * tOptions.maxHeight);
	    $(this).css("position", "relative");
	    formattedGoal = tOptions.goal;
	    if (tOptions.useCommas == true) {
		formattedGoal = addCommas(tOptions.goal);
	    }
	    $(this).html('<div class="thermometer"><div class="tOverlay"></div><div class="gauge"><div class="currentVal">' + tOptions.startingValue + '</div></div></div><div class="goal">' + tOptions.goalText + tOptions.prepend + '<span class="goalValue">'+formattedGoal+'</span></div>');
	    
	    container = $(this).children(".thermometer").first();

	    if (container.css("height") == "0px") {
		container.css("height", tOptions.maxHeight);
	    }
	    
	    gauge = container.children(".gauge").first();
	    
	    gauge.css("height", 0);
	    gauge.animate({
		height: curHeight
	    }, {
		duration: tOptions.duration,
		easing: tOptions.easingType,
		step: function(height) {
		    val = Math.ceil((height / tOptions.maxHeight) * tOptions.goal) + tOptions.startingValue;
		    if (tOptions.useCommas == true) {
			val = addCommas(val);
		    }
		    $(this).children(".currentVal").first().html(tOptions.prepend + val);
		},
		complete: function() {
		    val = tOptions.currentVal;
		    if (tOptions.useCommas == true) {
			val = addCommas(val);
		    }
		    $(this).children(".currentVal").first().html(tOptions.prepend + val);
		}
	    });
	});
    }
}) ( jQuery );
