/* Richtextbox.js

	Purpose:
		
	Description:
		
	History:
		Wed, Aug 13, 2014  2:47:48 PM, Created by RaymondChao

Copyright (C) 2014 Potix Corporation. All Rights Reserved.

*/

(function () {
zssex.Richtextbox = zk.$extends(zul.wgt.Div, {
	_content: '',
	_init: function () {
		this.editor = jq(this.$n()).cleditor({
			width: 550,
			height: 200,
			controls: 'bold italic underline strikethrough subscript superscript font size color',
			fonts: 'Arial, Arial Black, Comic Sans MS, Courier New, Georgia, Impact,' +
					'Lucida Console, Lucida Sans Unicode, Palatino Linotype, Tahoma,' +
					'Times New Roman, Trebuchet MS, Verdana, MS Sans Serif, MS Serif',
			sizes: '8,9,10,11,12,14,16,18,20,22,24,26,28,36,48,72',
			docType: '<!DOCTYPE html>',
			useCSS: false,
			bodyStyle: 'margin:8px; font-size:11pt; font-family:Calibri; cursor:text'
		})[0];
		this._colorNode = $(".cleditorButton[title='Font Color']")[0];
		this._colorPopup = new zss.ColorPopup(this._colorNode);
		var colorPopup = this._colorPopup;
		colorPopup.adjustPosition_ = function() {
			if(this._ref) {
				zk(this.$n('pp')).position(this._ref, this._getPosition());
			}
		};
		this.parent.appendChild(this._colorPopup);
		if (colorPopup) {
			colorPopup.listen({onChange: this.proxy(this.onChange)});
		}
		this.editor.wgt = this;
		var editor = this.editor;
		jq(this.$n()).val(this._content);
		editor.updateFrame();
		editor.blurred(function (event) {
			this.wgt.fire('onChange', {value: this.doc.body.innerHTML});
		});
		editor.focus();
	},
	_deferInit: function () {
		if (this._initId) {
			clearTimeout(this._initId);
			delete this._initId;
		}
		var self = this;
		if (this.$n()) {
			this._init();
		} else {
			this._initId =
				setTimeout(function () {
					self._deferInit();
				}, 50);
		}
	},
	adjustPosition_: function() {
		// adjust popup position to ref. widget
		if(this._ref) {
			zk(this.$n('pp')).position(this._ref, this._getPosition());
		}
	},
	setContent: function (content) {
		if (this._content === content) {
			return;
		}
		this._content = content;
		// TODO
	},
	openColorPopup: function () {
		var popup = this._colorPopup;
		if (popup) {
			popup.open(null, null, 'after_start');
		}
	},
	bind_: function () {
		this.$supers(zul.wgt.Div, 'bind_', arguments);
		var wgt = this;
		setTimeout(function () { wgt._init(); }, 100);
	},
	unbind_: function () {
		if (this._colorPopup) {
			this._colorPopup.unlisten({onChange: this.proxy(this.onChange)});
		}
		this.$supers(zul.wgt.Div, 'unbind_', arguments);
	},
	onChange: function (evt) { //invoke from Color Palette, not from event
		var hex = evt.data.color,
			editor = this.editor;
		if (editor) {
			editor.execCommand('forecolor', hex, false, this._colorNode);
			this.fire('onChange', {value: editor.doc.body.innerHTML});
		}
	}
});
})();