﻿function renameInputs() {
    $('div.multi').each(function() {
        var $t = $(this);
        var $f = $t.find('td input[type=radio]:first');

        if ($f.length) {
            var n = $f.attr('name');
            var p = n.indexOf('_');
            if (p > 1) n = n.substring(0, p);
            $t.find('tr').each(function(i) {
                //              $(this).find('input[type=radio]').attr('name', n + '_' + i.toString());
                var r = n + '_' + i.toString();
                $(this).find('input[type=radio][name!=' + r + ']').each(function() {
                    var price = $(this).attr('price');
                    if (price) price = ' price="' + price + '"';
                    $(this).replaceWith('<input type="radio" name="' + r + '" value="' + $(this).attr('value') + '"' + price + ' />');
                });
                bindPriceUpdate($(this));
            });
        }

        $f = $t.find('td input[type=checkbox]:first');

        if ($f.length) {
            var n = $f.attr('name');
            var p = n.indexOf('_');
            if (p > 1) n = n.substring(0, p);
            $t.find('tr').each(function(i) {
                $(this).find('input[type=checkbox]').attr('name', n + '_' + i.toString());
            });
        }
    });

    $('.each').each(function() {
        var $t = $(this);
        var $f = $t.find('input[type=radio]:first');
        if ($f.length) {
            var n = $f.attr('name');
            var p = n.indexOf('_');
            if (p > 1) {
                n = n.substring(0, p);
                $t.find('input[type=radio]').attr('name', n);
            }
        }
    });
}

function bindPriceUpdate($o) {
    $o.find('input[type=text][price]').keyup(updateTotal);
    $o.find('input[type=radio][price]').click(updateTotal);
    $o.find('input[type=checkbox][price]').click(updateTotal);
}

function onDifferent() {
    var $q = $(this).parents('.question');
    var $m = $q.find('div.multi');
    var $e = $q.find('.each');
    if ($(this).attr('checked')) {
        $m.append('<table></table>');
        var $t = $m.find('table');
        var names = $('body').data('names');
        var j;
        for (j = 0; j < names.length; j++)
            $t.append('<tr><td>' + names[j] + '</td><td>' + $e.html() + '</td></tr>');
        bindPriceUpdate($t);
        $e.empty();
    }
    else {
        if (!confirm('Are you sure you want to consolidate your answers? Per person values will be lost')) return false;
        var $t = $m.find('table');
        $t.empty();
        $t.remove();
        $e.html($q.data('each'));
        bindPriceUpdate($e);
    }
    renameInputs();
    updateTotal();
    return true;
}

function onAdd() {
    var $q = $(this).parents('.question');
    var $t = $q.find('table');
    
    $t.append('<tr>' + $q.data('tr') + '</tr>');
    $t.find('tr:last-child a.remove').click(onRemove);
    $t.find('tr:last input.ident').change(onIdent);

    $('body').data('names').push('');

    if ($t.find('tr').length == 3) {
        $('#questions > div.question').each(function() {
            var id = $(this).attr('id').substring(1);
            var $d = $(this).find('div.diffans');
            $d.html('<input type="checkbox" name="s' + id + '" /> Click to choose a different answer for each registrant. Otherwise, the answer you give applies to all.');
            $d.find('input[type=checkbox]').click(onDifferent);
            $(this).find('div.multi').show();
        });
    }
    else {
        $('#questions > div.question').each(function() {
            var $t = $(this);
            if ($t.find('div.diffans input[type=checkbox]').attr('checked')) {
                $t.find('div.multi table').append('<tr><td></td><td>' + $t.data('each') + '</td></tr>');
                bindPriceUpdate($t.find('div.multi table tr:last-child'));
            }
        });
    }

    renameInputs();
    updateTotal();

    $t.find('tr:last input:first').focus();

    return false;
}

