(function($) {

    $(function() {

        function updateProvinceInput(countryInput) {
            var provinceLabel = countryInput.closest('label').siblings('label.province');
            if(provinceLabel.length != 1)
                return;

            if(countryInput.val() == 'Canada') {
                provinceLabel.find('input[type=text]').attr('disabled', 'disabled').stop(true, true).hide();
                provinceLabel.find('select').removeAttr('disabled').fadeIn();
            } else {
                provinceLabel.find('input[type=text]').removeAttr('disabled').fadeIn();
                provinceLabel.find('select').attr('disabled', 'disabled').stop(true, true).hide();
            }
        }

        $('#membersArea').enableForms(function() {
            var form = $(this);

            // clear error state
            form.find('label .error').remove();
            form.find('.selector.highlight, label.highlight').removeClass('highlight');
            form.find('.tupleHighlight').removeClass('tupleHighlight');

            form.find('button[type=submit]:first').each(function() {
                $(this).prev('span.error').remove();
                $(this).before('<span class="throbber"></span>');
            });
        }, function(success, error) {
            var form = $(this);

            if(error == null) {
                // handle success
                var successBox = form.children('.success:first');
                if(successBox.length > 0) {
                    successBox.siblings().remove();
                    successBox.fadeIn().trigger('contentchanged');
                    successBox.find('a').focus(); // give focus for keyboard usage
                }

                // notify of success
                form.trigger('action', success);
            } else {
                if(typeof(error) == "string" && (error == 'Member login required' || error == 'Ouverture de session requise'))
                    form.trigger('memberloginrequest');

                // if error is simple string, display as special case
                var generalError = ($('body').hasClass('lang_fr') ? 'S\'il vous plaît corriger les erreurs ci-dessus' : 'Please correct highlighted fields');
                if(typeof(error) == "string") {
                    generalError = error;
                    error = {}; // no errors to display on fields
                }

                form.find('label').each(function() {
                    var label = $(this);
                    var inputs = label.find('input[name]:not(:hidden), select[name], textarea[name]');
                    inputs.each(function() {
                        var name = $(this).attr('name');
                        if(error[name] != null) {
                            label.addClass('highlight');
                            if(label.hasClass('long'))
                                $('<span class="error"></span>').appendTo(label).hide().fadeIn().text(error[name]);

                            // display one error per label
                            return false;
                        }
                    });
                });

                form.find('.selector').each(function() {
                    var label = $(this);
                    var input = label.find('input[name]:checkbox, input[name]:radio').eq(0);
                    if(input.length > 0) {
                        var name = input.attr('name').replace(/\[\]$/, '');
                        if(error[name] != null) {
                            label.addClass('highlight');
                        }
                    }
                });

                form.find('.tuple').each(function() {
                    var tuple = $(this);
                    var input = tuple.find('input[name], select[name]');
                    input.each(function() {
                        // find the first input that has an error
                        var name = $(this).attr('name');
                        if(error[name] != null) {
                            tuple.addClass('tupleHighlight');
                            return false;
                        }
                    })
                });

                form.find('button[type=submit]:first').each(function() {
                    $(this).prev('span.throbber').remove();
                    $('<span class="error"></span>').insertBefore(this).hide().fadeIn().text(generalError);
                });

                form.trigger('contentchanged');
            }

            return false;
        }).delegate('fieldset.address label.country select', 'change', function() {
            var countryInput = $(this);
            updateProvinceInput(countryInput);
        }).find('fieldset.address label.country select').each(function() {
            var countryInput = $(this);
            updateProvinceInput(countryInput);
        });

        $('#membersArea').delegate('form[data-redirect]', 'action', function() {
            // delay redirect to allow success animation, if any
            var form = $(this);
            setTimeout(function() {
                var dest = form.attr('data-redirect');
                if(dest == '')
                    location.reload();
                else
                    location.href = dest;
            }, 300);
        });
    });

})(jQuery)
