/**
 * @file-overview: Completely re-written functions for cross-browser compatibility.
 * @note: Confirmed working in Safari 2, Firefox 2, Camino 1.5, Internet Explorer 6, Internet Explorer 7
 * @author: Richard Herrera <http://doctyper.com>
 */

var BB = {
	ID : function(id) {
		return document.getElementById(id);
	},
	Node : {
		toggle : function(e) {
			(new RegExp("(?:^|\\s+)" + "hide" + "(?:\\s+|$)").test(e.className)) ? BB.Node.show(e) : BB.Node.hide(e);
		},
		hide : function(e) {
			if (!(new RegExp("hide", "i").test(e.className))) {
				e.className = e.className + ((e.className.length > 0) ? " " : "") + "hide";
			}
		},
		show : function(e) {
			e.className = e.className.replace(new RegExp(("hide" + "\s?"), "i"), "").replace(/^\s?|\s?$/g, "");
			if (e.className === "") {
				e.removeAttribute("class");
			}
		}
	},
	
	whichFormat : function() {
		if (BB.ID("BBBar")) {
			var type,
			    bbcode = BB.ID("Radio_BBCode"),
			    html = BB.ID("Radio_Html"),
			    text = BB.ID("Radio_Text"),
			    that = BB.whichFormat;
			if (bbcode && bbcode.checked) {
				that.type = "BBCode";
			} else if (html && html.checked) {
				that.type = "Html";
			} else if (text && text.checked) {
				that.type = "Text";
			}
			BB.closeButton();
		}
	},

	hidePopups : function(Smilies) {
		var nodes = BB.ID("BBBar").getElementsByTagName("ul");
		for (var i = 0, j = nodes.length; i < j; i++) {
			BB.Node.hide(nodes[i]);
		}
	},
	
	closeButton : function() {
		var nodes = BB.ID("BBBar").getElementsByTagName("li");
		for (var i = 0, j = nodes.length; i < j; i++) {
			if (nodes[i].className === "close") {
				nodes[i].onclick = function() {
					BB.Node.hide(this.parentNode);
				};
			}
		}
	},

	getSelectedText : function(aTag, eTag, selection) {
		var input = BB.ID("CommentBox");

		if (!input) {
			return;
		}

		if (!selection) {
			selection = "";
		}

		if (eTag === null) {
			eTag = "";
		}

		input.focus();
		var pos, insText;
		/* for Internet Explorer */
		if (typeof document.selection !== "undefined") {
			var range = document.selection.createRange();
			insText = range.text;
			if (!insText) {
				insText = selection;
			}
			range.text = aTag + insText + eTag;
			range = document.selection.createRange();
			if (insText.length === 0) {
				range.move("character", -eTag.length);
			}
			else {
				range.moveStart("character", aTag.length + insText.length + eTag.length);
			}
			range.select();
		} else if (typeof input.selectionStart !== "undefined") {
			/* For everyone else */
			var start = input.selectionStart,
			    end = input.selectionEnd;

			if ((start === 0) && (end === 0)) {
				insText = selection;
			} else {
				insText = input.value.substring(start, end);
			}

			input.value = input.value.substr(0, start) + aTag + insText + eTag + input.value.substr(end) ;
			if (insText.length === 0) {
	    		pos = start + aTag.length;
			} else {
				pos = start + aTag.length + insText.length + eTag.length;
			}
			input.selectionStart = pos;
			input.selectionEnd = pos;
		} else {

			/* OMFG WTF BBQ ?!?!?!?! */
			var re = new RegExp('^[0-9]{0,3}$');
			while(!re.test(pos)) {
				pos = prompt("Einfügen an Position (0.." + input.value.length + "):", "0");
			}

			if(pos > input.value.length) {
				pos = input.value.length;
			}
			insText = prompt("Please insert the text, that should be formatted:");
			input.value = input.value.substr(0, pos) + aTag  + insText + eTag + input.value.substr(pos);
		}
		return false;
	},
	
	insert : function(aTag, eTag, Smilies) {
		BB.hidePopups(Smilies);
		var format = BB.whichFormat.type;
		
		if (!eTag) {
			eTag = aTag;
		}

		if (format != "Text") {
			if (format == "BBCode") {
				aTag = "[" + aTag + "]";
				eTag = "[/" + eTag + "]";
			} else if (format == "Html") {
				if (aTag == "b") {
					aTag = "<strong>";
					eTag = "<\/strong>";
				} else if (aTag == "i") {
					aTag = "<em>";
					eTag = "<\/em>";
				} else if (aTag == "s") {
					aTag = "<strike>";
					eTag = "<\/strike>";
				} else {
					aTag = "<" + aTag + ">";
					eTag = "<\/" + eTag + ">";
				}
			}
			BB.getSelectedText(aTag, eTag);
		}
	},
	
	doTube : function() {
		var tubes = document.getElementsByTagName("div");
		for (var i = 0, j = tubes.length; i < j; i++) {
			if (tubes[i] && (/youtube/).test(tubes[i].className)) {
				if (window.console && console.firebug) {
					console.log(tubes[i].firstChild);
				}
				if (tubes[i].firstChild) {
					
					var link = tubes[i].firstChild.nodeValue.replace(/watch\?v=/, "/v/");
					
					var oWrap = document.createElement("div");
					oWrap.innerHTML = '<object type="application/x-shockwave-flash" data="' + link + '" width="425" height="355"><param name="movie" value="' + link + '" /></object>';
					tubes[i].parentNode.replaceChild(oWrap, tubes[i]);
				}
			}
		}
	},
	
	insertURL : function(Smilies) {
		BB.hidePopups(Smilies);
		BB.Node.toggle(BB.ID("BBBarURLDetails"));
		var format = BB.whichFormat.type,
		    submit = BB.ID("URLSubmit");

		this.Submit = function() {
			var message = BB.ID("URL").value,
			    selection = BB.ID("URLText").value;

			if (!selection) {
				selection = message;
			}
			if (message) {
				var aTag, eTag;
				if (format == "BBCode") {
					aTag = "[url=" + message + "]";
					eTag = "[/url]";
				} else if (format == "Html") {
					aTag = "<a href=\"" + message + "\">";
					eTag = "<\/a>";
				}
				BB.getSelectedText(aTag, eTag, selection);
			}
			BB.Node.toggle(BB.ID("BBBarURLDetails"));
			return false;
		};
		
		if (format != "Text") {
			var inputs = BB.ID("BBBarURLDetails").getElementsByTagName("input"),
		       _this = this;
			for (var i = 0, j = inputs.length; i < j; i++) {
				inputs[i].onkeypress = function(e) {
					e = e || window.event;
					if (e.keyCode == 13) {
						_this.Submit();
					}
					return false;
				};
			}
			submit.onclick = _this.Submit;
		}
	},

	insertMail : function(Smilies) {
		BB.hidePopups(Smilies);
		BB.Node.toggle(BB.ID("BBBarMailDetails"));
		var format = BB.whichFormat.type,
		    submit = BB.ID("mailSubmit");

		if (format != "Text") {
			submit.onclick = function() {
				var message = BB.ID("mailURL").value,
				    selection = BB.ID("mailText").value;
				
				if (!selection) {
					selection = message;
				}
				if (message) {
					var aTag, eTag;
					if (format == "BBCode") {
						aTag = "[url=" + message + "]";
						eTag = "[/url]";
					} else if (format == "Html") {
						aTag = "<a href=\"" + message + "\">";
						eTag = "<\/a>";
					}
					BB.getSelectedText(aTag, eTag, selection);
				}
				BB.Node.toggle(BB.ID("BBBarMailDetails"));
				return false;
			};
		}
	},

	insertImage : function(Smilies) {
		BB.hidePopups(Smilies);
		BB.Node.toggle(BB.ID("BBBarImageDetails"));
		var format = BB.whichFormat.type,
		    submit = BB.ID("imageSubmit");

		if (format != "Text") {
			submit.onclick = function() {
				if (BB.insertImage.value) {
					var aTag, eTag;
					if (format == "BBCode") {
						aTag = "[img]";
						eTag = "[/img]";
						BB.getSelectedText(aTag, eTag, BB.insertImage.value);
					} else if (format == "Html") {
						aTag = "<img src=\"" + BB.insertImage.value + "\" \/>";
						eTag = null;
						BB.getSelectedText(aTag, eTag);
					}
				}
				BB.Node.toggle(BB.ID("BBBarImageDetails"));
				return false;
			};
			BB.listenForImage();
		}
	},
	
	listenForImage : function() {
		var target = BB.ID("imageURL"),
		    submit = BB.ID("imageSubmit");
		BB.loadImage(target);
		target.onkeyup = target.onmouseover = function() {
			BB.loadImage(this);
			return true;
		};
	},
	
	loadImage : function(e) {
		// listen for image file names
		var value = e.value,
		    preview = BB.ID("imagePreview"),
		    image = e.parentNode.getElementsByTagName("img")[0];
		
		if (image && image.getAttribute("src") !== value) {
			image.parentNode.removeChild(image);
		}
		
		// if an extension exists
		if ((/\.jpg/.test(value)) || (/\.gif/.test(value)) || (/\.png/.test(value)) || (/\.jpeg/.test(value))) {
			if (!preview) {
				preview = document.createElement("div");
				preview.setAttribute("id", "imagePreview");
				e.parentNode.appendChild(preview);
			}
			BB.Node.show(preview);
			if (!image) {
				image = document.createElement("img");
				image.setAttribute("src", e.value);
				preview.appendChild(image);
			} else if (image.getAttribute("src") !== e.value) {
				image.setAttribute("src", e.value);
			}
			
			if (!(image.style.maxWidth) || (!!(document.childNodes && !document.all && !navigator.taintEnabled))) {
				// IE6 & Safari need help understanding max-width
				var containerWidth = 148; // Block width
				
				// If the image is WIDER than the container...
				if (image.width > containerWidth) {
					image.height = image.height * (containerWidth / image.width); 
					image.width = containerWidth; 
				}
				// End Resizing
			}
			
			BB.insertImage.value = e.value;
		} else {
			if (preview) {
				BB.Node.hide(preview);
			}
		}
	},
	
	align : function(direction, Smilies) {
		BB.hidePopups(Smilies);
		var format = BB.whichFormat.type;

		if (format != "Text") {
			var selection = BB.getSelection();
			if (format == "BBCode") {
				aTag = "[align=" + direction + "]";
				eTag = "[/align]";
			} else if (format == "Html") {
				aTag = "<div style=\"text-align: "+ direction + ";\">";
				eTag = "<\/div>";
			}
			BB.getSelectedText(aTag, eTag, selection);
		}
	},
	
	list : function(type, Smilies) {
		BB.hidePopups(Smilies);
		var format = BB.whichFormat.type;

		if (format != "Text") {
			if (type == "u") {
				if (format == "BBCode") {
					aTag = "[ulist]\n[li]";
					eTag = "[/li]\n[/ulist]";
				} else if (format == "Html") {
					aTag = "<ul>\n<li>";
					eTag = "</li>\n</ul>";
				}
			} else if (type == "o") {
				if (format == "BBCode") {
					aTag = "[list]\n[li]";
					eTag = "[/li]\n[/list]";
				} else if (format == "Html") {
					aTag = "<ol>\n<li>";
					eTag = "</li>\n</ol>";
				}
			}
			BB.getSelectedText(aTag, eTag);
		}
	},
	
	quotetext : function(Smilies) {
		BB.hidePopups(Smilies);
		var format = BB.whichFormat.type;

		if (format != "Text") {
			if (format == "BBCode") {
				aTag = "[quote]";
				eTag = "[/quote]";
			} else if (format == "Html") {
				aTag = "<blockquote><p>";
				eTag = "<\/p><\/blockquote>";
			}
		}
		BB.getSelectedText(aTag, eTag);
	},
	
	showColor : function() {
		BB.hidePopups();
		var picker = BB.ID("BBBarColorPicker");
		
		var nodes = picker.getElementsByTagName("li"),
		    node, hex;
		for (var i = 0, j = nodes.length; i < j; i++) {
			nodes[i].onclick = function() {
				hex = this.className.split("hex_")[1];
				BB.writeColor(hex);
			};
		}
		
		if (picker) {
			BB.Node.toggle(picker);
		}
	},

	writeColor : function(color) {
		BB.hidePopups();
		var format = BB.whichFormat.type;

		if (format != "Text") {
			if (format == "BBCode") {
				aTag = "[color=#" + color + "]";
				eTag = "[/color]";
			} else if (format == "Html") {
				aTag = "<span style=\"color:#"+ color + ";\">";
				eTag = "<\/span>";
			}
			BB.getSelectedText(aTag, eTag);
		}
	},
	
	showFont : function() {
		BB.hidePopups();
		var picker = BB.ID("BBBarFontPicker");
		if (picker) {
			BB.Node.toggle(picker);
		}
	},

	writeFont : function(font) {
		BB.hidePopups();
		var format = BB.whichFormat.type;

		if (format != "Text") {
			if (format == "BBCode") {
				aTag = "[font=" + font + "]";
				eTag = "[/font]";
			}
			if (format == "Html") {
				aTag = "<span style=\"font-family:" + font + ";\">";
				eTag = "<\/span>";
			}
			BB.getSelectedText(aTag, eTag);
		}
	},

	insertselFont : function() {
		var format = BB.whichFormat.type;
		if (format != "Text") {
			var font = document.forms[0].fontpicker.value;
			document.forms[0].fontpicker.value = "";
			if (format == "BBCode") {
				aTag = "[font=\"" + font + "\"]";
				eTag = "[/font]";
			} else if (format == "Html") {
				aTag = "<span style=\"font-family:" + font + ";\">";
				eTag = "\</span>";
			}
		}
	},

	BBformatselectchanged : function() {
		BB.whichFormat();
		var format = BB.whichFormat.type;
		BB.hidePopups();
		if (format == "Html" || format == "BBCode") {
			BB.Node.show(BB.ID("BBBar"));
		} else {
			BB.Node.hide(BB.ID("BBBar"));
		}
	},

	BBformatselectchangedwv : function() {
		BB.whichFormat();
		var format = BB.whichFormat.type;
		BB.hidePopups();
		if (format == "Html" || format == "BBCode") {
			BB.Node.show(BB.ID("BBBar"));
		} else {
			BB.Node.hide(BB.ID("BBBar"));
		}
	},

	insertBBSmilie : function() {
		BB.hidePopups();
		BB.Node.toggle(BB.ID("BBBarSmilies"));
	},
	
	getSelection : function() {
		var str, range;
		if (document.getSelection) {
			range = BB.ID("CommentBox");
			str = document.getSelection() || range.value.substring(range.selectionStart, range.selectionEnd);
		} else if (document.selection && document.selection.createRange) {
			range = document.selection.createRange();
			str = range.text;
		} else {
			str = false;
		}
		return str;
	}

};

window.onload = function() {
	BB.whichFormat();
	BB.doTube();
};
