<?php

class MEditor extends MDiv
{
    private $hidden;
    private $button;
    public $unload;
   
    public function __construct( $name='', $value='', $label = '', $width = '100%', $height = '250px', $plugins = '')
    {
//        parent::__construct( $name . '_editor', $value );
        parent::__construct( $name . '_editor', '');

        $this->hidden = new MHiddenField($name,$value);
        $this->button = new MButton($name . '_button', _M('Open Editor'));
        $this->button->addAttribute('onclick',"new dijit.Editor({height: '{$height}', extraPlugins: ['dijit._editor.plugins.AlwaysShowToolbar']}, dojo.byId('{$name}_editor')); dojo.query('#{$name}_button').orphan();");

        $this->width = $width;
        $this->height = $height;


 //       $plugins="['foreColor','hiliteColor',{name:'dijit._editor.plugins.FontChoice', command:'fontName', generic:true}]";
        $plugins= ($plugins != '') ? $plugins : "[{name:'dijit._editor.plugins.FontChoice', command:'fontName', generic:true}]";

        $this->page->addDojoRequire("dijit.Toolbar");
        $this->page->addDojoRequire("dijit.Editor");
        $this->page->addDojoRequire("dijit._editor.plugins.FontChoice");  // 'fontName','fontSize','formatBlock'
        $this->page->addDojoRequire("dijit._editor.plugins.TextColor");
           
        $this->addAttribute("dojoType", "dijit.Editor");
        $this->addAttribute("extraPlugins", $plugins);
//        $this->addAttribute("toolbar", 'null');

//$this->page->onLoad("dojo.require('dijit.Editor');");
//$this->page->onLoad("dojo.require('dijit._editor.plugins.FontChoice');");
//$this->page->onLoad("alert(dojo.byId('{$name}_editor').id);");

        $this->page->addJsCode("if (dijit.byId('{$name}_editor')) { dijit.byId('{$name}_editor').destroy();};");
        $this->page->onLoad("try {var {$name}_editor = new dijit.Editor({id: '{$name}_editor', height: '{$height}', extraPlugins: {$plugins}}, dojo.byId('{$name}_editor_div'));} catch (err) {console.log(err)}");
//        $this->page->onLoad("dijit.byId('{$name}_editor').postCreate();");

//$this->page->onLoad("alert('hhh');");
//        $this->page->onLoad("dojo.parser.parse(dojo.byId(\"{$name}_editor\"));");
        $this->page->onLoad("dijit.byId('{$name}_editor').setValue(dojo.byId('{$name}').value);");
        $this->page->onUnLoad("(dojo.byId('{$name}').value = dijit.byId('{$name}_editor').getValue(false)); dijit.byId('{$name}_editor').destroy();");
    }

    public function generate()
    {
        return parent::generate() . $this->hidden->generate();
    }
}

?>