// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// Set the selected option to the one with the given value 
//  select: the HTML select control
//  option_value: the option value to find and mark as selected
function set_selected_option(select, option_value) {
	options = select.options;
	for (var i=0; i<options.length; i++) {
		if (options[i].value == option_value) {
			select.selectedIndex = i;
			break;
		}
	}
}

// Adds a new option to a +select+ control with the given text and value
function add_option(select, text, value) {
	option = new Option( text, value, false, false );
	select.options[select.options.length] = option;		
}

// Get the text of the current +select+ control selection
function select_option_text(select) {
	text = '';
	index = select.selectedIndex;
	if (index > -1) {
		option =  select.options[index];
		text = option.text;
	}
	return text;
}

function text_to_float(value) {
  return parseFloat(value.gsub(/[$,]/,''));
}

// Convert the number to a currency value (12.3 => '$ 12.30', 2 => '$ 2.00')
function number_to_currency(value, units) {
	val = parseFloat(value);
	if (units == undefined) units = ''; 
	return units + val.toFixed(2);
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if ( isNaN(num) ) num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num % 100;
	num = Math.floor(num/100).toString();
  if ( cents < 10 ) cents = "0" + cents;
  for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
  return (((sign)?'':'-') + '$ ' + num + '.' + cents);
}

/* shows and hides ajax indicator */
Ajax.Responders.register({
    onCreate: function(){
        if ($('ajax-indicator') && Ajax.activeRequestCount > 0) {
            Element.show('ajax-indicator');
        }
    },
    onComplete: function(){
        if ($('ajax-indicator') && Ajax.activeRequestCount == 0) {
            Element.hide('ajax-indicator');
        }
    }
});

function showAjaxIndicator() {
  if ($('ajax-indicator')) {
    Element.show('ajax-indicator');
  }
}

// Hide the AJAX Indicator on page load; the indicator is initially visible so that the spinner image is gauranteed 
// to be downloaded.
document.observe('dom:loaded', function(event) { if ($('ajax-indicator')) { $('ajax-indicator').hide(); } });

