/*
 * jQuery bbCode & smiley plugin
 *JavaScript Document bbCode control by subBlue design www.subBlue.com
 * Date: 2010-02-02 
 * Version: 1.2
*/

(function($) {
	
	// Check for Browser & Platform for PC & IE specific bits
	// More details from: http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html
	var clientPC = navigator.userAgent.toLowerCase(); // Get client info
	var clientVer = parseInt(navigator.appVersion); // Get browser version
	
	var is_ie = ((clientPC.indexOf("msie") != -1) && (clientPC.indexOf("opera") == -1));
	var is_nav = ((clientPC.indexOf('mozilla')!=-1) && (clientPC.indexOf('spoofer')==-1)
					&& (clientPC.indexOf('compatible') == -1) && (clientPC.indexOf('opera')==-1)
					&& (clientPC.indexOf('webtv')==-1) && (clientPC.indexOf('hotjava')==-1));
	var is_moz = 0;
	
	var is_win = ((clientPC.indexOf("win")!=-1) || (clientPC.indexOf("16bit") != -1));
	var is_mac = (clientPC.indexOf("mac")!=-1);

	$.extend({
		BBCode: function(user_setting){
			$.BBCode.settings = $.extend({}, $.BBCode.defaults, user_setting);	 
			$.addEventToElements($('#' + $.BBCode.settings.ContainerBBCodeID),$.BBCode.settings.TextAreaClass);
			return this;
		}
	});		

	/*$.BBCode.HelpValue = {
		// Helpline messages
		// Moved to user-fordisplay.xd
		b_help: "Bold text: [b]text[/b]  (alt+b)",
		z_help: "Paragraph: [p]text[/p]  (alt+z)",
		i_help: "Italic text: [i]text[/i]  (alt+i)",
		u_help: "Underline text: [u]text[/u]  (alt+u)",
		q_help: "Quote text: [quote]text[/quote]  (alt+q)",
		c_help: "Code display: [code]code[/code]  (alt+c)",
		p_help: "Insert image: [img]http://image_url[/img]  (alt+p)",
		w_help: "Insert URL: [url]http://url[/url] or [url=http://url]URL text[/url]  (alt+w)",
		a_help: "Close all open bbCode tags",
		s_help: "Font color: [color=red]text[/color]  Tip: you can also use color=#FF0000",
		f_help: "Font size: [size=x-small]small text[/size]",
		// Unmoved yet
		l_help: "List: [list]text[/list] (alt+l)",
		o_help: "Ordered list: [list=]text[/list]  (alt+o)"
	}*/
	
	// Define the bbCode tags
	//$.BBCode.arrayBBCode = [ ];
	$.BBCode.bbtags = ['[b]','[/b]','[i]','[/i]','[u]','[/u]','[quote]','[/quote]','[code]','[/code]','[list]','[/list]','[list=]','[/list]','[img]','[/img]','[url]','[/url]','[p]','[/p]' ];
	
	$.BBCode.settings;
	$.BBCode.defaults = {
		TextAreaClass: "txtBBCode",
		ContainerBBCodeID: "Container_BBCode"
		};
	
	$.inputs = function(smiley,context,txtClass){
			var txtarea = $('.' + txtClass,context).get(0);
			var scrollPos = txtarea.scrollTop;
			var strPos = 0;
			var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? 
				"ff" : (document.selection ? "ie" : false ) );
			if (br == "ie") { 
				txtarea.focus();
				var range = document.selection.createRange();
				range.moveStart ('character', -txtarea.value.length);
				strPos = range.text.length;
			}
			else if (br == "ff") strPos = txtarea.selectionStart;
			
			var front = (txtarea.value).substring(0,strPos);  
			var back = (txtarea.value).substring(strPos,txtarea.value.length); 
			txtarea.value=front+smiley+back;
			strPos = strPos + smiley.length;
			if (br == "ie") { 
				txtarea.focus();
				var range = document.selection.createRange();
				range.moveStart ('character', -txtarea.value.length);
				range.moveStart ('character', strPos);
				range.moveEnd ('character', 0);
				range.select();
			}
			else if (br == "ff") {
				txtarea.selectionStart = strPos;
				txtarea.selectionEnd = strPos;
				txtarea.focus();
			}
			txtarea.scrollTop = scrollPos;
		}
		
	// Shows the help messages in the helpline window
	/*$.helpline = function(help)
		$("input[name=helpbox]").val(eval(help + "_help"));
	};*/
	
	// Replacement for arrayname.length property
	$.getarraysize = function(thearray) {
		for (i = 0; i < thearray.length; i++) {
			if ((thearray[i] == "undefined") || (thearray[i] == "") || (thearray[i] == null))
				return i;
			}
		return thearray.length;
	};
	
	// Replacement for arrayname.push(value) not implemented in IE until version 5.5
	// Appends element to the array
	$.arraypush =  function(thearray,value) {
		thearray[ $.getarraysize(thearray) ] = value;
	};
	
	// Replacement for arrayname.pop() not implemented in IE until version 5.5
	// Removes and returns the last element of an array
	$.arraypop = function(thearray) {
		thearraysize = $.getarraysize(thearray);
		retval = thearray[thearraysize - 1];
		delete thearray[thearraysize - 1];
		return retval;
	};
	
	
	// From http://www.massless.org/mozedit/
	$.mozWrap = function(txtarea, open, close)
	{
		var selLength = txtarea.textLength;
		var selStart = txtarea.selectionStart;
		var selEnd = txtarea.selectionEnd;
		if (selEnd == 1 || selEnd == 2)
			selEnd = selLength;
	
		var s1 = (txtarea.value).substring(0,selStart);
		var s2 = (txtarea.value).substring(selStart, selEnd)
		var s3 = (txtarea.value).substring(selEnd, selLength);
		txtarea.value = s1 + open + s2 + close + s3;
		return;
	};
	
	// Insert at Claret position. Code from
	// http://www.faqts.com/knowledge_base/view.phtml/aid/1052/fid/130
	$.storeCaret = function(textEl) {
		if (textEl.createTextRange) 
			textEl.caretPos = document.selection.createRange().duplicate();
	};
	
	
	$.BBCode.bbfontstyle = function(bbopen, bbclose,context,txtClass) {
		var theSelection = false;
		var txtarea = $('.' + txtClass,context).get(0);
	
		if ((clientVer >= 4) && is_ie && is_win) {
			theSelection = document.selection.createRange().text;
			if (!theSelection) {
				txtarea.value += bbopen + bbclose;
				txtarea.focus();
				return;
			}
			document.selection.createRange().text = bbopen + theSelection + bbclose;
			txtarea.focus();
			return;
		}
		else if (txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0))
		{
			$.mozWrap(txtarea, bbopen, bbclose);
			return;
		}
		else
		{
			txtarea.value += bbopen + bbclose;
			txtarea.focus();
		}
		$.storeCaret(txtarea);
	};
	
	$.BBCode.UtilityFunc = 
	{
		getArrayBBCode: function(context){
			return $('input[name=ArrayBBCode]',context).val().split(',');
		},	
		setArrayBBCode: function(context,value){
			var str = '';
			for (var i = 0; i < value.length ; ++i){
				if (value[i] != null && value[i] != 'undefined' && value[i] != '')
					str += value[i] + ',';
			};
			$('input[name=ArrayBBCode]',context).val(str);
		}
	}
	
	$.BBCode.bbstyle = function(bbnumber,context,txtClass) {
		var txtarea = $('.' + txtClass,context).get(0);
		var imageTag = false;
		var donotinsert = false;
		var arrayBBCode = $.BBCode.UtilityFunc.getArrayBBCode(context);
		
		bblast = 0;
		
		if (bbnumber == -1) { // Close all open tags & default button names
			while (arrayBBCode[0]) {
				var butnumber = $.arraypop(arrayBBCode) - 1;
				txtarea.value += $.BBCode.bbtags[butnumber + 1];
								
				var buttext =  $("[name=addbbcode" + butnumber + ']',context).val();				
				 $("[name=addbbcode" + butnumber + ']',context).val(buttext.substr(0,(buttext.length - 1)));

			}
			imageTag = false; // All tags are closed including image tags :D
			txtarea.focus();
			$.BBCode.UtilityFunc.setArrayBBCode(context,arrayBBCode);
			return;
		}
	
		var theSelection = false;
		if ((clientVer >= 4) && is_ie && is_win)
		{
			theSelection = document.selection.createRange().text; // Get text selection
			if (theSelection) {
				// Add tags around selection
				document.selection.createRange().text = $.BBCode.bbtags[bbnumber] + theSelection + $.BBCode.bbtags[bbnumber+1];
				txtarea.focus();
				theSelection = '';
				$.BBCode.UtilityFunc.setArrayBBCode(context,arrayBBCode);
				return;
			}
		}
		else if (txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0))
		{
			$.mozWrap(txtarea, $.BBCode.bbtags[bbnumber], $.BBCode.bbtags[bbnumber+1]);
			$.BBCode.UtilityFunc.setArrayBBCode(context,arrayBBCode);
			return;
		}
	
		// Find last occurance of an open tag the same as the one just clicked
		for (i = 0; i < arrayBBCode.length; i++) {
			if (arrayBBCode[i] == bbnumber+1) {
				bblast = i;
				donotinsert = true;
			}
		}
	
		if (donotinsert) {        // Close all open tags up to the one just clicked & default button names
			while (arrayBBCode[bblast]) {
					butnumber = $.arraypop(arrayBBCode) - 1;
					txtarea.value += $.BBCode.bbtags[butnumber + 1];									
					
					buttext =  $("[name=addbbcode" + butnumber + ']',context).val();				
				 	$("[name=addbbcode" + butnumber + ']',context).val(buttext.substr(0,(buttext.length - 1)));
					
					imageTag = false;
				}
				txtarea.focus();
				$.BBCode.UtilityFunc.setArrayBBCode(context,arrayBBCode);
				return;
		} else { // Open tags
	
			if (imageTag && (bbnumber != 14)) {        // Close image tag before adding another
				txtarea.value += $.BBCode.bbtags[15];
				lastValue = $.arraypop(arrayBBCode) - 1;    // Remove the close image tag from the list
				
				 $("[name=addbbcode14",context).val("Img");// Return button back to normal state
					
				imageTag = false;
			}
	
			// Open tag
			txtarea.value += $.BBCode.bbtags[bbnumber];
			if ((bbnumber == 14) && (imageTag == false)) 
				imageTag = 1; // Check to stop additional tags after an unclosed image tag
			$.arraypush(arrayBBCode,bbnumber+1);
			
			//eval('document.post.addbbcode'+bbnumber+'.value += "*"');
			
			temp = $("[name=addbbcode" + bbnumber + ']',context).val();
			$("[name=addbbcode" + bbnumber + ']',context).val(temp += "*");
			
			txtarea.focus();
			$.BBCode.UtilityFunc.setArrayBBCode(context,arrayBBCode);
			return;
		}
		$.storeCaret(txtarea);
	};
	
	$.addEventToElements = function(context,txtClass)
	{
		//paragraph: p
		$("input[name=addbbcode18]",context).click(function(){
			$.BBCode.bbstyle(18,context,txtClass);
		});
		
		$("input[name=addbbcode18]",context).mouseover(function(){
			$('[name=helpbox]',context).val('Paragraph: [p]text[/p] (alt+z)'); return true;
		});
		//bold: b
		$("input[name=addbbcode0]",context).click(function(){
			$.BBCode.bbstyle(0,context,txtClass);
		});
		
		$("input[name=addbbcode0]",context).mouseover(function(){
			$('[name=helpbox]',context).val('Bold text: [b]text[/b] (alt+b)'); return true;
		});
		//italic: i
		$("input[name=addbbcode2]",context).click(function(){
			$.BBCode.bbstyle(2,context,txtClass);
		});
		
		$("input[name=addbbcode2]",context).mouseover(function(){
			$('[name=helpbox]',context).val('Italic text: [i]text[/i] (alt+i)'); return true;
		});
		//underline: u
		$("input[name=addbbcode4]",context).click(function(){
			$.BBCode.bbstyle(4,context,txtClass);
		});
		
		$("input[name=addbbcode4]",context).mouseover(function(){
			$('[name=helpbox]',context).val('Underline text: [u]text[/u] (alt+u)'); return true;
		});
		///quote
		$("input[name=addbbcode6]",context).click(function(){
			$.BBCode.bbstyle(6,context,txtClass);
		});
		
		$("input[name=addbbcode6]",context).mouseover(function(){
			$('[name=helpbox]',context).val('Quote text: [quote]text[/quote] (alt+q)'); return true;
		});
		//code
		$("input[name=addbbcode8]",context).click(function(){
			$.BBCode.bbstyle(8,context,txtClass);
		});
		
		$("input[name=addbbcode8]",context).mouseover(function(){
			$('[name=helpbox]',context).val('Code display: [code]code[/code] (alt+c)'); return true;
		});
		//img
		$("input[name=addbbcode14]",context).click(function(){
			$.BBCode.bbstyle(14,context,txtClass);
		});
		
		$("input[name=addbbcode14]",context).mouseover(function(){
			$('[name=helpbox]',context).val('Insert image: [img]http://image_url[/img] (alt+p)'); return true;
		});
		///url
		$("input[name=addbbcode16]",context).click(function(){
			$.BBCode.bbstyle(16,context,txtClass);
		});
		
		$("input[name=addbbcode16]",context).mouseover(function(){
			$('[name=helpbox]',context).val('Insert URL: [url]http://url[/url] or [url=http://url]URL text[/url] (alt+w)'); return true;
		});
		//Font Color
		$("select[name=addbbcode20]",context).change(function(){
			$.BBCode.bbfontstyle('[color=' + this.options[this.selectedIndex].value + ']', '[/color]',context,txtClass); this.selectedIndex=0;
		});
		
		$("select[name=addbbcode20]",context).mouseover(function(){
			$('[name=helpbox]',context).val('Font color: [color=red]text[/color] Tip: you can also use color=#FF0000'); return true;
		});
		//Font style
		$("select[name=addbbcode22]",context).change(function(){
			$.BBCode.bbfontstyle('[size=' + this.options[this.selectedIndex].value + ']', '[/size]',context,txtClass); this.selectedIndex=0;
		});
		
		$("select[name=addbbcode22]",context).mouseover(function(){
			$('[name=helpbox]',context).val('Font size: [size=x-small]small text[/size]'); return true;
		});
		
		//smiley
		$("a[title=confused]",context).click(function(){
			$.inputs(' :? ',context,txtClass);
		});
		$("a[title=cool]",context).click(function(){
			$.inputs(' 8) ',context,txtClass);
		});
		$("a[title=redface]",context).click(function(){
			$.inputs(' :oops: ',context,txtClass);
		});
		$("a[title=evil]",context).click(function(){
			$.inputs(' :evil: ',context,txtClass);
		});
		$("a[title=frown]",context).click(function(){
			$.inputs(' :( ',context,txtClass);
		});
		$("a[title=happy]",context).click(function(){
			$.inputs(' :D ',context,txtClass);
		});	
		$("a[title=lol]",context).click(function(){
			$.inputs(' :lol: ',context,txtClass);
		});	
		$("a[title=mad]",context).click(function(){
			$.inputs(' :x ',context,txtClass);
		});	
		$("a[title=razz]",context).click(function(){
			$.inputs(' :p ',context,txtClass);
		});
		$("a[title=cry]",context).click(function(){
			$.inputs(' :cry: ',context,txtClass);
		});
		$("a[title=smile]",context).click(function(){
			$.inputs(' :) ',context,txtClass);
		});
		$("a[title=surprised]",context).click(function(){
			$.inputs(' :o ',context,txtClass);
		});
		$("a[title=rolleyes]",context).click(function(){
			$.inputs(' :roll: ',context,txtClass);
		});
		$("a[title=wink]",context).click(function(){
			$.inputs(' ;) ',context,txtClass);
		});
	}

})(jQuery);

