/* This code is used internally in Bitrix API and is not intended for public use. This file is subject to change. */

if(typeof(Bitrix) == "undefined"){
	var Bitrix = new Object();
}

Bitrix.BBCodeTag = { 
	b: 		1,	//Bold 
	i: 		2, 	//Italic
	u: 		3,	//Underline
	s: 		4,	//Strike
	quote:	5,
	code:	6,
	a:		7,	//hyperlink
	img:	8,
	color:	9,
	list:	10,
	cut:	11
};

Bitrix.BBCodeUtility = function Bitrix$BBCodeUtility(){
    if(typeof(Bitrix.BBCodeUtility.initializeBase) == "function")
        Bitrix.BBCodeUtility.initializeBase(this);
	this._initialized = false;
}

Bitrix.BBCodeInsertMode = {
	replace:		1, //replace selected
	insertAfter:	2
}; 

Bitrix.BBCodeInsertCursorPosition = {
	beforeCloseTag:	1, 
	afterCloseTag:	2
}; 

Bitrix.BBCodeUtility.prototype = {
	initialize: function(){
		this._initialized = true;
		this._urlRx = new RegExp("^(http|https|news|ftp|aim|mailto)\:\/\/", "i");
		this._palette = null;
		this._strings = {
			UrlTitle : "My site",
			UrlPromptUrl : "Enter full address (URL)",
			UrlPromptTitle : "Enter site name",
			ImgPromptUrl : "Enter full image address (URL)",
			ListFirst : "First Element",
			ListSecond : "Second Element",
			CutTitle : "More...",
			Default : "Default"
		};
	},
	
	setStrings: function(strings)
	{
		this._strings = strings;
	},
	
	insertInTextArea: function(tag, textArea, args){
		if(!(args instanceof Array))
			args = new Array();
			
		switch(tag){
			case Bitrix.BBCodeTag.b:
				this.insertInTextAreaCustomTag("b", textArea, args);				
				break;
			case Bitrix.BBCodeTag.i:
				this.insertInTextAreaCustomTag("i", textArea, args);			
				break;	
			case Bitrix.BBCodeTag.u:
				this.insertInTextAreaCustomTag("u", textArea, args);						
				break;
			case Bitrix.BBCodeTag.s:
				this.insertInTextAreaCustomTag("s", textArea, args);					
				break;
			case Bitrix.BBCodeTag.quote:
				this.insertInTextAreaCustomTag("quote", textArea, args);								
				break;	
			case Bitrix.BBCodeTag.code:
				this.insertInTextAreaCustomTag("code", textArea, args);						
				break;
			case Bitrix.BBCodeTag.cut:
				this.insertInTextAreaCustomTag("cut", textArea, args);			
				break;			
			case Bitrix.BBCodeTag.color:{
				if(args.length == 0)
					args[0] = "#000000";
				this.insertInTextAreaCustomTag("color", textArea, args);			
				break;	
			}
			case Bitrix.BBCodeTag.a:{
				var textAreaSelection = Bitrix.TextAreaSelection.create(textArea);
				var currentTextAreaSelection = textAreaSelection.getSelection();
				var textOriginal = currentTextAreaSelection.text;			
			
				var url = "http://";
				var siteName = this._strings.UrlTitle;
				if(textOriginal.search(this._urlRx) >= 0)
					url = textOriginal;
				else
					siteName = textOriginal;
					
				if((url = window.prompt(this._strings.UrlPromptUrl, url)) == null)
					return;
				if((siteName = window.prompt(this._strings.UrlPromptTitle, siteName)) == null)
					return;
					
				args[0] = url;
				args[1] = siteName;
				this.insertInTextAreaCustomTag("url", textArea, args);					
				break;
			}
			case Bitrix.BBCodeTag.img:{
				var textAreaSelection = Bitrix.TextAreaSelection.create(textArea);
				var currentTextAreaSelection = textAreaSelection.getSelection();
				var textOriginal = currentTextAreaSelection.text;	
				
				var mode = Bitrix.BBCodeInsertMode.insertAfter;
				var url = "http://";
				if(textOriginal.search(this._urlRx) >= 0){
					url = textOriginal;
					mode = Bitrix.BBCodeInsertMode.replace;
				}
					
				if((url = window.prompt(this._strings.ImgPromptUrl, url)) == null)
					return;
					
				args[0] = "";
				args[1] = url;
				this.insertInTextAreaCustomTag("img", textArea, args, mode);					
				break;
			}		
			case Bitrix.BBCodeTag.list:{
				var items = new Array(this._strings.ListFirst, this._strings.ListSecond);
				var stub = "\n";
				for(var i = 0; i < items.length; i++)
					stub += "[*]" + items[i] + "\n";

				args[0] = "1";
				args[1] = stub;
				this.insertInTextAreaCustomTag("list", textArea, args, Bitrix.BBCodeInsertMode.insertAfter);			
				break;
			}		
		}
	},
	
	insertInTextAreaCustomTag: function(tagName, textArea, args, mode, cursorPos){
		if(!(args instanceof Array))
			args = new Array();
		
		if(!mode)
			mode = Bitrix.BBCodeInsertMode.replace; //replace
		
		if(!cursorPos)
			cursorPos = Bitrix.BBCodeInsertCursorPosition.beforeCloseTag;
			
		var value = args.length > 0 ? args[0].toString() : "";
		var contents = args.length > 1 ? args[1].toString() : "";
		
		var textAreaSelection = Bitrix.TextAreaSelection.create(textArea);
		var currentTextAreaSelection = textAreaSelection.getSelection();
		
		var textSelectionStart = currentTextAreaSelection.start;
		var textSelectionEnd = currentTextAreaSelection.end;		
		var textFinalCursorPosition = textSelectionEnd;
		var textOriginal = currentTextAreaSelection.text;
		
		var textModified = contents.length > 0 ? contents : (mode == 1 ? textOriginal : "");
		textModified = (value.length > 0 ? "[" + tagName + "=" + value + "]" : "[" + tagName + "]") + textModified + "[/" + tagName + "]";
		
		var tmpEl = document.createElement("TEXTAREA");
		tmpEl.value = textModified;
		textModified = tmpEl.value; 
		
		if(mode == Bitrix.BBCodeInsertMode.replace){
			textAreaSelection.replaceSelectionByText(currentTextAreaSelection, textModified);
			if(cursorPos == Bitrix.BBCodeInsertCursorPosition.beforeCloseTag)
				textFinalCursorPosition = textSelectionStart + textModified.length - 3 - tagName.length;
			else
				textFinalCursorPosition = textSelectionStart + textModified.length;
		}
		else{
			textAreaSelection.insertAfterSelection(currentTextAreaSelection, textModified);
			if(cursorPos == Bitrix.BBCodeInsertCursorPosition.beforeCloseTag)
				textFinalCursorPosition = textSelectionStart + textOriginal.length + textModified.length - 3 - tagName.length;
			else
				textFinalCursorPosition = textSelectionStart + textOriginal.length + textModified.length;
		}
			
		textAreaSelection.setCursorPosition(textFinalCursorPosition);	
		textAreaSelection.setFocus();
	},
	
	getColorPicker: function()
	{
		if (this._palette != null)
			return this._palette;
		
		this._palette = new Bitrix.UI.ColorPicker();
		
		this._palette.Instantiate(this._strings);
		
		return this._palette;
	},
	
	insertInTextAreaQuotation: function(srcTextArea, dstTextArea, args){
		if(!(args instanceof Array))
			args = new Array();
			
		var srcTextAreaSelection = Bitrix.TextAreaSelection.create(srcTextArea);
		var currentSrcTextAreaSelection = srcTextAreaSelection.getSelection();
		var text = currentSrcTextAreaSelection.text;
		if(text.length == 0)
			text = srcTextAreaSelection.getElementText();
		var author = args.length > 0 ? 	args[0].toString() : "";
		text = (author.length > 0 ? "[b]" + author + "[/b]: " : "") + text;
		
		args[0] = "";
		args[1] = text;
		
		this.insertInTextAreaCustomTag("quote", dstTextArea, args, Bitrix.BBCodeInsertMode.insertAfter, Bitrix.BBCodeInsertCursorPosition.afterCloseTag);
	}
}

