package
{
    import flash.display.*;
    import flash.events.*;
    import flash.utils.*;
    import flash.ui.ContextMenu;
    import flash.ui.ContextMenuItem;


    public class contextmenucrash_workaround extends Sprite
    {
        public function contextmenucrash_workaround()
        {
            this.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
        }

        private function enterFrameHandler(event:Event):void
        {
            // create a new ContextMenu every frame
            // (not a real life situation but the fastest way to demonstrate the crashing)
            create_new_contextmenu();
        }

        private function create_new_contextmenu():void
        {
            var cm:ContextMenu = new ContextMenu();

            cm.hideBuiltInItems();
            cm.addEventListener(ContextMenuEvent.MENU_SELECT, contextMenu_menuSelect);

            this.contextMenu = cm;
        }


        // global variable to avoid destroying/freeing the "current" this.contextMenu object
        private var crashworkaround_savecontextmenu : * = null;

        private function contextMenu_menuSelect(event:ContextMenuEvent):void
        {
            // workaround for the crash:
            // "save" (avoid freeing) the current ContextMenu because "this.contextMenu"
            // could be changed in the ENTER_FRAME event while the Flashplayer still shows
            // (and uses) the current one

            crashworkaround_savecontextmenu = this.contextMenu;


            // build a custom contextmenu
            var customItems:Array = new Array();

            var item:ContextMenuItem = new ContextMenuItem("NO crash now");
            customItems.push(item);

            this.contextMenu.customItems = customItems;
        }
    }
}