Change theme_entityreference() to pass along the field name. Change _theme_entityreference_pageshow() to attach an onclick handler and other variables. Add entityreference_assemble_form_state_into_field() and _entityreference_onclick().