$(function() {
    // Correct for Firefox's refresh functionality
    // Set the correct visibility for the student info section
    var student = $('#form_student');
    if(student.attr('checked')) {
        $('#student_info').show();
    }
    // Set the correct class and maxlength for the Student ID
    var sid = $('#form_sid');
    if(sid.attr('value') == '') {
        sid.attr('value', 'Example: 950-12-3456');
    }
    if(sid.attr('value') == 'Example: 950-12-3456') {
        sid.attr('maxlength', '100');
        sid.addClass('example');
    }
    else {
        sid.attr('maxlength', '11');
        sid.removeClass('example');
    }

    // Setup the form submit
    $('#signup').bind('submit', function() {
        if($('#sid')[0].value == 'Example: 950-12-3456') {
            $('#sid')[0].value = '';
        }
    });

    // Setup the student menu
    $('#affiliation [name=affiliation]').bind('click', function(e) {
        var student_info = $('#student_info');
        student_info.hide();
        switch(this.value) {
            case 'student':
                student_info.show();
                break;
            default:
                break;
        }
    });

    // Setup the Student ID
    sid.bind('focus', function() {
        if(this.value == 'Example: 950-12-3456') {
            this.value = '';
            var self = $(this);
            self.removeClass('example');
            self.attr('maxlength', '11');
        }
    });
    sid.bind('blur', function() {
        if(this.value == '') {
            this.value = 'Example: 950-12-3456';
            var self = $(this);
            self.addClass('example');
            self.attr('maxlength', '100');
        }
    });
    sid.bind('keypress', function(e) {
        // Don't let them press a non-numeric key
        if(e.which != 13 && e.which != 0  && e.which != 8 && (e.which < 48 || e.which > 57)) {
            return false;
        }
    });
    sid.bind('keyup', function() {
        // If the string is 3 characters long, add a hypen
        if(this.value.length == 3) {
            this.value += '-';
        }
        // If the string is 6 characters long (including the last hypen), add a hypen
        if(this.value.length == 6) {
            this.value += '-';
        }
    });
    sid.bind('change', function() {
        var value = this.value.replace(/-/g,'');
        if(this.value.length > 5) {
            this.value = value.substr(0,3)+'-'+value.substr(3,2)+'-'+value.substr(5);
        }
        else if(this.value.length > 2) {
            this.value = value.substr(0,3)+'-'+value.substr(3);
        }
    })
});