Bitrix.BBCodeUtility._instance = null;
Bitrix.BBCodeUtility.getInstance = function(){
	if(this._instance == null){
		this._instance = new Bitrix.BBCodeUtility();
		this._instance.initialize();
	}
	return this._instance;
}

Bitrix.BBCodeUtility.setStrings = function(strings){	
	this.getInstance().setStrings(strings);
}

Bitrix.BBCodeUtility.insertInTextArea = function(tag, textArea, args){	
	this.getInstance().insertInTextArea(tag, textArea, args);
}
Bitrix.BBCodeUtility.getColorPicker = function(){	
	return this.getInstance().getColorPicker();
}

Bitrix.BBCodeUtility.insertInTextAreaQuotation = function(srcTextArea, dstTextArea, args){	
	this.getInstance().insertInTextAreaQuotation(srcTextArea, dstTextArea, args);
}


Bitrix.DocumentSelection = function Bitrix$DocumentSelection()
{
    if(typeof(Bitrix.DocumentSelection.initializeBase) == "function")
        Bitrix.DocumentSelection.initializeBase(this);
	this._initialized = false; 
}

Bitrix.DocumentSelection.prototype = {
    initialize: function(){
		this._initialized = true;
	},
	
	getSelectedText: function(){
		if (document.selection && document.selection.createRange)
			return document.selection.createRange().text;
		else if (window.getSelection)
			return window.getSelection().toString();
		return "";
	}
}

Bitrix.DocumentSelection.create = function(){
	var self = new Bitrix.DocumentSelection();
	self.initialize();
	return self;
}

Bitrix.TextAreaSelection = function Bitrix$TextAreaSelection(){
    if(typeof(Bitrix.TextAreaSelection.initializeBase) == "function")
        Bitrix.TextAreaSelection.initializeBase(this);
	this._initialized = false;
	this._element = null;
}

