// Creating the global var that will store the original options from the server
var original_subject_select = null;

// Once the whole page is loaded...
$(document).ready(function() {
    // Store the original options from the server in the global var
    original_subject_select = $('#PaperThemeSubjectId').clone().removeAttr('id');
    
    // Creating the function that will handle hiding/showing the correct subjects
    var handler = function(event) {
        if ($('#ThemeSubjectEventId').val() == '' || $('#ThemeSubjectEventId').val() == '3') {
            // Clearing the value before hiding the control
            $('#PaperThemeSubjectId').val('');
            $('#subjectdiv').hide();
        } else {
            $('#subjectdiv').show();
            // Replacing the select with the original one
            $('#PaperThemeSubjectId').replaceWith(original_subject_select.clone().attr('id', 'PaperThemeSubjectId'));
            
            // Remove the options according to the selected event (hard-coded)
            if ($('#ThemeSubjectEventId').val() == '1') {
                $('#PaperThemeSubjectId optgroup[label*=2008], #PaperThemeSubjectId optgroup[label*=2010]').remove();
            } else if ($('#ThemeSubjectEventId').val() == '2') {
                $('#PaperThemeSubjectId optgroup:not([label*=2008])').remove();
            } else if ($('#ThemeSubjectEventId').val() == '3') {
                $('#PaperThemeSubjectId optgroup:not([label*=2010])').remove();
            }
            //If we have only one optgroup, shift its options to the lower level
            if ($('#PaperThemeSubjectId optgroup').size() == 1) {
                $('#PaperThemeSubjectId optgroup *').appendTo('#PaperThemeSubjectId');
                $('#PaperThemeSubjectId optgroup').remove();
            }
        }
    }
    
    // Calling the handler on load to show the right object at the very start
    handler();
    // Setting the handler to be called when the user changes the event
    $('#ThemeSubjectEventId').change(handler);
});