function onRemove() {
    var $tr = $(this).parents('tr');
    var $table = $tr.parent();
    var rows = $table.find('tr').length - 1;

    if (rows < 2) {
        alert('You must have at least one registrant!');
        return false;
    }

    if (!confirm('Remove this registrant?')) return false;

    var i = $table.children().index($tr) - 1;

    var $rem = $('div.multi table').find('tr:eq(' + i.toString() + ')');
    $rem.empty();
    $rem.remove();
   
    $tr.empty();
    $tr.remove();

    var names = $('body').data('names');
    names.splice(i, 1);

    if (rows == 2) {
        $('.each').each(function() {
            var $t = $(this);
            var $q = $t.parents('.question');
            var $m = $q.find('div.multi');
            $q.find('div.diffans').empty();
            $t.append($m.find('tr:first td:eq(1)').contents());
            $m.empty();
            $m.hide();
            $t.show();
        });
    }

    renameInputs();
    updateTotal();

    return false;

}

function onIdent() {
    var $tr = $(this).parents('tr');
    var i = $tr.parent().children().index($tr) - 1;
    var names = $('body').data('names');

    names[i] = '';
    $tr.find('input.ident').each(function() {
        if (names[i]) names[i] += ' ';
        names[i] += $(this).val();
    });

    $('#questions > div > div.multi > table tr:nth-child(' + (i + 1).toString() + ') > td:first-child').text(names[i]);
}

function onProceed() {
    var valid = true;
    var regexemail = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
    var $o;

    $('input[type=text].reqd').each(function() {
        if ($(this).val() == '') {
            $(this).addClass('invalid');
            valid = false;
        }
        else
            $(this).removeClass('invalid');
    });

    $('select.reqd').each(function() {
        if ($(this).val() == '') {
            $(this).addClass('invalid');
            valid = false;
        }
        else
            $(this).removeClass('invalid');
    });

    $('input[type=checkbox].reqd:checked').removeClass('invalid');
    $o = $('input[type=checkbox].reqd:not(:checked)');
    if ($o.length) {
        valid = false;
        $o.addClass('invalid');
    }

    $('input[type=radio]').removeClass('invalid');
    $('input[type=radio]:not(:checked)').each(function() {
        if (!$('input[type=radio][name=' + $(this).attr('name') + ']:checked').length) {
            valid = false;
            $(this).addClass('invalid');
        }
    });

    $('input.email').each(function() {
        var v = $(this).val();
        if (!$(this).hasClass('reqd') && val == '') return;
        if (regexemail.test($(this).val()))
            $(this).removeClass('invalid');
        else {
            $(this).addClass('invalid');
            valid = false;
        }
    });

    var num = $('body').data('names').length;

    $('div.question[avail]').each(function() {
        var avail = $(this).attr('avail');

        if (avail == 'choice') {
            var $q = $(this);
            $q.find('div.unavail').each(function() {
                var $u = $(this);
                var t = 0;
                var cid = $u.attr('id').substring(7);
                $q.find('input[value=' + cid + ']:checked').each(function() {
                    if ($(this).attr('name').indexOf('_') == -1)
                        t += num;
                    else
                        t++;
                });
                if (t > 0 && t > ($u.attr('avail') * 1)) {
                    $u.show();
                    valid = false;
                }
                else {
                    $u.hide();
                }
            });
        }
        else {
            var t = 0;
            var q;
            $(this).find('input[type=text].qty').each(function() {
                q = $(this).val();
                if (!isNaN(q)) t += q * 1;
            });
            t += $(this).find('input[type=checkbox][name^=a]:checked').length;
            if ($(this).find('div.diffans input[type=checkbox]:checked').length) t *= num;
            if (t > 0 && t > (avail * 1)) {
                $(this).find('div.unavail').show();
                valid = false;
            }
            else
                $(this).find('div.unavail').hide();
        }
    });

    $('div.question[shavail]').each(function() {
        var $q = $(this);
        var $ua = $q.find('div.unavail');
        var t = 0;
        $ua.find('div').each(function() {
            var $u = $(this);
            var p = 0;
            var cid = $u.attr('id').substring(7);
            var s = $u.attr('share') * 1;
            var a = $u.attr('partavail');
            $q.find('input[value=' + cid + ']:checked').each(function() {
                if ($(this).attr('name').indexOf('_') == -1)
                    p += num;
                else
                    p++;
            });
            if (p > a) {
                t += Math.ceil((p - a) / s);
            }
        });
        if (t > ($q.attr('shavail') * 1)) {
            $ua.show();
            valid = false;
            Recaptcha.reload();
        }
        else
            $ua.hide();
    });

    var $ca = $('#captchaauth');
    if ($ca.length) {
        if ($ca.val() == '') {
            var resp = $.ajax({
                type: 'POST',
                data: {recaptcha_challenge_field: Recaptcha.get_challenge(), recaptcha_response_field: Recaptcha.get_response()},
                url: '/registrations/captchavalidate',
                async: false
            }).responseText;
            if (resp == 'invalid') {
                valid = false;
                Recaptcha.reload();
                $('#captchamessage').text('Invalid captcha');
            }
            else {
                $ca.val(resp);
                $('#captchamessage').empty();
                $('#captchaph').empty();
            }
        }
    }

    if (!valid) alert('Please fix issues with this form! Scroll up to find fields that require your attention.');
    return valid;
}

