﻿function createEditor(textBoxId, saveId, cancelId, height, width, resourceSet, context, contentId, theme, culture) {
    var Dom = YAHOO.util.Dom,
        Event = YAHOO.util.Event;
        
    if (document.getElementById(textBoxId)) {
        var state = 'off';
        var editor = new YAHOO.widget.Editor(textBoxId, {height:height+'px',width:width+'px',dompath:true,animate:true,focusAtStart:true});
        editor._defaultToolbar.titlebar = false;

        editor.on('toolbarLoaded', function() {
        	var codeConfig = { type: 'push', label: 'Edit HTML Code', value: 'editcode' };
        	this.toolbar.addButtonToGroup(codeConfig, 'insertitem');
        	this.toolbar.on('editcodeClick', function() {
        		var ta = this.get('element'),
                iframe = this.get('iframe').get('element');

        		if (state == 'on') {
        			state = 'off';
        			this.toolbar.set('disabled', false);
        			this.setEditorHTML(ta.value);
        			if (!this.browser.ie) {
        				this._setDesignMode('on');
        			}

        			Dom.removeClass(iframe, 'editor-hidden');
        			Dom.addClass(ta, 'editor-hidden');
        			this.show();
        			this._focusWindow();
        			Dom.setStyle(iframe, 'position', '');
        		} else {
        			state = 'on';
        			this.cleanHTML();
        			Dom.addClass(iframe, 'editor-hidden');
        			Dom.removeClass(ta, 'editor-hidden');
        			this.toolbar.set('disabled', true);
        			this.toolbar.getButtonByValue('editcode').set('disabled', false);
        			this.toolbar.selectButton('editcode');
        			this.dompath.innerHTML = 'Editing HTML Code';
        			this.hide();
        		}
        		return false;
        	}, this, true);

        	this.toolbar.on('insertimageClick', function() {
        		var _sel = this._getSelectedElement();
        		if (_sel && _sel.tagName && (_sel.tagName.toLowerCase() == 'img')) {
        		} else {
        			var form = document.createElement('form');
        			form.encoding = 'multipart/form-data';
        			form.action = APP_ROOT + "/resources/upload.ashx";
        			document.body.appendChild(form);
        			var pickImage = new YAHOO.widget.Panel(textBoxId + '_pickImage', { width: '600px', height: '400px', fixedcenter: true, close: true, visible: true, modal: true, draggable: true, dragOnly: true });
        			pickImage.setHeader("Select or Upload image");
        			pickImage.setBody("<input type='hidden' name='resourceSet' value = '" + resourceSet + "'/><input type='hidden' name='context' value = '" + context + "'/><input type='hidden' name='contentId' value = '" + contentId + "'/><input type='hidden' name='theme' value = '" + theme + "'/><input type='hidden' name='culture' value = '" + culture + "'/><div id='" + textBoxId + "_images' class='contentEditorImages'><img src='" + APP_IMAGEPATH + "/loading.gif' /></div><input type='file' name='" + textBoxId + "_pickFile' id='" + textBoxId + "_pickFile' class='contentEditorInput'/>&nbsp;<input type='submit' id='" + textBoxId + "_upload' value='Upload' class='contentEditorUpload'/><div id='" + textBoxId + "_error' class='contentEditorImageError'>&nbsp;</div>");
        			pickImage.render(form);

        			var imageDiv = document.getElementById(textBoxId + '_images');
        			if (imageDiv) {
        				var addImage = function(imagePair) {
        					var field = document.createElement('fieldset');
        					var legend = document.createElement('legend');
        					legend.innerText = imagePair.Key;
        					var span = document.createElement('span');
        					span.innerHTML = imagePair.Value.replace('$~/', APP_ROOT + '/');
        					field.appendChild(legend);
        					field.appendChild(span);
        					imageDiv.appendChild(field);
        				}
        				var selectImage = function(src) {
        					var url = Dom.get(textBoxId + '_insertimage_url');
        					url.value = src;
        					url.focus();
        					pickImage.hide();
        				}
        				var loadImages = function() {
        					ResourceService.GetImages(resourceSet, context, contentId, theme, culture,
								function(result) {
									imageDiv.innerText = '';
									for (i = 0; i < result.length; i++) {
										addImage(result[i]);
									}
								},
								function(error) {
									imageDiv.innerText = '';
									var errorDiv = document.getElementById(textBoxId + '_error');
									errorDiv.innerHTML = error;
								});
        				}
        				var onUpload = function(e) {
        					Event.stopEvent(e); // stop default action
        					var errorDiv = document.getElementById(textBoxId + '_error');
        					errorDiv.innerHTML = '&nbsp;';
        					var file = document.getElementById(textBoxId + '_pickFile');
        					if (file.value.length == 0) {
        						errorDiv.innerHTML = 'Required';
        					} else {
        						YAHOO.util.Connect.setForm(form, true);
        						var c = YAHOO.util.Connect.asyncRequest('POST', form.action, {
        							upload: function(r) {
        								var resp = eval('(' + r.responseText + ')');
        								if (resp.error) {
        									errorDiv.innerHTML = resp.errorText;
        								} else {
        									imageDiv.innerHTML = unescape(resp.fileLink).replace('+', ' ').replace('$~/', APP_ROOT + '/');
        									selectImage(imageDiv.firstChild.getAttribute('src', 2));
        								}
        							}
        						});
        					}
        				}

        				Event.on(textBoxId + '_images', 'click', function(ev) {
        					var tar = Event.getTarget(ev);
        					if (tar && tar.tagName && (tar.tagName.toLowerCase() == 'img')) {
        						Event.stopEvent(ev);
        						selectImage(tar.getAttribute('src', 2));
        					}
        				});

        				Event.on(textBoxId + '_upload', 'click', onUpload);

        				loadImages();
        			}
        		}
        	}, this, true);

        	this.on('cleanHTML', function(ev) { this.get('element').value = ev.html; }, this, true);

        	this.on('afterRender', function() {
        		var wrapper = this.get('editor_wrapper');
        		wrapper.appendChild(this.get('element'));
        		this.setStyle('width', '100%');
        		this.setStyle('height', height + 'px');
        		this.setStyle('visibility', '');
        		this.setStyle('top', '');
        		this.setStyle('left', '');
        		this.setStyle('position', 'static');
        		this.addClass('editor-hidden');
        		this.addClass('source');
        	}, this, true);
        }, editor, true);

	    editor.render();

	    Event.onDOMReady(function() {
	    	var button = document.getElementById(saveId);
	    	if (button) {
	    		var f = button.onclick;
	    		button.onclick = function() {
	    			var ta = editor.get('element')
	    			if (!Dom.hasClass(ta, 'editor-hidden')) { editor.setEditorHTML(ta.value); }
	    				editor.saveHTML();
	    			if (f) f();
	    		};
	    	}
	    });

	    Dom.getElementsBy(function(el) { return true; }, 'body', null, function(el) { Dom.addClass(el, 'yui-skin-sam'); });
    }
}
