﻿// JsLint Global Objects
/*global window, alert, document, Ext, AV, ShowLinkBuilder, InnovaEditor, editorDoc_Init, editorDoc_PostInit */
/*jslint devel: true, browser: true, unparam: true, sloppy: true, white: true, nomen: true, maxerr: 50, indent: 2, eqeq: true, newcap: true */

// This should extend Ext.form.Field, but I don't have the time
AV.HtmlEditorContainer = Ext.extend(Ext.Container, {
	hide: false,
	editorRendered: false,
	validationDelay: 250,

	initComponent: function () {

		var editorName = this.name;

		this.labelCt = new Ext.Container({
			anchor: '-20',
			cls: "x-form-item-label",
			html: this.label,
			style: { marginBottom: '2px' }
		});

		this.spellObj = new Ext.form.Hidden({
			name: "txtSpell" + this.name
		});

		this.hiddenDesc = new Ext.form.Hidden({
			name: this.name,
			value: this.text
		});

		this.textArea = new Ext.form.TextArea({
			id: "txt_" + this.name,
			height: this.editorHeight || 200,
			anchor: '-20',
			value: this.text,
			hideLabel: true,
			hidden: (Ext.isIE || Ext.isGecko),
			validator: this.validator,
			msgTarget: "div_" + this.name + "ValMsg",
			listeners: {
				afterrender: {
					fn: function () {
						if (!this.hide) {
							this.initHtmlEditor(this.text);
						}
					},
					scope: this
				}
			},

			// Override the validate function to change the border color of the iframe
			validate: function () {
				var editor = Ext.getDom('idContent' + editorName);

				if (this.disabled || this.validateValue(this.processValue(this.getRawValue()))) {
					this.clearInvalid();
					if (editor) { editor.style.borderColor = 'cfcfcf'; }
					return true;
				}

				if (editor) { editor.style.borderColor = 'CC3300'; }
				return false;
			}
		});

		this.editorCt = new Ext.Container({
			anchor: '-20',
			autoEl: {
				tag: "div",
				id: "div_" + this.name + "Target"
			}
		});

		this.validationMsg = new Ext.Container({
			anchor: '-20',
			autoEl: {
				tag: "div",
				cls: "x-form-invalid-msg",
				id: "div_" + this.name + "ValMsg",
				style: "display:none"
			}
		});

		this.editorCtText = new Ext.Container({
			autoEl: {
				tag: "div",
				id: "div_" + this.name,
				html: "You must have the latest versions of Internet Explorer or Mozilla Firefox to use this editor."
			}
		});

		Ext.apply(this, {
			// hide label to keep the space for a label from showing
			hideLabel: true,
			style: { marginBottom: '10px' },
			layout: 'anchor',
			items: [
				this.labelCt,
				this.spellObj,
				this.hiddenDesc,
				this.textArea,
				this.editorCt,
				this.validationMsg,
				this.editorCtText
			]
		});

		AV.HtmlEditorContainer.superclass.initComponent.apply(this, arguments);
	},

	initHtmlEditor: function (html) {
		var cnt = 0,
				ieCompat = (Ext.isIE && document.compatMode && document.compatMode === 'CSS1Compat'),
				editor, doc;

		// Only render for IE and Firefox
		if (!Ext.isIE && !Ext.isGecko) { return; }

		if (this.editorRendered) {
			// Firefox has issues when an editable iframe has display set to 'none', calling putHTML
			// re-initializes the editor to make it editable again
			if (Ext.isGecko || ieCompat) { this.htmlEditor.putHTML(html); }
			return;
		}

		//Make sure the div we're writing the editor to is available
		if (!Ext.getDom('div_' + this.name + 'Target') && cnt < 20) {
			cnt += 1;
			this.initHtmlEditor.defer(100, this, [html]);
			return;
		}

		//unfortunately, we have to add the editor to the global scope
		window[this.name] = new InnovaEditor(this.name);
		editor = window[this.name];

		editor.name = this.name;
		editor.css = this.editorCss;
		editor.height = (this.editorHeight || 200) + 'px';
		editor.width = '100%'; //  (this.editorWidth	|| 700) + 'px';

		editorDoc_Init(editor);

		Ext.apply(editor, (this.initialConfig.editorConfig || {}));

		editor.btnFullScreen = true;

		//Remove functionality for AV lite sites
		if (AV.site_type_id == 2 || AV.site_type_id == 7) {
			editor.btnFlash = false;
			editor.btnMedia = false;
			//editor.useDocInsert		= false;
			editor.useTemplate = false;
			editor.btnBookmark = false;
			editor.useMap = false;
		}

		editorDoc_PostInit(editor, true);

		editor.fullScreen = this.setFullWindow.createDelegate(this);

		this.htmlEditor = editor;

		if (this.validator) {
			doc = this.getDocBody();

			if (doc) {
				this.validationTask = new Ext.util.DelayedTask(this.validate, this);
				Ext.EventManager.on(doc, 'keyup', this.filterValidation, this);
				//2011-12 related to TICKET 106208 pasting HTML source in only, there is no "change" event for contenteditable (yet)....
				Ext.EventManager.on(doc, 'focus', this.validate, this);//focus event called by editor source_html.htm - critical (for FF at least)
				Ext.EventManager.on(doc, 'focusin', this.validate, this);//for IE quirks mode
			}
		}

		this.editorRendered = true;
	},

	getDocBody: function () {
		if (this.htmlEditor) {
			var objIframe = Ext.getDom('idContent' + this.name);
			//return objIframe ? objIframe.contentDocument || objIframe.contentWindow.document : null;
			return objIframe ? objIframe.document || objIframe.contentDocument : null;//2012-01 TICKET 106208
		}
		else { return null; }
	},

	filterValidation: function (e) {
		if (!e.isNavKeyPress()) { try { this.validationTask.delay(this.validationDelay); } catch (e) { } }
	},

	validate: function () {
		if (this.htmlEditor) {
			this.textArea.setValue(this.htmlEditor.getXHTMLBody());
			this.textArea.validate();
		}
	},

	clearInvalid: function () {
		this.textArea.clearInvalid();
	},

	setValue: function (html) {
		this.validate(); //2011-12 TICKET 106208
		if (this.htmlEditor) { this.htmlEditor.loadHTML(html); }
		else { this.textArea.setValue(html); }
	},

	focus: function () {
		if (this.htmlEditor) { this.htmlEditor.focus(); }
		else { this.textArea.focus(); }
	},

	getValue: function () {
		this.validate(); //2011-12 TICKET 106208
		return this.htmlEditor ? this.htmlEditor.getXHTMLBody() : this.textArea.getValue();
	},

	getText: function () {
		return Ext.util.Format.stripTags(this.getValue()).replace(/&nbsp;/g, " ").replace(/\s+/g, ' ').replace(/\n|\r/g, ' ').replace(/\t/g, '');
	},

	smartSubString: function (intLength) {
		var inString = this.getText(),
				tmpStr;

		if (inString.length <= intLength) { return inString; }
		else {
			tmpStr = inString.substring(0, intLength);

			while (tmpStr.charAt(intLength) !== " ") {
				intLength -= 1;
			}
			return tmpStr.substring(0, intLength) + "...";
		}
	},

	setFullWindow: function () {
		var elText = this.textArea.getEl(),
				parentWin = elText.findParentNode('.av-content-win-panel', 10, true),
				elForm = elText.findParentNode('form', 10, true),
				elArea = Ext.get("idArea" + this.htmlEditor.name),
				elIframe = Ext.get('idContent' + this.htmlEditor.name),
				elFSBtn = Ext.get('btnFullScreen' + this.htmlEditor.name),
				box = parentWin ? parentWin.getBox() : { width: 700, height: 250, x: 0, y: 0 },
				padding = parentWin ? parseInt(parentWin.getStyle('padding'), 10) : 10,
				zIndex;

		if (this.isFullWindow) {
			this.isFullWindow = false;
			zIndex = '9000';
			elArea.setStyle({ 'position': 'relative', 'zIndex': '9020' });
			if (elFSBtn) { elFSBtn.first().setStyle({ 'top': '0' }); }
			box = this.originalBox;
		}
		else {

			if (!this.originalBox) { this.originalBox = elArea.getBox(); }
			this.isFullWindow = true;

			box.height -= (2 * padding);
			box.width -= (2 * padding);

			// Have to set the form size or it cuts off the iframe
			elForm.setSize(box);

			// account for the iframe border
			box.height -= 2;
			box.width -= 2;

			box.x += padding;
			box.y += padding;

			if (elFSBtn) { elFSBtn.first().setStyle({ 'top': '-75px' }); }

			elArea.setStyle({ 'position': 'absolute', 'zIndex': '9050', 'backgroundColor': '#ffffff' });
		}

		elIframe.setHeight(box.height - 64);
		elArea.setBox(box, true, true);
		this.focus();

		//??
		//ifrm						= document.getElementById("idFixZIndex"+this.oName),
	},

	onDestroy: function () {
		if (this.htmlEditor) {
			var doc = this.getDocBody();
			if (doc) {
				Ext.EventManager.un(doc, 'keyup', this.filterValidation, this);
				Ext.EventManager.un(doc, 'focus', this.validate, this);
				Ext.EventManager.un(doc, 'focusin', this.validate, this);
			}

			if (this.validationTask) {
				this.validationTask.cancel();
				this.validationTask = null;
			}

			delete this.htmlEditor;
			window[this.name] = null;
		}

		AV.HtmlEditorContainer.superclass.onDestroy.apply(this, arguments);
	}
});
