var BBCode = Class.create();

BBCode.prototype = {
	SBBtextarea: undefined,
	SBBcontainer: 'BBcontainer',
	SBBcodeSmall: 'b u i  sup sub img',
	SBBcodeFull: 'b u i list sup sub img url',		
	
	initialize: function(version) { 			
		this.SBBtextarea = $$('textarea')[0]
		if(!this.SBBtextarea || !$(this.SBBcontainer)){			
			return;
		}
		this.SBBcontainer = $(this.SBBcontainer);
		
		if(version){
			var SBBcode = this.SBBcodeFull;
		}
		else{
			var SBBcode = this.SBBcodeSmall;
		}
		
	
		var th = this;	
		$w(SBBcode).each(
			function(cSBBcode){ 
				th.SBBcode(cSBBcode);
				$(cSBBcode).observe('click', function(event){ th.SBBclicked(cSBBcode); });
			}
		);
		
		if(version){
			this.SBBfiles();
		}
	},
	
	SBBcode: function (SBBcode){		
		this.SBBcontainer.appendChild(
			Builder.node('div',{
					id: SBBcode,
					onmouseover: "this.addClassName('BBitemHover')", 
					onmouseout: "this.removeClassName('BBitemHover')"
				},
				Builder.node('img', { src: 'js/BBcode/'+ SBBcode +'.gif' })
			)
		);	
	},
	
	SBBclicked: function (SBBcode){		
		// IE
		if(document.selection != undefined){
			var selection = document.selection.createRange().text;
			if(selection){
				document.selection.createRange().text = '['+ SBBcode +']'+ selection +'[/'+ SBBcode +']';
				$(SBBcode).removeClassName('BBitemHover');
				return;
			}
			else{
				this.SBBaddTagAtEnd(SBBcode);
			}
		}
		else{			
			var text = this.SBBtextarea.value;
			var textLength = text.length;
			var selectionStart = this.SBBtextarea.selectionStart;
			var selectionEnd = this.SBBtextarea.selectionEnd;
			// FF, chrome
			if(selectionStart != undefined && selectionEnd != undefined){
				
				// insert single tag
				if((selectionStart == selectionEnd && selectionStart > 0) || textLength > 0){										
					this.SBBtextarea.value = text.substr(0, selectionStart) +
											 '['+ (($(SBBcode).hasClassName('BBitemActive')) ? '/' : '') + SBBcode +']'+  
											 text.substr(selectionStart, textLength);					
				}
				// insert 2 tags around the selection
				else if(selectionEnd > 0){
					this.SBBtextarea.value = text.substring(0, selectionStart) +
											 '['+ SBBcode +']'+  
											 text.substring(selectionStart, selectionEnd) +
											 '[/'+ SBBcode +']'+
											 text.substring(selectionEnd, textLength);
					$(SBBcode).removeClassName('BBitemHover');
					return;
				}
				// add tag add the end
				else{
					this.SBBaddTagAtEnd(SBBcode);
				}				
			}
			else{
				this.SBBsimpleAddTag(SBBcode);
			}
		}
		
		$(SBBcode).removeClassName('BBitemHover').toggleClassName('BBitemActive');		
	},
	
	SBBaddTagAtEnd: function (SBBcode){		
		this.SBBtextarea.value += (($(SBBcode).hasClassName('BBitemActive')) ? '[/'+ SBBcode +']': '['+ SBBcode +']');				
	},
	
	SBBfiles: function (){		
		this.SBBcode('file');
		
	}
	
}

document.observe('dom:loaded', function () { new BBCode( showAdmin ); });