$(document).ready(function() {
    
    function update_soe() {
        
        function hide_details() {
            $('#id_details').hide();
            $("label[for='id_details']").hide();
        }

        function show_details() {
            $('#id_details').show();
            $("label[for='id_details']").show();
            $("label[for='id_details']").addClass('required');
        }
        

        $('#id_details').children().remove().end();
        var soe_id = $('#id_source').val();

        if (typeof soe_id == 'undefined' || soe_id == '') {
            hide_details();
            return;
        }

        $.getJSON('/soe/json/details/' + soe_id, function(data) {
	    $('#id_details').append($('<option></option>').attr("value", '').text('Please Select'));
            $.each(data, function(key, value) {
                $.each(value, function(k, v) {
                    $('#id_details').append($('<option></option>').attr("value", k).text(v));
                });
            });

            if ($('#id_details').children().size() > 1) {
                show_details();
            }
            else {
                hide_details();
            }
            
            if (typeof OB_SOE_DETAIL_SELECTED == 'undefined') {
               var curr_sel = 0;
            }
            else {
                var curr_sel = OB_SOE_DETAIL_SELECTED;
                OB_SOE_DETAIL_SELECTED = undefined;
                $('#id_details').val(curr_sel);
            }
        });
    }

    $('#id_source').change(function (){
        update_soe();
    });
    update_soe();
    
});
