/* Mixed use of jQuery $() object and custom gel() getElementById alias function */


var dtLinkText = "Get&nbsp;a&nbsp;progress&nbsp;bar&nbsp;at&nbsp;DollarTimes.com";
// DOM Element holders
//var bar, barframe, bargoal, barholder, barfill;

// Check if a value is a valid hex color value
function validColor(s)
{
	return (s.match(/#[a-f0-9]{6}/) == null) ? false : true;
}

function var_dump(o)
{
	for(var i in o)
	{
		console.log(i + '|' + o[i]);
	}
}

// Replace spaces with '&nbsp;'
function hardSpace(s)
{
	ns="";
	for(i=0;i<s.length;i++)
	{
		if(s.charAt(i)==' ') ns+='&nbsp;';
		else ns+=s.charAt(i);
	}
	return ns
}

// callback function for color picker
function callback(color) {
	// update color preview div
	gel('color_preview').style.backgroundColor = color;
	// set text input box to chosen color value
	$('#pb_color').attr('value', color);
	generate();
}

// Alias function for document.gelElementById
function gel(id)
{
	return document.getElementById(id);
}

// Generates / Updates Progress bar
function generate()
{
	//console.log('updating');

	// Grab user values
	var title = hardSpace(gel('pb_title').value); // hard spaces to avoid linebreaks
	var units = gel('pb_units').value;
	var unitPos = gel('pb_unit_right').checked ? 'right' : 'left';
	var barColor = gel('pb_color').value
	var orientation = gel('pb_orientation_ver').checked ? 'ver' : 'hor';
	
	var start = fixNumber( gel('pb_start').value );
	var goal = fixNumber( gel('pb_goal').value );
	var current = fixNumber( gel('pb_current').value );
	
	// Did the user supply valid numbers?
	if( isNaN(parseInt(start)) || isNaN(parseInt(goal)) || isNaN(parseInt(current)) ) {
		alert('Please enter Start, Goal and Current value as numbers.')
		return;
	}
	// parse these ints now, before it's too late!
	start = parseInt(start);
	goal = parseInt(goal);
	current = parseInt(current);
	
	if( (start<goal && current<start) || (goal<start && current>start) )
	{
		alert('Your current amount is not beteween the start and goal amounts! Automatically setting current value to your start value.')
		gel('pb_current').value = start;
		return;
	}
	// if user has overshot goal
	var curLab = gel('pb_current_label');
	if( (start<goal && current>goal) || (goal<start && current<goal) )
	{
		current = goal;
		curLab.style.color="red";
	}
	else
		curLab.style.color="#000";
		
	if(!validColor(barColor)) {
		alert("Please enter a valid color value, e.g. '#0000ee' . It's easiest to use the color picker.");
		return;
	}
	
	var displayCurrent = "";
	
	// UPDATE!
	// Title
	$(bartitle).html(title);
	// Start and Goal amounts
	if(unitPos=='left')
	{
		$(barstart).html(units + formatDollars(start).replace('$',''));
		$(bargoal).html(units + formatDollars(goal).replace('$',''));
		displayCurrent = units + ' ' + current;
	}
	else
	{
		$(barstart).html(formatDollars(start).replace('$','') + units);
		$(bargoal).html(formatDollars(goal).replace('$','') + units);
		displayCurrent = current + ' ' + units;
	}
	
	// Orientation, Fill & Color Progress Bar
	var widgetSize = ['250', '25'];
	
	var calcGoal = Math.abs(goal - start);
	var calcCurrent = Math.abs(current - start);
	var fraction = calcCurrent / calcGoal;
	var percentage = (100 * fraction);
	var barPadding = (1 - fraction) * widgetSize[0];
	
	// Always update bar
	switch(orientation)
	{
		case 'ver' :
			$(barfill).height(percentage + '%');
			$(barfill).css('marginTop', barPadding + 'px');
		break;
		case 'hor':
		default:
			$(barfill).height('100%');
			$(barfill).width(percentage + '%');
			$(barfill).css('marginTop', '0px');
		break;
	}
	
	// Restyle widget if orientation has changed
	if($(bar).attr('orientation') != orientation) switch(orientation)
	{
		case 'ver' :
			$(bar).attr('orientation', 'ver');
			// style widget
			$(bar).width(widgetSize[1] + 'px'); // this is too small, but .frame expands widget
			$(barholder).width(widgetSize[1] + 'px');
			$(barholder).height(widgetSize[0] + 'px');
			$(barfill).width('100%');
			
			// style captions & link
			$(bargoal).remove().prependTo(barframe);
			//bar.insertBefore(bargoal, barframe);
			$(bargoal).css('cssFloat','none');
			$(barlink).css('cssFloat','none');
			$(barlink).html('DollarTimes.com');
		break;
		
		case 'hor' :
		default :
			$(bar).attr('orientation', 'hor');
			// style widget
			$(bar).width(widgetSize[0] + 'px');
			$(barholder).height(widgetSize[1] + 'px');
			$(barholder).width('');
			// style captions & link
			$(bargoal).remove().appendTo(barframe);
			//bar.removeChild(bargoal);
			//barframe.appendChild(bargoal);			
			$(bargoal).css('cssFloat','right');
			$(barlink).css('cssFloat','right');
			$(barlink).html(dtLinkText);
		break;
	}
	
	// mouseover tooltip text
	$(barholder).attr('title', (fraction<1) ? ("Current amount: " + displayCurrent + " (" + formatPercent(fraction) + " towards goal)") : (" Goal has been reached.") );
	// bar Color
	$(barfill).css('backgroundColor',barColor);

	// Output Code
	barEl = gel('pb_1');
	$('#pb_code').attr('value','<div class="dt_progress_bar" style="'+barEl.style.cssText+'">'+barEl.innerHTML+'</div>');
	
	
}

function loadElements()
{
}

/**************
 INITIALIZATION
 **************/

	$(document).ready(function()
	{
		// Element Identifiers
		// bar is the whole widget
		bar =  '#pb_1';
		$(bar).attr('orientation', 'hor'); // set default orientation

		// widget title
		bartitle =  '#pb_1 .title';

		// barframe is the frame around the bar and captions
		barframe =  '#pb_1 .frame';

		//start caption
		barstart = '#pb_1 .start';

		// bargoal is the goal caption
		bargoal =  '#pb_1 .goal';

		// barholder holds the colored bar
		barholder =  '#pb_1 .barholder';

		// barfill is the colored bar
		barfill =  '#pb_1 .fill';

		// barlink is the dollartimes link
		barlink =  '#pb_1 .dt_link';
		
		// Init event listeners
		$('input[type=text]').bind('blur', generate);
		$('input[type=radio]').bind('change', generate);
		
		// Init Color Picker
		if($('#colorpicker') && $('#pb_color'))
		{
			$('#colorpicker').farbtastic(callback);
		}
		// select code on focus
		$('#pb_code').bind('focus', function(){ $(this).select(); });
		
	});
