dojo.provide("pc.widget.editor_html_view");

dojo.require("dijit._editor._Plugin");
dojo.require("dijit.Dialog");

dojo.requireLocalization('pc.widget', 'editor');

dojo.declare("pc.widget.editor_html_view",
	dijit._editor._Plugin,
	{
		// Override _Plugin.useDefaultCommand... processing is handled by this plugin, not by dijit.Editor.
		useDefaultCommand: false,

        _initButton: function(){
			// Override _Plugin._initButton() to setup listener on button click

            this.command = "htmlView";
			this.editor.commands[this.command] = "HTML";
			this.inherited("_initButton", arguments);
			delete this.command;

            this.connect(this.button, "onClick", this._htmlView);
		},


		_htmlView: function()
        {
            this._initDialog();
            this.textarea.value = this.editor.getValue();
            this.dialog.show();
		},

        _initDialog: function () {
            if (!this.dialog)
            {
                this.dialog = new dijit.Dialog({}, dojo.doc.createElement('div'));

                var messages = dojo.i18n.getLocalization('pc.widget', 'editor', this.lang);

                //var buttonsHtml = '<button>Set</button><button>Set and continue</button>';
                var buttonsHtml = dojo.string.substitute('<button>${0}</button><button>${1}</button>', [
                   messages['Set'], messages['Set_and_continue']
                ]);
                this.dialog.attr('content', '<div class="html-view"><div><textarea></textarea></div><div class="buttons">' + buttonsHtml + '</div></div>');
                dojo.body().appendChild(this.dialog.domNode);
                this.dialog.startup();

                this.textarea = dojo.query("textarea", this.dialog.domNode).pop();
                var buttons = dojo.query("button", this.dialog.domNode);
                this.setBtn = buttons.pop();
                this.setAndHideBtn = buttons.pop();
                this.connect(this.setAndHideBtn, 'onclick', this._replaceValueAndHide);
                this.connect(this.setBtn, 'onclick', this._replaceValue);
            }
        },

        _replaceValue: function ()
        {
            this.editor.replaceValue(this.textarea.value);
        },
        _replaceValueAndHide: function ()
        {
            this._replaceValue();
            this.dialog.hide();
        }
	}
);

// Register this plugin.
dojo.subscribe(dijit._scopeName + ".Editor.getPlugin",null,function(o){
	if(o.plugin){ return; }
	switch(o.args.name){
	case "htmlView":
		o.plugin = new pc.widget.editor_html_view({command: o.args.name});
	}
});


