var form_total_amount;

var jQueryButton = $j.fn.button;

$j(document).ready(function() {
    //setup the price.
    $j('.featured_article select[name!=account_id]')
        .change(setupPricing)
        .change();

    $j('.registration_checkbox')
        .change(setupPricing)
        .change();

    formname = 'registration_form';
    var event_id = $j('#' + formname + ' input[name=event_id]').val();
    var search_type = $j('#' + formname + ' .account_id').attr('datasource') == 'sam_all' ? 'sam_all' : 'accounts';
    var exclude_deceased_and_inactive = $j('#' + formname + ' .account_id').attr('exclude_deceased_and_inactive') === 'true' ? 'true' : '';
    $j('#' + formname + ' .account_name')
        .autocomplete({
            source: '/admin/ajax.user_autocomplete.php?type=' + search_type + '&get_type=true&event_id=' + event_id + '&exclude_deceased_and_inactive=' + exclude_deceased_and_inactive,
            minLength: 2,
            select: function(event, ui) {
                if (ui.item) {
                    $j('#' + formname + ' .account_id').attr('hidden_name', ui.item.label);
                    $j('#' + formname + ' .account_id').val(ui.item.id);
                    $j('#' + formname + ' .account_name').val(ui.item.label);
                    $j('#' + formname + ' .no_account_selected').hide();
                    $j('#' + formname + ' input[name=name]').val($j(this).val());
                    updatePricingTiers(ui.item.account_type_id);
                }
                return false;
            }
        })
        .bind('keypress', function(e) {
            if (13 === e.keyCode) {
                e.preventDefault();
                return false;
            }
        })
        .change(function(e) {

            var $account_name_input = $j(this);
            var $account_id_hidden_input = $j('#'+formname+' .account_id');

            var current_value = e.target.value.trim();
            var last_autocompleted_value = $account_id_hidden_input.attr('hidden_name');

            if (
                current_value !== last_autocompleted_value
            ) {
                // Setup to be a public registrant
                $j('#' + formname + ' .account_id').val(0);
                $j('#' + formname + ' .no_account_selected').show();
                $j('#' + formname + ' input[name=name]').val($account_name_input.val());
                $account_id_hidden_input.attr('hidden_name', '');
                updatePricingTiers(0);
            }
            return false;
        });

    //ADMIN ACCOUNT CHANGE

    //VALIDATION
    $j('form[name=registration_form]').submit(function() {
        msg = '';

        //must register for 1 person.
        num_selected = 0;
        $j('.featured_article select').each(function() {
            num_selected += $j(this)
                .find(':selected')
                .val();
        });
        $j('.registration_checkbox').each(function() {
            num_selected += $j(this).prop('checked') ? 1 : 0;
        });
        if (num_selected < 1) {
            msg += '• At least one person must be registered\n';
        }
        if ($j('textarea[name=notes]').val() == '' && enforce_notes) {
            msg += '• The Notes field is required\n';
        }

        //not signed up - need name, email, phone?
        if ($j('input[name=name]').length > 0 && !$j('input.account_name').length > 0) {
            if ($j('input[name=name]').val() == '') {
                msg += '• Your name is required\n';
            }
            if ($j('input[name=email_address]').val() == '') {
                msg += '• An email address is required\n';
            }
            if ($j('input[name=phone]').val() == '') {
                msg += '• A phone number is required\n';
            }
        }
        if (msg != '') {
            alert('Please fix the following to continue:\n\n' + msg);
            return false;
        }
        if (window.grecaptcha) {
            grecaptcha.execute();
            return false;
        }
        return true;
    });

    var getType = {};
    if ($j.buttonUI && getType.toString.call($j.buttonUI) === '[object Function]') {
        $j('.ev_back_to_cal').buttonUI({
            icons: {
                primary: 'ui-icon-arrowthick-1-w'
            },
            text: true
        });
        $j('.ev_share').buttonUI({
            icons: {
                primary: 'ui-icon-plusthick'
            },
            text: true
        });
        $j('.ev_print').buttonUI({
            icons: {
                primary: 'ui-icon-print'
            },
            text: true
        });
        $j('.ev_save_cal').buttonUI({
            icons: {
                primary: 'ui-icon-disk'
            },
            text: true
        });
        $j('.ev_show_on_fb').buttonUI({
            text: true
        });
    }

    function_after_monetary_form_changes = setupPricing;

    //turn off widgets and forms
    if (typeof CKEDITOR !== 'undefined') {
        CKEDITOR.config.removePlugins = 'forms,widgets,image2';
    }
});

window.onload = function() {
    $j('#inner_login_form').width($j('#login_area_above').outerWidth());
    $j('#login_area').height($j('#inner_login_form').outerHeight());
    moveAbsoluteBoxInside($j('#inner_login_form'), $j('#login_area'));
};

function updatePricingTiers(account_type_id) {
    if (tier_pricing) {
        for (var tier_name in tier_pricing[account_type_id]) {
            var $row = $j('tr[tier_name=' + tier_name + ']');

            var field = tier_pricing[account_type_id][tier_name];

            var $input = $row.find('.tier_input');

            if (!isNaN(parseFloat(field.price))) {
                $input.attr('price', field.price);
            }
            if ($input.attr('name') == 'registered_item') {
                $input.attr('value', field.tier_id).attr('price', field.price);
            }

            var $label = $row.find('.tier_price');
            if (field.price == 0) {
                $label.html('<em>Free</em>');
            } else {
                $label.html(field.price + ' Each');
            }
        }
        setupPricing();
    }
}

function setupPricing() {
    var total = 0;

    $j('.registration_select').each(function() {
        var this_amt = $j(this).val() * $j(this).attr('price');
        total += this_amt * 1;
    });

    $j('.registration_checkbox').each(function() {
        if ($j(this).prop('checked')) {
            this_amt = $j(this).attr('price');
            total += parseFloat(this_amt);
        }
    });

    if (form_total_amount && !isNaN(form_total_amount)) {
        total = total * 1 + form_total_amount * 1;
    }

    total = parseFloat(total);

    $j('#total_price').text(total.toFixed(2));
}

function recaptcha_callback(token) {
    var form$ = $j('#registration_form');
    form$.append("<input type='hidden' name='g-recaptcha-response' value='" + token + "' />");
    form$.get(0).submit();
}
