var LIGHTHOUSE = LIGHTHOUSE || {};
LIGHTHOUSE.widget = LIGHTHOUSE.widget || {};

// this file is used to house created widgets, as well as modifications to other (likely Yahoo) widgets.
// widgets have a userinterface

(function(){

	var Dom = YAHOO.util.Dom;
	var Event = YAHOO.util.Event;
	var Lang = YAHOO.lang;
	YAHOO.widget.Editor.prototype._handleAutoHeight = function() {
		var doc = this._getDoc(),
			body = doc.body,
			docEl = doc.documentElement;

		var height = parseInt(Dom.getStyle(this.get('editor_wrapper'), 'height'), 10);
		var newHeight = body.scrollHeight;
		if (this.browser.webkit) {
			newHeight = docEl.scrollHeight;
		}
		if(newHeight > 32000){
			newHeight = 32000;
			this.set('autoHeight', false); // turn autoheight off
		}
		if (newHeight < parseInt(this.get('height'), 10)) {
			newHeight = parseInt(this.get('height'), 10);
		}

		if ((height != newHeight) && (newHeight >= parseInt(this.get('height'), 10))) {   
			Dom.setStyle(this.get('editor_wrapper'), 'height', newHeight + 'px');
			if (this.browser.ie) {
				//Internet Explorer needs this
				this.get('iframe').setStyle('height', '99%');
				this.get('iframe').setStyle('zoom', '1');
				var self = this;
				window.setTimeout(function() {
					self.get('iframe').setStyle('height', '100%');
				}, 1);
			}
		}
	};

	YAHOO.widget.Editor.prototype._getSelectedElement = function() {
            var doc = this._getDoc(),
                range = null,
                sel = null,
                elm = null,
                check = true;

            if (this.browser.ie) {
                this.currentEvent = this._getWindow().event; //Event utility assumes window.event, so we need to reset it to this._getWindow().event;
                range = this._getRange();
                if (range) {
                    elm = range.item ? range.item(0) : range.parentElement();
                    if (this._hasSelection()) {
                        //TODO
                        //WTF.. Why can't I get an element reference here?!??!
                    }
                    if (elm === doc.body) {
                        elm = null;
                    }
                }
                if ((this.currentEvent !== null) && (this.currentEvent.keyCode === 0)) {
                    elm = Event.getTarget(this.currentEvent);
                }
            } else {
                sel = this._getSelection();
                range = this._getRange();

                if (!sel || !range) {
                    return null;
                }
                //TODO
                if (!this._hasSelection() && this.browser.webkit3) {
                    //check = false;
                }
                if (this.browser.gecko) {
                    //Added in 2.6.0
                    if (range.startContainer) {
                        check = false;
                        if (range.startContainer.nodeType === 3) {
                            elm = range.startContainer.parentNode;
                        } else if (range.startContainer.nodeType === 1) {
                            elm = range.startContainer;
                        } else {
                            check = true;
                        }
                        if (!check) {
                            this.currentEvent = null;
                        }
                    }
                }
                if (check) {
                    if (sel.anchorNode && (sel.anchorNode.nodeType == 3)) {
                        if (sel.anchorNode.parentNode) { //next check parentNode
                            elm = sel.anchorNode.parentNode;
                        }
                        if (sel.anchorNode.nextSibling != sel.focusNode.nextSibling) {
                            elm = sel.anchorNode.nextSibling;
                        }
                    }
                    if (this._isElement(elm, 'br')) {
                        elm = null;
                    }
                    if (!elm) {
                        elm = range.commonAncestorContainer;
                        if (!range.collapsed) {
                            if (range.startContainer == range.endContainer) {
                                if (range.startOffset - range.endOffset < 2) {
                                    if (range.startContainer.hasChildNodes()) {
                                        elm = range.startContainer.childNodes[range.startOffset];
                                    }
                                }
                            }
                        }
                    }
               }
            }
            
            if (this.currentEvent !== null) {
                try {
                    switch (this.currentEvent.type) {
                        case 'click':
                        case 'mousedown':
                        case 'mouseup':
                            if (this.browser.webkit) {
                                elm = Event.getTarget(this.currentEvent);
                            }
                            break;
                        default:
                            //Do nothing
                            break;
                    }
                } catch (e) {
                    YAHOO.log('Firefox 1.5 errors here: ' + e, 'error', 'SimpleEditor');
                }
            } else if ((this.currentElement && this.currentElement[0]) && (!this.browser.ie)) {
                //TODO is this still needed?
                //elm = this.currentElement[0];
            }


            if (this.browser.opera || this.browser.webkit) {
                if (this.currentEvent && !elm) {
                    elm = YAHOO.util.Event.getTarget(this.currentEvent);
                }
            }
            if (!elm || !elm.tagName) {
                elm = doc.body;
            }
            if (this._isElement(elm, 'html')) {
                //Safari sometimes gives us the HTML node back..
                elm = doc.body;
            }
            if (this._isElement(elm, 'body')) {
                //make sure that body means this body not the parent..
                elm = doc.body;
            }
            if (elm && !elm.parentNode) { //Not in document
                elm = doc.body;
            }
            if (elm === undefined) {
                elm = null;
            }
            return elm;
        };
	/*YAHOO.widget.Editor.prototype.cmd_forecolor = function(value){
		var exec = true,
			el = this._getSelectedElement();

			if (!this._isElement(el, 'body') && !this._hasSelection()) {
				Dom.setStyle(el, 'color', value);
				this._selectNode(el);
				exec = false;
			} else if (!this._isElement(el, 'body') && this._hasSelection()) {
				Dom.setStyle(el, 'color', value);
				this._selectNode(el);
				exec = false;
			} else {
				if (this.get('insert')) {
					el = this._createInsertElement({ color: value });
				} else {
					this._createCurrentElement('span', { color: value });
					this._selectNode(this.currentElement[0]);
				}
				exec = false;
			}
			return [exec];
	}*/
	YAHOO.widget.Editor.prototype._handleInsertImageWindowClose = function() {
		var url = Dom.get('insertimage_url');
		var link = Dom.get('insertimage_link');
		var el = this.currentElement[0];
		if (url && url.value && (url.value != this.STR_IMAGE_HERE)) {
			el.setAttribute('src', url.value);
			var par = el.parentNode;
			if (link.value) {
				var urlValue = link.value;
				if ((urlValue.indexOf(':/'+'/') == -1) && (urlValue.substring(0,1) != '/') && (urlValue.substring(0, 6).toLowerCase() != 'mailto')) {
					if ((urlValue.indexOf('@') != -1) && (urlValue.substring(0, 6).toLowerCase() != 'mailto')) {
						//Found an @ sign, prefix with mailto:
						urlValue = 'mailto:' + urlValue;
					} else {
						/* :// not found adding */
						urlValue = 'http:/'+'/' + urlValue;
					}
				}
				if (par && this._isElement(par, 'a')) {
					par.setAttribute('href', urlValue);
					par.setAttribute('target', '_blank');
				} else {
					var _a = this._getDoc().createElement('a');
					_a.setAttribute('href', urlValue);
					_a.setAttribute('target', '_blank');
					el.parentNode.replaceChild(_a, el);
					_a.appendChild(el);
				}
			} else {
				if (par && this._isElement(par, 'a')) {
					par.parentNode.replaceChild(el, par);
				}
			}
		} else {
			//No url/src given, remove the node from the document
			el.parentNode.removeChild(el);
		}
		this.currentElement = [];
		this.nodeChange();
	};
	YAHOO.widget.Editor.prototype._handleInsertImageClick = function(){
		if (this.get('limitCommands')) {
			if (!this.toolbar.getButtonByValue('insertimage')) {
				return false;
			}
		}
		this._setBusy();
		this.on('afterExecCommand', function() {
			var el = this.currentElement[0],
				body = null,
				link = '',
				target = '',
				title = '',
				src = '',
				align = '',
				height = 75,
				width = 75,
				padding = 0,
				oheight = 0,
				owidth = 0,
				blankimage = false,
				win = new YAHOO.widget.EditorWindow('insertimage', {
					width: '415px'
				});

			if (!el) {
				el = this._getSelectedElement();
			}
			if (el) {
				if (el.getAttribute('src')) {
					src = el.getAttribute('src', 2);
					if (src.indexOf(this.get('blankimage')) != -1) {
						src = this.STR_IMAGE_HERE;
						blankimage = true;
					}
				}
				if (el.getAttribute('alt', 2)) {
					title = el.getAttribute('alt', 2);
				}
				if (el.getAttribute('title', 2)) {
					title = el.getAttribute('title', 2);
				}

				if (el.parentNode && this._isElement(el.parentNode, 'a')) {
					link = el.parentNode.getAttribute('href', 2);
					if (el.parentNode.getAttribute('target') !== null) {
						target = el.parentNode.getAttribute('target');
					}
				}
				height = parseInt(el.height, 10);
				width = parseInt(el.width, 10);
				if (el.style.height) {
					height = parseInt(el.style.height, 10);
				}
				if (el.style.width) {
					width = parseInt(el.style.width, 10);
				}
				if (el.style.margin) {
					padding = parseInt(el.style.margin, 10);
				}
				if (!el._height) {
					el._height = height;
				}
				if (!el._width) {
					el._width = width;
				}
				oheight = el._height;
				owidth = el._width;
			}

			body = document.createElement('div');
			body.setAttribute('id', 'imageInsertForm');
			body.innerHTML = '<label for="insertimage_upload"><em class="subtext">Option 1.</em> Upload<span class="subtext">from your computer</span></label> <div id="uploaderOverlay"></div><button class="selectfile" id="uploadimagefile"><span>Select</span></button>'
							+'<label for="insertimage_url"><em class="subtext">Option 2.</em> by URL<span class="subtext">from another website</span></label> <input type="text" id="insertimage_url" value="' + src + '" size="40">'
							+'<input type="text" name="insertimage_link" id="insertimage_link" value="' + link + '">'   // I've kept this here, but hidden it with CSS
							    																						// So that there aren't any JS errors from searching for elements that aren't there
							+'';
			var tbarCont = document.createElement('div');
			tbarCont.id = 'img_toolbar';
			body.appendChild(tbarCont);		
		
			closeButton = document.createElement('button');
			closeButton.innerHTML = '<span>Done</span>';
			Event.addListener(closeButton, 'click', function(ev){
				Event.stopEvent(ev);
				this.closeWindow();
			}, null, this);
			body.appendChild(closeButton);
			win.cache = body;

			var tbar = new YAHOO.widget.Toolbar(tbarCont, {
				buttonType: this._defaultToolbar.buttonType,
				buttons: [
					{ group: 'textflow', label: 'Alignment <span class="subtext">How the text flows.',
						buttons: [
							{ type: 'push', label: 'Left', value: 'left' },
							{ type: 'push', label: 'Inline', value: 'inline' },
							{ type: 'push', label: 'Block', value: 'block' },
							{ type: 'push', label: 'Right', value: 'right' }
						]
					}
				]
			});

			if ((el.align == 'right') || (el.align == 'left')) {
				tbar.selectButton(el.align);
			} else if (el.style.display == 'block') {
				tbar.selectButton('block');
			} else {
				tbar.selectButton('inline');
			}
			tbar.on('buttonClick', function(o) {
				var value = o.button.value,
					borderString = '';
				if (o.button.menucmd) {
					value = o.button.menucmd;
				}
				switch(value) {
					case 'right':
					case 'left':
						tbar.deselectAllButtons();
						el.style.display = '';
						el.align = o.button.value;
						break;
					case 'inline':
						tbar.deselectAllButtons();
						el.style.display = '';
						el.align = '';
						break;
					case 'block':
						tbar.deselectAllButtons();
						el.style.display = 'block';
						el.align = 'center';
						break;
				}
				tbar.selectButton(o.button.value);
				this.moveWindow();
			}, this, true);

			win.setHeader(this.STR_IMAGE_PROP_TITLE);
			win.setBody(body);
			this.openWindow(win);
			var loadingIcon = document.createElement('img');
			loadingIcon.setAttribute('src', 'http://myebookmaster.com/img/loading.gif');
			loadingIcon.setAttribute('id', 'imageInsertFormLoading');
			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( "uploaderOverlay" );
			LIGHTHOUSE.widget.Uploader.addListener('contentReady', function(ev){
				LIGHTHOUSE.widget.Uploader.setFileFilters([{description:"Images (jpg, png, gif, bmp)", extensions:"*.jpg;*.png;*.gif;*.bmp"}]);
					
				document.getElementById('uploaderOverlay').style.overflow = 'auto'; // Firefox absolute positioning bug -- it sucks

				var sessionId = document.body.getAttribute('session-id');
				LIGHTHOUSE.widget.Uploader.addListener('uploadStart',	   function(ev){ Dom.addClass('imageInsertForm', 'invisible'); Dom.removeClass('imageInsertFormLoading', 'hide');});
				LIGHTHOUSE.widget.Uploader.addListener('uploadCompleteData', function(ev){ 
					Dom.removeClass('imageInsertForm', 'invisible');
					Dom.addClass('imageInsertFormLoading', 'hide'); 
					this.clearFileList();
					var object = Lang.JSON.parse(ev.data);
					document.getElementById('insertimage_url').value = object.url;
				});

				LIGHTHOUSE.widget.Uploader.addListener('uploadError', function(ev){ alert('There was an error while uploading your image. Try again or contact us at support@myebookmaster.com'); Dom.removeClass('imageInsertForm', 'hide'); });     
				LIGHTHOUSE.widget.Uploader.addListener('fileSelect', function(ev){ this.uploadAll("/books/uploadImage/"+sessionId, "POST", {}, 'uploadedImage'); }, LIGHTHOUSE.widget.Uploader, true);
			});



			//Set event after openWindow..
			Event.onAvailable('insertimage_url', function() {

				this.toolbar.selectButton('insertimage');

				window.setTimeout(function() {
					YAHOO.util.Dom.get('insertimage_url').focus();
					if (blankimage) {
						YAHOO.util.Dom.get('insertimage_url').select();
					}
				}, 50);
				
				if (this.get('localFileWarning')) {
					Event.on('insertimage_link', 'blur', function() {
						var url = Dom.get('insertimage_link');
						if (this._isLocalFile(url.value)) {
							//Local File throw Warning
							Dom.addClass(url, 'warning');
							this.get('panel').setFooter(this.STR_LOCAL_FILE_WARNING);
						} else {
							Dom.removeClass(url, 'warning');
							this.get('panel').setFooter(' ');
						}
					}, this, true);

					Event.on('insertimage_url', 'blur', function() {
						var url = Dom.get('insertimage_url');
						if (url.value && el) {
							if (url.value == el.getAttribute('src', 2)) {
								return false;
							}
						}
						if (this._isLocalFile(url.value)) {
							//Local File throw Warning
							Dom.addClass(url, 'warning');
							YAHOO.log('Local file reference found, show local warning', 'warn', 'Editor');
							this.get('panel').setFooter(this.STR_LOCAL_FILE_WARNING);
						} else if (this.currentElement[0]) {
							Dom.removeClass(url, 'warning');
							this.get('panel').setFooter(' ');
							if (url && url.value && (url.value != this.STR_IMAGE_HERE)) {
								this.currentElement[0].setAttribute('src', url.value);
								var self = this,
									img = new Image();

								img.onerror = function() {
									url.value = self.STR_IMAGE_HERE;
									img.setAttribute('src', self.get('blankimage'));
									self.currentElement[0].setAttribute('src', self.get('blankimage'));
								};

								if (url.value != this.STR_IMAGE_HERE) {
									img.src = url.value;
								}
							}
						}
					}, this, true);
				}
			}, this, true);
		});
	}; // end handleinsertimageclick

	YAHOO.widget.Editor.prototype.cmd_unlink = function(value) {
		this._swapEl(this.currentElement[0], 'span', function(el) {
			el.className = 'yui-non';
		});
		return [false];
	};
	YAHOO.widget.Editor.prototype._handleCreateLinkWindowClose = function() {
		var url = Dom.get('createlink_url'),
			el = this.currentElement[0],
			a = el;
		if (el && url && url.value) {
			var urlValue = url.value;
			if ((urlValue.indexOf(':/'+'/') == -1) && (urlValue.substring(0,1) != '/') && (urlValue.substring(0, 6).toLowerCase() != 'mailto')) {
				if ((urlValue.indexOf('@') != -1) && (urlValue.substring(0, 6).toLowerCase() != 'mailto')) {
					//Found an @ sign, prefix with mailto:
					urlValue = 'mailto:' + urlValue;
				} else {
					/* :// not found adding */
					if (urlValue.substring(0, 1) != '#') {
						urlValue = 'http://' + urlValue;
					}
					
				}
			}
			el.setAttribute('href', urlValue);
		} else {
			var _span = this._getDoc().createElement('span');
			_span.innerHTML = el.innerHTML;
			Dom.addClass(_span, 'yui-non');
			el.parentNode.replaceChild(_span, el);
		}
		this.nodeChange();
		this.currentElement = [];
	};
	YAHOO.widget.Editor.prototype._handleCreateLinkClick = function() {
		var el = this._getSelectedElement();
		if (this._isElement(el, 'img')) {
			this.STOP_EXEC_COMMAND = true;
			this.currentElement[0] = el;
			this.toolbar.fireEvent('insertimageClick', { type: 'insertimageClick', target: this.toolbar });
			this.fireEvent('afterExecCommand', { type: 'afterExecCommand', target: this });
			return false;
		}
		if (this.get('limitCommands')) {
			if (!this.toolbar.getButtonByValue('createlink')) {
				YAHOO.log('Toolbar Button for (createlink) was not found, skipping exec.', 'info', 'Editor');
				return false;
			}
		}
		
		this.on('afterExecCommand', function() {

			var win = new YAHOO.widget.EditorWindow('createlink', {
				width: '415px'
			});
			
			var el = this.currentElement[0],
				url = '',
				title = '',
				target = '',
				localFile = false;
			if (el) {
				if (el.getAttribute('href', 2) !== null) {
					url = el.getAttribute('href', 2);
					if (this._isLocalFile(url)) {
						//Local File throw Warning
						YAHOO.log('Local file reference found, show local warning', 'warn', 'Editor');
						win.setFooter(this.STR_LOCAL_FILE_WARNING);
						localFile = true;
					} else {
						win.setFooter(' ');
					}
				}
				if (el.getAttribute('title') !== null) {
					title = el.getAttribute('title');
				}
				if (el.getAttribute('target') !== null) {
					target = el.getAttribute('target');
				}
				
			}			
			var body = document.createElement('div');
			body.innerHTML = '<label for="createlink_url">' + this.STR_LINK_URL + '<span class="subtext">ex. http://google.com</span></label>'
							 +'<input type="text" name="createlink_url" id="createlink_url" value="' + url + '"' + ((localFile) ? ' class="warning"' : '') + '>';
			
			closeButton = document.createElement('button');
			closeButton.innerHTML = '<span>Done</span>';
			Event.addListener(closeButton, 'click', function(ev){
				Event.stopEvent(ev);
				this.closeWindow();
			}, null, this);
			body.appendChild(closeButton);

			if(!!url){
				var unlink = document.createElement('button');
				unlink.innerHTML = "<span>Remove</span>";
				Event.on(unlink, 'click', function(ev) {
					Event.stopEvent(ev);
					this.execCommand('unlink');
					this.closeWindow();
				}, this, true);
				body.appendChild(unlink);
			}



			win.setHeader(this.STR_LINK_PROP_TITLE);
			win.setBody(body);

			Event.onAvailable('createlink_url', function() {
				window.setTimeout(function() {
					try {
						YAHOO.util.Dom.get('createlink_url').focus();
					} catch (e) {}
				}, 50);
				Event.on('createlink_url', 'blur', function() {
					var url = Dom.get('createlink_url');
					if (this._isLocalFile(url.value)) {
						//Local File throw Warning
						Dom.addClass(url, 'warning');
						YAHOO.log('Local file reference found, show local warning', 'warn', 'Editor');
						this.get('panel').setFooter(this.STR_LOCAL_FILE_WARNING);
					} else {
						Dom.removeClass(url, 'warning');
						this.get('panel').setFooter(' ');
					}
				}, this, true);
			}, this, true);

			this.openWindow(win);
		});
	}; //handlecreatelinkclick

})();





(function(){

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

	var Templates = LIGHTHOUSE.templates;

	LIGHTHOUSE.widget.Tooltip = function(){
	
		var template = new Templates.Tooltip;
		var owner;
		var title;
		var offset = 25;

		return {
			show : function(target){
				owner = target;
				title = target.getAttribute('title');
				target.removeAttribute('title');
				

				var newXY = Dom.getXY(target);
				template.setBody(title);
				template.move([newXY[0] + offset, newXY[1] + offset]);
				template.show();
			}, 
			hide : function(){
				if(owner){
					owner.setAttribute('title', title);
					owner = null;
				}
				template.hide();
			}
		}

	}();

	Event.onDOMReadyConstructor('mouseover', function(target, event){
		if(Dom.hasClass(target, 'tip-icon') && target.getAttribute('title')){
			LIGHTHOUSE.widget.Tooltip.show(target);
		}else{
			LIGHTHOUSE.widget.Tooltip.hide();
		}
	});

})(); 
