// JavaScript Document

function setupTextEditor(promotionId, webRoot, fieldId, fieldName, height, width){

/* Gutter Plugin */
    (function() {
        var Dom = YAHOO.util.Dom,
        Event = YAHOO.util.Event;

        YAHOO.gutter = function() {
            return {
                status: false,
                gutter: null,
                createGutter: function() {
                    YAHOO.log('Creating gutter (#gutter1)', 'info', 'example');
                    this.gutter = new YAHOO.widget.Overlay('gutter1', {
                        height: '425px',
                        width: '300px',
                        context: [myEditor.get('element_cont').get('element'), 'tl', 'tr'],
                        position: 'absolute',
                        visible: false
                    });
                    this.gutter.hideEvent.subscribe(function() {
                        myEditor.toolbar.deselectButton('flickr');
                        Dom.setStyle('gutter1', 'visibility', 'visible');
                        var anim = new YAHOO.util.Anim('gutter1', {
                            width: {
                                from: 300,
                                to: 0
                            },
                            opacity: {
                                from: 1,
                                to: 0
                            }
                        }, 1);
                        anim.onComplete.subscribe(function() {
                            Dom.setStyle('gutter1', 'visibility', 'hidden');
                        });
                        anim.animate();
                    }, this, true);
                    this.gutter.showEvent.subscribe(function() {
                        myEditor.toolbar.selectButton('flickr');
                        this.gutter.cfg.setProperty('context', [myEditor.get('element_cont').get('element'), 'tl', 'tr']);
                        Dom.setStyle(this.gutter.element, 'width', '0px');
                        var anim = new YAHOO.util.Anim('gutter1', {
                            width: {
                                from: 0,
                                to: 300
                            },
                            opacity: {
                                from: 0,
                                to: 1
                            }
                        }, 1);
                        anim.animate();
                    }, this, true);
                    var warn = '';
                    if (myEditor.browser.webkit || myEditor.browser.opera) {
                        warn = myEditor.STR_IMAGE_COPY;
                    }
                    this.gutter.setBody('<h2>Image Search</h2><label for="flikr_search">Search:</label><input type="text" value="" id="flickr_search"><div id="flickr_results"><p>Enter your search term into the box above. Be patient, it my take a few seconds to get the images..</p></div>' + warn);
                    this.gutter.render(document.body);
                },
                open: function() {
                    Dom.get('flickr_search').value = '';
                    YAHOO.log('Show Gutter', 'info', 'example');
                    this.gutter.show();
                    this.status = true;
                },
                close: function() {
                    YAHOO.log('Close Gutter', 'info', 'example');
                    this.gutter.hide();
                    this.status = false;
                },
                toggle: function() {
                    if (this.status) {
                        this.close();
                    } else {
                        this.open();
                    }
                }
            }
        }

    })();
	
	YAHOO.util.Event.onAvailable('flickr_search', function() {
        YAHOO.log('onAvailable: #flickr_search', 'info', 'example');
        YAHOO.util.Event.on('flickr_results', 'mousedown', function(ev) {
            YAHOO.util.Event.stopEvent(ev);
            var tar = YAHOO.util.Event.getTarget(ev);
            if (tar.tagName.toLowerCase() == 'img') {
                if (tar.getAttribute('fullimage', 2)) {
                    YAHOO.log('Found an image, insert it..', 'info', 'example');
                    var img = tar.getAttribute('fullimage', 2),
                    title = tar.getAttribute('fulltitle'),
                    owner = tar.getAttribute('fullowner'),
                    url = tar.getAttribute('fullurl');
                    this.toolbar.fireEvent('flickrClick', { type: 'flickrClick', img: img, title: title, owner: owner, url: url });
                }
            }
        }, myEditor, true);
        YAHOO.log('Create the Auto Complete Control', 'info', 'example');
        oACDS = new YAHOO.widget.DS_XHR("includes/ajax/photos.php",
        ["Photo", "Caption", "PhotoId", "Extension"]);
        oACDS.scriptQueryParam = "searchterm";
        oACDS.responseType = YAHOO.widget.DS_XHR.TYPE_XML;
        oACDS.maxCacheEntries = 0;
        oACDS.scriptQueryAppend = "promotionid=" + promotionId + "&type=XML";

        // Instantiate AutoComplete
        oAutoComp = new YAHOO.widget.AutoComplete('flickr_search', 'flickr_results', oACDS);
        oAutoComp.autoHighlight = false;
        oAutoComp.alwaysShowContainer = true;
        oAutoComp.formatResult = function(oResultItem, sQuery) {
            // This was defined by the schema array of the data source
            var sTitle = oResultItem[0];
            var sId = oResultItem[1];
            var sType = oResultItem[2];
            var urlPart = webRoot + 'images/' + sId;
            var sUrl = urlPart + '_small.' + sType;
            var lUrl = urlPart + '_large.' + sType;
            //var fUrl = 'http:/' + '/www.flickr.com/photos/' + sOwner + '/' + sId;
            var sMarkup = '<img src="' + sUrl + '" fullimage="' + lUrl + '" fulltitle="' + sTitle + '" fullid="' + sId + '" fullurl="' + urlPart + '_original.' + sType + '" class="yui-ac-flickrImg" title="Click to add this image to the editor"><br>';
            return (sMarkup);
        };
    });

    var gutter = null;
	
	//Setup some private variables 
	var Dom = YAHOO.util.Dom, 
	    Event = YAHOO.util.Event;

    var myConfig = {
        height: '300px',
        width: '600px',
        animate: true,
        dompath: true,
        focusAtStart: true
    };
	
	var state = 'off'; 
    YAHOO.log('Set state to off..', 'info', 'example'); 

    YAHOO.log('Editor loaded..', 'info', 'example');
    var myEditor = new YAHOO.widget.Editor(fieldId, { 
	    height: height, 
	    width: width, 
	    dompath: true, //Turns on the bar at the bottom 
	    animate: true,
		markup: 'xhtml',
		toolbar: {
			collapse: true,
			titlebar: fieldName,
			draggable: false,
			buttonType: 'advanced',
			buttons: [
				{ group: 'fontstyle', label: 'Font Name and Size',
					buttons: [
						{ type: 'select', label: 'Arial', value: 'fontname', disabled: true,
							menu: [
								{ text: 'Arial', checked: true },
								{ text: 'Arial Black' },
								{ text: 'Comic Sans MS' },
								{ text: 'Courier New' },
								{ text: 'Lucida Console' },
								{ text: 'Tahoma' },
								{ text: 'Times New Roman' },
								{ text: 'Trebuchet MS' },
								{ text: 'Verdana' }
							]
						},
						{ type: 'spin', label: '13', value: 'fontsize', range: [ 9, 75 ], disabled: true }
					]
				},
				{ type: 'separator' },
				{ group: 'textstyle', label: 'Font Style',
					buttons: [
						{ type: 'push', label: 'Bold CTRL + SHIFT + B', value: 'bold' },
						{ type: 'push', label: 'Italic CTRL + SHIFT + I', value: 'italic' },
						{ type: 'push', label: 'Underline CTRL + SHIFT + U', value: 'underline' },
						{ type: 'separator' },
						{ type: 'push', label: 'Subscript', value: 'subscript', disabled: true },
						{ type: 'push', label: 'Superscript', value: 'superscript', disabled: true },
						{ type: 'separator' },
						{ type: 'color', label: 'Font Color', value: 'forecolor', disabled: true },
						{ type: 'color', label: 'Background Color', value: 'backcolor', disabled: true },
						{ type: 'separator' },
						{ type: 'push', label: 'Remove Formatting', value: 'removeformat', disabled: true },
						{ type: 'push', label: 'Show/Hide Hidden Elements', value: 'hiddenelements' }
					]
				},
				{ type: 'separator' },
				{ group: 'alignment', label: 'Alignment',
					buttons: [
						{ type: 'push', label: 'Align Left CTRL + SHIFT + [', value: 'justifyleft' },
						{ type: 'push', label: 'Align Center CTRL + SHIFT + |', value: 'justifycenter' },
						{ type: 'push', label: 'Align Right CTRL + SHIFT + ]', value: 'justifyright' },
						{ type: 'push', label: 'Justify', value: 'justifyfull' }
					]
				},
				{ type: 'separator' },
				{ group: 'parastyle', label: 'Paragraph Style',
					buttons: [
					{ type: 'select', label: 'Normal', value: 'heading', disabled: true,
						menu: [
							{ text: 'Normal', value: 'none', checked: true },
							{ text: 'Header 1', value: 'h1' },
							{ text: 'Header 2', value: 'h2' },
							{ text: 'Header 3', value: 'h3' },
							{ text: 'Header 4', value: 'h4' },
							{ text: 'Header 5', value: 'h5' },
							{ text: 'Header 6', value: 'h6' }
						]
					}
					]
				},
				{ type: 'separator' },
				{ group: 'indentlist', label: 'Indenting',
					buttons: [
						{ type: 'push', label: 'Indent', value: 'indent', disabled: true },
						{ type: 'push', label: 'Outdent', value: 'outdent', disabled: true }
					]
				},
				{ group: 'indentlist', label: 'Lists',
					buttons: [
						{ type: 'push', label: 'Create an Unordered List', value: 'insertunorderedlist' },
						{ type: 'push', label: 'Create an Ordered List', value: 'insertorderedlist' }
					]
				},
				{ group: 'insertitem', label: 'Insert Item',
					buttons: [
						{ type: 'push', label: 'HTML Link CTRL + SHIFT + L', value: 'createlink', disabled: true },
						{ type: 'push', label: 'Insert Image', value: 'flickr' }
					]
				},
				{ group: 'imageformat', label: 'Image Align',
					buttons: [
					]
				},
				{ group: 'view', label: 'View',
					buttons: [
					]
				}				
			]

		}
	});
	
    myEditor.on('toolbarLoaded', function() {
        YAHOO.log('Toolbar loaded, add button and create gutter', 'info', 'example');
        gutter = new YAHOO.gutter();
		
		/* Code Editor begins...*/
		var codeConfig = {
            type: 'push', label: 'Edit HTML Code', value: 'editcode'
        };
        YAHOO.log('Create the (editcode) Button', 'info', 'example');
        this.toolbar.addButtonToGroup(codeConfig, 'view');
        
        this.toolbar.on('editcodeClick', function() {
            var ta = this.get('element'),
                iframe = this.get('iframe').get('element');

            if (state == 'on') {
                state = 'off';
				$("#codeeditor").val("off");
                this.toolbar.set('disabled', false);
                YAHOO.log('Show the Editor', 'info', 'example');
                YAHOO.log('Inject the HTML from the textarea into the editor', 'info', 'example');
                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();
            } else {
                state = 'on';
				$("#codeeditor").val("on");
                YAHOO.log('Show the Code Editor', 'info', 'example');
                this.cleanHTML();
                YAHOO.log('Save the Editors HTML', 'info', 'example');
                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.on('cleanHTML', function(ev) {
            YAHOO.log('cleanHTML callback fired..', 'info', 'example');
            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', '100%');
            this.setStyle('visibility', '');
            this.setStyle('top', '');
            this.setStyle('left', '');
            this.setStyle('position', '');

            this.addClass('editor-hidden');
        }, this, true);
		/* Code Editor ends...*/
		
		var codeConfig = {
            type: 'push', label: 'Align Left', value: 'alignleft'
        };
        YAHOO.log('Create the (alignleft) Button', 'info', 'example');
        this.toolbar.addButtonToGroup(codeConfig, 'imageformat');
        
        this.toolbar.on('alignleftClick', function() {
           //Get the selected element 
	        var _sel = this._getSelectedElement();
			
			if(_sel.firstChild) { // check for children
				var oChild = _sel.firstChild;
				while(oChild) { // run over them
				  if(oChild.nodeType==1) { // element
					if(oChild.tagName && (oChild.tagName.toLowerCase() == 'img')) {
						oChild.setAttribute("style", "float: left; padding: 5px;");
					}
				  }
				  oChild = oChild.nextSibling;
				}
			 }
			 return false;
			
        }, this, true);
		
		var codeConfig = {
            type: 'push', label: 'Align Right', value: 'alignright'
        };
        YAHOO.log('Create the (alignright) Button', 'info', 'example');
        this.toolbar.addButtonToGroup(codeConfig, 'imageformat');
        
        this.toolbar.on('alignrightClick', function() {
           //Get the selected element 
	        var _sel = this._getSelectedElement();
			
			if(_sel.firstChild) { // check for children
				var oChild = _sel.firstChild;
				while(oChild) { // run over them
				  if(oChild.nodeType==1) { // element
					if(oChild.tagName && (oChild.tagName.toLowerCase() == 'img')) {
						oChild.setAttribute("style", "float: right; margin: 5px;");
					}
				  }
				  oChild = oChild.nextSibling;
				}
			 }
			 return false;
			
        }, this, true);
		
		myEditor.toolbar.on('flickrClick', function(ev) {
            YAHOO.log('flickrClick: ' + YAHOO.lang.dump(ev), 'info', 'example');
            this._focusWindow();
            if (ev && ev.img) {
                YAHOO.log('We have an image, insert it', 'info', 'example');
                //To abide by the Flickr TOS, we need to link back to the image that we just inserted
                var html = '<img src="' + ev.img + '" title="' + ev.title + '">';
                this.execCommand('inserthtml', html);
            }
            gutter.toggle();
        }, myEditor, true);
        gutter.createGutter();
    });
    myEditor.render();
		
	//Inside an event handler after the Editor is rendered 
	YAHOO.util.Event.on('submit', 'click', function() { 
	    //Put the HTML back into the text area 
	    myEditor.saveHTML();
	});
	
	//Inside an event handler after the Editor is rendered 
	YAHOO.util.Event.on('submitstore', 'click', function() { 
	    //Put the HTML back into the text area 
	    myEditor.saveHTML();
	});
	
	//Inside an event handler after the Editor is rendered 
	YAHOO.util.Event.on('editevents', 'click', function() { 
	    //Put the HTML back into the text area 
	    myEditor.saveHTML();
	});
	
	//Inside an event handler after the Editor is rendered 
	YAHOO.util.Event.on('save', 'click', function() { 
	    //Put the HTML back into the text area 
	    myEditor.saveHTML();
	});
	
	//Inside an event handler after the Editor is rendered 
	YAHOO.util.Event.on('editwrestlers', 'click', function() { 
	    //Put the HTML back into the text area 
		myEditor.saveHTML();
	});
	
}
