/**
jQuery BBcode menu generation script. 
Made for LabCMS, http://labcms.ru
@author Andrew Teologov a.k.a. Defari, teologov.and@gmail.com
*/
/*Solving the problem with ie / opera*/
Function.prototype.bind = function(context) {
    var ob = this;
    return function() {
        return ob.apply(context, arguments);
    };
};

var bb = bb || {};
bb = (function($){
	 this.smiles = [[[':)','smiley.png'],[':S','smiley_confuse.png'],['8)','smiley_cool.png'],[':\'(','smiley_cry.png']],[[':shock:','smiley_eek.png'],['\]:->','smiley_evil.png'],[':D','smiley_grin.png'],[':lol:','smiley_lol.png']],[[':mad:','smiley_mad.png'],[':|','smiley_neutral.png'],[':P','smiley_razz.png'],[':-\[','smiley_red.png']],[[':roll:','smiley_roll.png'],[':(','smiley_sad.png'],['8-O','smiley_surprise.png'],['>:-D','smiley_twist.png']]];
	 this.tags = [['[b]','bold.gif', 'Выделить жирным'],['[i]','italic.gif', 'Выделить курсивом'],['[u]','underline.gif', 'Подчеркнутый текст'],['[s]','s.gif', 'Зачеркнутый текст'],['[quote]','quote.gif', 'Вставить цитату'],['[url]','link.gif', 'Вставить внешнюю ссылку'],['[img]','image.gif', 'Вставить изображение'], ['[smile]','smile.gif', 'Вставить смайлик']];
	 this.element = {
	 	div : {
			id: 'bbMenu',
			clas: 'bbMenu'
		},
		img : {
			src: '/skins/default/images',
			alt: '',
			a: '',
			tag: '',
			id: '',
			events:''
		},
	 };
	 this.smiles_table = "smile_list-";
	 //bbcode init function
	 this.bbcode = function(id){
		 if(!id) return false;
		var menu=$('<div>', {'class': 'bbMenu', 'id':'bbMenu-'+id});
		for (var i = 0; this.tags[i]; ++i)
		{
			if (this.tags[i][0]=='[smile]' && !this.smiles.length) continue;
			$(menu).append($('<a>', {'title':this.tags[i][0], 'tag':this.tags[i][0], 'id':'bbtag_'+this.tags[i][0]+'-'+id, 
			'onclick':"bb.getTag(this); return false;"}).append($('<img>', {'src':this.element.img.src+'/buttons/'+this.tags[i][1], 'alt':this.tags[i][0]})));
		}
		
		$(menu).append($('<table>', {'id':'smile_list-'+id, 'class':'smile_list',}).css('display','none'));
		$("#"+id).before(menu);
		$('body,a').bind("click", function(e){if ($(e.target).parent().attr('tag')!='[smile]') $('.smile_list').hide();}.bind(this));
	 };
	 
	 this.getTag = function(tag){
		var tagAtr = $(tag).attr('tag');
		var tagId = $(tag).attr('id');
		if (tagAtr=='[smile]') this.make_smileList(tag,tagAtr,tagId);
		else if (tagAtr=='[url]') this.insert_url(tag);
		else if (tagAtr=='[quote]') this.insert_quote('','',this.getId(tagId));
		else if (tagAtr=='[img]') this.insert_img(tag);
		else
		{
			end=tagAtr.replace(/\[/,'[/');
			this.insertTag(tagAtr, end, this.getId($(tag).attr('id')));
		}
	 };
	 
	 this.insert_img = function(tag)
	 {
		if (!this.getSel(this.getId($(tag).attr('id'))))
		{
			url=prompt("введите адрес картинки", "");
			if (!url) this.insertTag('[img]','[/img]', this.getId($(tag).attr('id')));
			else this.insertTag('[img]'+url+'[/img]','', this.getId($(tag).attr('id')));
		}
		else
		{
			this.insertWithSelection('[img]','[/img]', this.getId($(tag).attr('id')));
		}
	 };
	 
	 this.make_smileList = function(obj,smile, id){
		var table = '#'+this.smiles_table+this.getId(id);
		if ($(table).css("display")=="table"){
			$(table).hide();
			return;
		}
			if (!$(table).attr('ready'))
			{
				var coord=$(obj).position();
				$(table).attr('ready', 'true');
				for (var i = 0; this.smiles[i]; ++i)
				{
					var tr=$('<tr>');
					for (var j = 0; this.smiles[i][j]; ++j)
					{
						$(tr).append($("<td>", {'height':'20px', 'width':'20px'}).append($("<a>",{'title':this.smiles[i][j][0], 'tag':this.smiles[i][j][0],'class':'bbsmile-'+this.getId(id),'onclick': "bb.insert_smile(this); return false;"}).append($("<img>", {'src':this.element.img.src+'/smiles/'+this.smiles[i][j][1], 'alt':this.smiles[i][j][0]}))));
					}
					$(table).append(tr);
				}
				$(table).css({"position": "absolute","left": coord.left,"top":coord.top+20+'px',"width":"auto","background-color":"white"}).show();
			}
			else
			{
				var coord=$(obj).position();
				$(table).css({"position": "absolute","left": coord.left,"top":coord.top+20+'px',"width":"auto","background-color":"white"}).show();
			}
			//console.info(obj);
	 };
	 
	 this.insert_url = function(tag)
	 {
		var url=prompt("введите URL", "");
		if (!url) {this.insertTag('[url]','[/url]', this.getId($(tag).attr('id'))); return true;}
		if (url && !url.match(/\//) && !url.match(/^ftp|https?:\/\//)) url='http://'+url;
		
		if (!this.getSel(this.getId($(tag).attr('id'))))
		{
			text=prompt("введите текст ссылки", "");
			if(text) url='[url="'+url+'"]'+text+'[/url]';
			else  url='[url]'+url+'[/url]';
			this.insertTag(url,'', this.getId($(tag).attr('id')));
		}
		else
		{
			this.insertWithSelection('[url="'+url+'"]' ,'[/url]', this.getId($(tag).attr('id')));
		}
	 };
	 
	 this.insert_quote = function(text, author, textarea)
	 {
		if (!text) text='';
		if (author && text) this.insertTag('[quote="'+author+'"]'+text+'[/quote]', '', textarea);
		else this.insertTag('[quote]','[/quote]', textarea);
	 };
	 
	 this.getId = function(text)
	 {
		return text.match(/^.+?-(.+)$/)[1];
	 };
	 
	 this.insert_smile = function(smile)
	 {
		 //console.info(smile);
		$('#smile_list-'+this.getId($(smile).attr('class'))).css('display', 'none');
		this.insertTag($(smile).attr('tag'), '', this.getId($(smile).attr('class')));
	 };
	 
	 /*check if exisists there any selection*/
	 this.insertWithSelection = function(start,end,textarea)
	 {
		var element = $('#'+textarea)[0];
		if (document.selection)
		{
			element.focus();
			sel = document.selection.createRange();
			sel.text = start + sel.text + end;
			//console.info("is selection");
		}
		else if ('selectionStart' in element || 'selectionStart' in element == '0')
		{
			element.focus();
			var startPos = element.selectionStart;
			var endPos = element.selectionEnd;
			element.value = element.value.substring(0, startPos) + start + element.value.substring(startPos, endPos) + end + element.value.substring(endPos, element.value.length);
			return element;
		}
		
		  else
		  	return element.value += start + end;
	 };
	 
	  this.insertTag = function(text1, text2, textarea)
	 {
		var textarea = $('#'+textarea)[0];
		// Can a text range be created?
		if (typeof(textarea.caretPos) != "undefined" && textarea.createTextRange) {
			var caretPos = textarea.caretPos, temp_length = caretPos.text.length;
			caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text1 + caretPos.text + text2 + ' ' : text1 + caretPos.text + text2;
	
			if (temp_length == 0) {
				caretPos.moveStart("character", -text2.length);
				caretPos.moveEnd("character", -text2.length);
				caretPos.select();
			}
			else
				textarea.focus(caretPos);
		}
		// Mozilla text range wrap.
		else if (typeof(textarea.selectionStart) != "undefined") {
			var begin = textarea.value.substr(0, textarea.selectionStart);
			var selection = textarea.value.substr(textarea.selectionStart, textarea.selectionEnd - textarea.selectionStart);
			var end = textarea.value.substr(textarea.selectionEnd);
			var newCursorPos = textarea.selectionStart;
			var scrollPos = textarea.scrollTop;
	
			textarea.value = begin + text1 + selection + text2 + end;
	
			if (textarea.setSelectionRange) {
				if (selection.length == 0)
					textarea.setSelectionRange(newCursorPos + text1.length, newCursorPos + text1.length);
				else
					textarea.setSelectionRange(newCursorPos, newCursorPos + text1.length + selection.length + text2.length);
				textarea.focus();
			}
			textarea.scrollTop = scrollPos;
		}
		// Just put them on the end, then.
		else {
			textarea.value += text1 + text2;
			textarea.focus(textarea.value.length - 1);
		}
	 };
	 // get the selection
	this.getSel = function (id) {
				//is this a BUG of jQuery?
				textarea = $('#'+id)[0];
				textarea.focus();
				scrollPosition = textarea.scrollTop;
				if (document.selection) {
					selection = document.selection.createRange().text;
					if ($.browser.msie) { // ie
						var range = document.selection.createRange(), rangeCopy = range.duplicate();
						rangeCopy.moveToElementText(textarea);
						caretPosition = -1;
						while(rangeCopy.inRange(range)) {
							rangeCopy.moveStart('character');
							caretPosition ++;
						}
					} else { // opera
						caretPosition = textarea.selectionStart;
					}
				} else { // gecko & webkit
					caretPosition = textarea.selectionStart;

					selection = textarea.value.substring(caretPosition, textarea.selectionEnd);
				} 
				return selection;
			};

	 return this;		   
}).call(bb || {},jQuery);
							  
jQuery(document).ready(function($){
		$.each($("textarea.bbcode, input.bbcode"),function(k,v){
            bb.bbcode($(v).attr("id"));
        }.bind(this));
});