Bitrix.TextAreaSelection.prototype = {
	initialize: function(textArea){
		var el = null;
		if(Bitrix.TypeUtility.isNotEmptyString(textArea))
			el = document.getElementById(textArea);
		else if(Bitrix.TypeUtility.isDomElement(textArea))
			el = textArea;	
		
		if(el == null)
			throw "TextArea element is not defined!";
			
		if(el.tagName.toUpperCase() != "TEXTAREA")
			throw "Element '" + textAreaEl.id, "'" + " is not a 'TEXTAREA'!";
		
		this._element = el;
		this._initialized = true;
	},
	
	getElement: function(){
		return this._element;
	},
	
	getElementText: function(){
		return this._element.value;
	},
	
	getSelection: function(){
		var result = { start: 0, end: 0, text: "" };
		if(/*@cc_on !@*/true){ //NOT IE
			result.start = this._element.selectionStart;
			result.end = this._element.selectionEnd;
			result.text = this._element.value.substring(result.start, result.end);
		}
		else{	//IE
			this._element.focus();
			var documentRange  = document.selection.createRange().duplicate();
			result.text = documentRange.text;
			var contentsOriginal = this._element.value;
			
			var marker = "", 
			markerCreationTryCount = 0;
		
			while(contentsOriginal.indexOf((marker = "BX_TEXTAREASELECTION_MARKER_#" + (new Date()).valueOf().toString())) != -1){
				if(++markerCreationTryCount > 32)
					throw "Could not create unique marker!";
			}
			documentRange.text = marker + documentRange.text + marker;
			var contentsWork = this._element.value;
			result.start = contentsWork.indexOf(marker);
			result.end = contentsWork.indexOf(marker, result.start + marker.length) - marker.length;	
			
			this._element.value = contentsOriginal;
			//TextRange.moveStart(), TextRange.moveEnd() treat '\r\n' as 1 char!
			var priorSelectionText = contentsOriginal.substring(0, result.start);
			var newLineInPriorSelectionTextCount = 0;
			if(priorSelectionText.length > 0){
				var newLineRx = /\r\n/g;
				while(newLineRx.exec(priorSelectionText) != null)
					newLineInPriorSelectionTextCount++;			
			}
			var elementRange = this._element.createTextRange().duplicate();
	        elementRange.collapse(true);
	        elementRange.moveStart("character", result.start - newLineInPriorSelectionTextCount);
	        elementRange.moveEnd("character", result.end - result.start);
	        elementRange.select();				
		}
		return result;
	},
	
	getSelectionStart: function(){
		return this.getSelection().start;
	},
	
	getSelectionEnd: function(){
		return this.getSelection().end;	
	},
	
	getSelectedText: function(){
		var contents = this._element.value;
		if(contents.length == 0)
			return "";
			
		var selection = this.getSelection();
		return 	selection.text;	
	},
	
	replaceSelectionByText: function(selection, text){
		if(typeof(selection) != "object" || selection == null || !("start" in selection) || !("end" in selection))
			throw "Parameter 'selection' is not a valid!";
			
		if(!Bitrix.TypeUtility.isString(text))
			throw "Parameter 'text' is not a String!";
		
		var contentsOld = this._element.value;
		var contentsNew = contentsOld.substring(0, selection.start) + text + contentsOld.substring(selection.end);
		this._element.value = contentsNew;		
	},
	
	insertAfterSelection: function(selection, text)
	{
		if(typeof(selection) != "object" || selection == null || !("start" in selection) || !("end" in selection))
			throw "Parameter 'selection' is not a valid!";
			
		if(!Bitrix.TypeUtility.isString(text))
			throw "Parameter 'text' is not a String!";
		
		var contentsOld = this._element.value;
		var contentsNew = contentsOld.substring(0, selection.end) + text + contentsOld.substring(selection.end);
		this._element.value = contentsNew;			
	},
	
	replaceSelectedText: function(text){
		if(!Bitrix.TypeUtility.isString(text))
			throw "Parameter 'text' is not a String!";
		
		var contentsOld = this._element.value;
		var selection = this.getSelection();
		
		var contentsNew = contentsOld.substring(0, selection.start) + text + contentsOld.substring(selection.end);
		this._element.value = contentsNew;
	},
	
	setCursorPosition: function(position){
		if(/*@cc_on !@*/true){ //NOT IE
			this._element.setSelectionRange(position, position);
		}
		else{ //IE
			var priorSelectionText = this._element.value.substring(0, position);
			var newLineInPriorSelectionTextCount = 0;
			if(priorSelectionText.length > 0){
				var newLineRx = /\r\n/g;
				while(newLineRx.exec(priorSelectionText) != null)
					newLineInPriorSelectionTextCount++;			
			}			
			var range = this._element.createTextRange();
	        range.collapse(true);			
	        range.moveStart("character", position - newLineInPriorSelectionTextCount);
	        range.moveEnd("character", 0);
	        range.select();			
		}
	},
	
	setFocus: function(){
		this._element.focus();	
	}
}

Bitrix.TextAreaSelection.create = function(textArea){
	var self = new Bitrix.TextAreaSelection();
	self.initialize(textArea);
	return self;
}

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded(); 