(function(){

	LIGHTHOUSE = LIGHTHOUSE || {};
	LIGHTHOUSE.widgetPlugins = LIGHTHOUSE.widgetPlugins || {};

})();

(function(){

	var Dom = YAHOO.util.Dom;
	var Event = YAHOO.util.Event;
	var Lang = YAHOO.lang;
	var Widget = YAHOO.widget;

	LIGHTHOUSE.widgetPlugins.Editor = LIGHTHOUSE.widgetPlugins.Editor || {};
	// This is used to add a insert video button to RTE's, it should be
	// used like 
	
	//editorInstance.on('toolbarloaded', insertVideoLoader);

	//used by the rich text editor, Editor widget.
	
	LIGHTHOUSE.widgetPlugins.Editor.insertVideoLoader = function(){
			var editor = this;
			this.toolbar.on('insertvideoClick', function(ev){
				Event.stopEvent(ev);
				var videoWindow = new Widget.EditorWindow('insertvideo', {
					width: '415px'
				});

				var placeholder = Dom.getAncestorIfClass('yui-video', editor._getSelectedElement(), true);
				var embedStrHolder;
				var brLine;

				if(!placeholder || !Dom.hasClass(placeholder, 'yui-video')){
					if(editor._hasSelection()){
						editor._getSelection().deleteFromDocument();
					}
					
					editor._createCurrentElement('span');
					placeholder = editor.currentElement[0];

					placeholder.className = 'yui-video';
					Dom.addClass(placeholder, 'temp');
					
					placeholderIcon = editor._getDoc().createElement('span');
					Dom.addClass(placeholderIcon, 'placeholder-icon');
					placeholder.appendChild(placeholderIcon);

					embedStrHolder = editor._getDoc().createElement('span');
					Dom.addClass(embedStrHolder, 'yui-video-embed-str');
					placeholderIcon.appendChild(embedStrHolder);

					brLine = editor._getDoc().createElement('br');
					Dom.insertAfter(brLine, placeholder);
					Dom.insertAfter(editor._getDoc().createTextNode(' '), placeholder);
					Dom.insertBefore(brLine.cloneNode(true), placeholder);

				}else{
					embedStrHolder = Dom.getElementsByClassName('yui-video-embed-str', 'span', placeholder)[0];
				}
				editor.currentElement[0] = placeholder;
				
				// create the dialog
				var body = document.createElement('div');
				body.setAttribute('id', 'videoInsertForm');
				body.innerHTML = '<div id="yui-video-dialog">'
								+'<label for="insertimage_upload"><em class="subtext">Option 1.</em> Upload<span class="subtext">must be less than 500mb</span></label> <div id="uploaderOverlayVideo"></div><button class="selectfile" id="uploadimagefile"><span>Select</span></button>'
								+'<img src="http://myebookmaster.com/img/1x1.gif" class="icon help-24 tip-icon" title="Upload a video from the following formats AVI, MOV, WMV).  Your videos hosted on our server are free and are private, however if the address of the video was known it could be manually searched from a browser, however this is highly unlikely.  You may also post embed code from any of the popular free video hosts, or host the video on your own server and place the embed code in the box below.">'
							    +'<label<em class="subtext">Option 2.</em> <br>Embed Code<span class="subtext">from another website</span></label>'
							    +'<textarea id="embed-string-textarea">' + Lang.trim(embedStrHolder.innerHTML) + ' </textarea>'
							    +'<label>YouTube <span class="subtext"><a href="http://youtube.com">Upload</a></span></label> <span class="data">You can find the embed code at the bottom of the "About this Video" box on the right.</span>'
							    +'<label>Flickr<span class="subtext"><a href="http://flickr.com">Upload</a></span></label> <span class="data">You can find this under step three, by clicking the <strong>embed button</strong> and selecting the HTML</span>'
							    +'<label>Yahoo! Video<span class="subtext"><a href="http://video.yahoo.com">Upload</a></span></label> <span class="data">You can find this tag in the Add to Site box, at the bottom of the video</span>'
							    +'</div>';
				var closeButton = document.createElement('button');
				closeButton.innerHTML = '<span>Done</span>';
				Event.addListener(closeButton, 'click', function(ev){
					Event.stopEvent(ev);
					this.closeWindow();
				}, null, editor);
				body.appendChild(closeButton);
				videoWindow.setBody(body);
				editor.openWindow(videoWindow);
				var loadingIcon = document.createElement('img');
				loadingIcon.setAttribute('src', 'http://myebookmaster.com/img/loading.gif');
				loadingIcon.setAttribute('id', 'videoInsertFormLoading');
				Dom.addClass(loadingIcon, 'hide');
				body.parentNode.appendChild(loadingIcon);


				/* Upload config */
				YAHOO.widget.Uploader.SWFURL = "http://myebookmaster.com/swf/uploader.swf"; 
				LIGHTHOUSE.widget.Uploader = new YAHOO.widget.Uploader( "uploaderOverlayVideo" );
				
				LIGHTHOUSE.widget.Uploader.addListener('contentReady', function(ev){
					LIGHTHOUSE.widget.Uploader.setFileFilters([{description:"Videos (mov, avi, wmv)", extensions:"*.mov;*.avi;*.wmv;"}]);

					document.getElementById('uploaderOverlayVideo').style.overflow = 'auto'; // Firefox/flash absolute positioning bug -- it sucks

					var sessionId = document.body.getAttribute('session-id');
					LIGHTHOUSE.widget.Uploader.addListener('uploadStart', function(ev){ Dom.addClass('videoInsertForm', 'invisible'); Dom.removeClass('videoInsertFormLoading', 'hide');});
					LIGHTHOUSE.widget.Uploader.addListener('uploadCompleteData', function(ev){ 
						Dom.removeClass('videoInsertForm', 'invisible');
						Dom.addClass('videoInsertFormLoading', 'hide'); 
						this.clearFileList();
						var object = Lang.JSON.parse(ev.data);
						var videoid = object.object.video.id;
						document.getElementById('embed-string-textarea').value = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="437" height="370" id="viddler_'+videoid+'"><param name="movie" value="http://www.viddler.com/player/'+videoid+'/" /><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="true" /><embed src="http://www.viddler.com/player/'+videoid+'/" width="437" height="370" type="application/x-shockwave-flash" allowScriptAccess="always" allowFullScreen="true" name="viddler_'+videoid+'"></embed></object>';

					});
					LIGHTHOUSE.widget.Uploader.addListener('uploadError', function(ev){ alert('There was an error while uploading your video. Try again or contact us at support@myebookmaster.com'); Dom.removeClass('imageInsertForm', 'hide'); Dom.addClass('videoInsertFormLoading', 'hide'); });     
					LIGHTHOUSE.widget.Uploader.addListener('fileSelect', function(ev){ this.uploadAll("http://myebookmaster.com/books/uploadVideo/"+sessionId, "POST", null, 'uploadedVideo'); });
				});

				var textareaElement = document.getElementById('embed-string-textarea');
				textareaElement.scrollIntoView(false);
				textareaElement.select();
				textareaElement.focus();

				editor.on('windowinsertvideoClose', function(){
					var embedStr = Lang.trim(document.getElementById('embed-string-textarea').value);
					var placeholder = this.currentElement[0];
					if(embedStr !== ""){
						var embedStrHolder = Dom.getElementsByClassName('yui-video-embed-str', 'span', placeholder)[0];
						embedStrHolder.parentNode.parentNode.contentEditable = false;
						embedStrHolder.parentNode.contentEditable = false;
						embedStrHolder.contentEditable = false;
						if(embedStr.indexOf('embed') > 0 || embedStr.indexOf('object') > 0){
							Dom.removeClass(placeholder, 'temp');
							embedStrHolder.innerHTML = embedStr;
							this.nodeChange();
						}else{
							placeholder.parentNode.removeChild(placeholder);
						}
					}else{
						// delete the placeholder
						placeholder.parentNode.removeChild(placeholder);
					}
					if(this.get('autoHeight')){
						this._handleAutoHeight();
					}
					this.currentElement = [];
				});
			});

			// set the button as selected
			this.on('afterNodeChange', function(o) {
				var el = this._getSelectedElement();
				if (el && Dom.getAncestorIfClass('yui-video', el, true)) {
					var insertVideoButton = this.toolbar.getButtonByValue('insertvideo');
					this.toolbar.disableAllButtons();
					this.toolbar.enableButton(insertVideoButton);
					this.toolbar.selectButton(insertVideoButton);
				}
			}, this, true);

			// open the dialog window if the element is double clicked
			this.on('editorDoubleClick', function(o) {
				var el = this._getSelectedElement();
				if (el && Dom.getAncestorIfClass('yui-video', el, true)) {
					this.toolbar.fireEvent('insertvideoClick', { type: 'insertvideoClick', target: this.toolbar });
				}
			}, this, true);

		}

})(); 
