
var checkboxes;
var radios;
var start_date;

//
// Money Fields
//
var decimalSep = (3/2).toString().charAt(1);
var non_money_chars_re    = new RegExp('[^\\-\\' + decimalSep + '\\d]', 'g');
var match_pounds_pence_re = new RegExp('^(\\-?\\d*)(\\' + decimalSep + '\\d{0,2}|)');

function string_to_money(str)
{
	// Remove any non money chars (only digits and .)
	str = str.replace(non_money_chars_re, '');

	// Chop string into an integer number of pence/cents, then convert to an integer base 10
	// (Done this way to avoid rounding errors)
	var matches = str.match(match_pounds_pence_re);
	if(matches)
	{
		var pounds = matches[1];
		var pence = matches[2].substr(1);
		if(pence.length < 2)
			pence += '00'.substr(0, 2 - pence.length);

		return parseInt(pounds + pence, 10); // Base 10 radix is important otherwise leading 0 would indicate octal by default
	}

	return 0;
}

function money_to_string(money)
{
	// This is done is a seemingly round about way to avoid rounding errors.
	var money_str = money.toFixed(0) +'';
	if(money_str.length < 3)
		money_str = '000'.substr(0, 3 - money_str.length) + money_str;

	return money_str.substr(0, money_str.length - 2) + decimalSep + money_str.substr(money_str.length - 2, 2);
}

function calculate_price()
{
    var monthly_total = 0;

    // myVI price
    var checked = radios.find(function(radio) {
        return radio.checked;
    });

    if(checked)
        monthly_total = string_to_money(checked.up().next().innerHTML);

    // VI data price
    checkboxes.each(function(checkbox) {
        if(checkbox.checked && ! checkbox.disabled)
            monthly_total += string_to_money(checkbox.up().next().innerHTML);
    });

    // Value Remaining from current subscription
    var value_remaining = 0;
    var val_remaining_row_today = $('value_remaining_today');

    if(val_remaining_row_today)
    {
        value_remaining = -string_to_money(val_remaining_row_today.down('td').next().innerHTML);

        if(start_date)
        {
            var val_remaining_row_renewal = $('value_remaining_renewal');
            if($F(start_date) == 'today')
            {
                val_remaining_row_today.style.display = '';
                if(val_remaining_row_renewal)
                    val_remaining_row_renewal.style.display = 'none';
            }
            else
            {
                val_remaining_row_today.style.display = 'none';
                if(val_remaining_row_renewal)
                {
                    val_remaining_row_renewal.style.display = '';
                    value_remaining = -string_to_money(val_remaining_row_renewal.down('td').next().innerHTML);
                }
                else
                    value_remaining = 0;
            }
        }
    }

    var num_months = [1, 3, 12];

    // Multi month discounts
    var discount  = $('discount').childElements();
    var discounts = [0, monthly_total/4, monthly_total*2];

    // Totals
    var total_price  = $('total_price').childElements();
    var total_to_pay = $('total_to_pay').childElements();
    var per_month    = $('per_month').childElements();
    var per_day      = $('per_day').childElements();

    num_months.each(function(months, index)
    {
        var total = monthly_total * months;

        total_price[index + 1].innerHTML = money_to_string(total);
        discount[index + 1].innerHTML    = discounts[index] > 0 ? '-' + money_to_string(discounts[index]) : 'n/a';

        var this_total_to_pay = total - discounts[index];
        var this_per_month    = this_total_to_pay / months;
        var this_per_day      = this_per_month / 30;

        this_total_to_pay -= value_remaining;
        if(this_total_to_pay < 0)
            this_total_to_pay = 0;

        total_to_pay[index + 1].innerHTML = '&pound;' + money_to_string(this_total_to_pay);
        per_month[index + 1].innerHTML = '&pound;' + money_to_string(this_per_month);
        per_day[index + 1].innerHTML = '&pound;' + money_to_string(this_per_day);
    });
}

function refresh_vi_data_selection(selected_checkbox)
{
    var includes = selected_checkbox.getAttribute('rel').split(',').without(selected_checkbox.getAttribute('value'));

    checkboxes.each(function(checkbox) {
        if(includes.include(checkbox.getAttribute('value')))
        {
            checkbox.checked = selected_checkbox.checked;
            if(selected_checkbox.checked)
                checkbox.disable();
            else
                checkbox.enable();
        }
    });
}

function vi_data_clicked(event)
{
    refresh_vi_data_selection(event.element());
    calculate_price();
}

function initialize()
{
    radios     = $$('#subs_table input[type=radio]');
    checkboxes = $$('.vi_data_table input[type=checkbox]');
    start_date = $('contract_start_date');

    radios.invoke('observe', 'click', calculate_price);
    checkboxes.invoke('observe', 'click', vi_data_clicked);

    if(start_date)
        start_date.observe('click', calculate_price);

    checkboxes.each(function(checkbox)
    {
        if(checkbox.checked)
            refresh_vi_data_selection(checkbox);
    });
    calculate_price();
}

document.observe('dom:loaded', function()
{
    initialize();
});