function updateTotal() {
    var tot = 0;

    var num = $('body').data('names').length;

    $('.each input[type=text][price]').each(function() {
        var v = $(this).val();
        if (!isNaN(v)) {
            tot += num * v * $(this).attr('price');
        }
    });

    $('.each input[type=checkbox][price]:checked').each(function() {
        tot += num * $(this).attr('price');
    });

    $('.each input[type=radio][price]:checked').each(function() {
        tot += num * $(this).attr('price');        
    });

    $('.multi input[type=text][price]').each(function() {
        var v = $(this).val();
        if (!isNaN(v)) {
            tot += v * $(this).attr('price');
        }
    });

    $('.multi input[type=checkbox][price]:checked').each(function() {
        tot += 1 * $(this).attr('price');        
    });

    $('.multi input[type=radio][price]:checked').each(function() {
        tot += 1 * $(this).attr('price');        
    });

    if (tot == Math.floor(tot))
        $('#totprice').text('$' + tot);   
    else
        $('#totprice').text('$' + tot.toFixed(2));

    $('#pricecheck').val(tot.toFixed(2));

    onUpdate();
}

function stripVals(str) {
    return str.replace(/\svalue=\s*("[^"]*"|[^"][^\s]*)/ig, ' value=""').replace(/(<textarea[^>]*>)[^<]*(<\/textarea>)/ig, '$1$2').replace(' checked="checked"','').replace(' selected','');
}

function storeEmpty($where, name, $src) {
    var $n = $src.clone();
    $n.find('input[type=text]').val('');
    $n.find('textarea').val('');
    $n.find('select').val('');
    $n.find('input[type=checkbox]:checked').attr('checked', false);    
    $where.data(name, $n.html());
}

function InitReg() {
    var $proceed = $('#proceed');

    $proceed.removeClass('nojs');    

    $proceed.html('<input id="submitreg" type="submit" value="Submit" />');

    $('div.unavail').hide();

    $('#regform').submit(onProceed);

    if ($('input[price]:first').length) {
        $proceed.prepend('<div id="total">Total: <span id="totprice">$0</span></div>');
    }

    $('a.add').click(onAdd);


    $('a.remove').each(function() {
        storeEmpty($(this).parents('.question'), 'tr', $(this).parents('tr'));
    });

    $('a.remove').click(onRemove);

    $('.each').each(function() {
        storeEmpty($(this).parents('.question'), 'each', $(this));
    });

    $('div.diffans input[type=checkbox]:checked').each(function() {
        $(this).parents('.question').find('.each').empty();
    });

    $('div.diffans input[type=checkbox]').click(onDifferent);

    $('input.ident').change(onIdent);

    bindPriceUpdate($('#questions > div.question'));

    updateTotal();

}
