var uagent    = navigator.userAgent.toLowerCase();
var is_safari = ( (uagent.indexOf('safari') != -1) || (navigator.vendor == "Apple Computer, Inc.") );
var is_opera  = (uagent.indexOf('opera') != -1);
var is_ie     = ( (uagent.indexOf('msie') != -1) && (!is_opera) && (!is_safari) );
var is_ie4    = ( (is_ie) && (uagent.indexOf("msie 4.") != -1) );

var is_win    =  ( (uagent.indexOf("win") != -1) || (uagent.indexOf("16bit") !=- 1) );
var ua_vers   = parseInt(navigator.appVersion);

var ie_range_cache = '';
var bbtags   = new Array();

function setFieldName(which)
{
            if (which != selField)
            {
                selField = which;
            }
};


function ins_smile ( text ){
	doInsert(' ' + text + ' ', '', false);
	ie_range_cache = null;
};

function simpletag(thetag)
{
	doInsert("[" + thetag + "]", "[/" + thetag + "]", true);
}

function tag_url()
{
    var FoundErrors = '';
    var thesel = get_sel(eval('fombj.'+ selField))

    if (!thesel) {
        thesel ='My Webpage';
    }

    var enterURL   = prompt(text_enter_url, "http://");
    var enterTITLE = prompt(text_enter_url_name, thesel);

    if (!enterURL) {
        FoundErrors += " " + error_no_url;
    }
    if (!enterTITLE) {
        FoundErrors += " " + error_no_title;
    }

    if (FoundErrors) {
        alert("Error!"+FoundErrors);
        return;
    }

	doInsert("[url="+enterURL+"]"+enterTITLE+"[/url]", "", false);
};

function tag_kp(){var a="",b="";(b=ua_vers>=4&&is_ie&&is_win?document.selection.createRange().text:"")||(b="");(b=prompt("Insert Kinopoisk ID",b))||(a+=" "+error_no_url);a?alert("Error!"+a):doInsert("[center][kp="+b+"][/center]","",false)}
function tag_game(){var a="",b="";(b=ua_vers>=4&&is_ie&&is_win?document.selection.createRange().text:"")||(b="");(b=prompt("Insert Game ID",b))||(a+=" "+error_no_url);a?alert("Error!"+a):doInsert("[center][game="+b+"][/center]","",false)}

function tag_media()
{
    var FoundErrors = '';
    var thesel = get_sel(eval('fombj.'+ selField))

    if (!thesel) {
        thesel ='http://';
    }

    var enterURL = prompt(text_enter_url, thesel);

    if (!enterURL) {
        FoundErrors += " " + error_no_url;
    }

    if (FoundErrors) {
        alert("Error!"+FoundErrors);
        return;
    }

	doInsert("[media="+enterURL+"]", "", false);
};

function tag_flash()
{
    var FoundErrors = '';
    var enterURL   = prompt(text_enter_flash, "http://");

    var size = prompt(text_enter_size, "425,264");

    if (!enterURL) {
        FoundErrors += " " + error_no_url;
    }

    if (FoundErrors) {
        alert("Error!"+FoundErrors);
        return;
    }
	doInsert("[flash="+size+"]"+enterURL+"[/flash]", "", false);

};

function tag_image()
{
    var FoundErrors = '';
    var enterURL   = prompt(text_enter_image, "http://");

    var Title = prompt(img_title, image_align);

    if (!enterURL) {
        FoundErrors += " " + error_no_url;
    }

    if (FoundErrors) {
        alert("Error!"+FoundErrors);
        return;
    }

if (Title == "")
           {
	doInsert("[img]"+enterURL+"[/img]", "", false);
           }
else {
if (Title == "center") {
	doInsert("[center][img]"+enterURL+"[/img][/center]", "", false);
}
else {
	doInsert("[img="+Title+"]"+enterURL+"[/img]", "", false);
	}
 }
};

function tag_video()
{
    var FoundErrors = '';
    var thesel = get_sel(eval('fombj.'+ selField))

    if (!thesel) {
        thesel ='http://';
    }

    var enterURL = prompt(text_enter_url, thesel);

    if (!enterURL) {
        FoundErrors += " " + error_no_url;
    }

    if (FoundErrors) {
        alert("Error!"+FoundErrors);
        return;
    }

	doInsert("[video="+enterURL+"]", "", false);
};

function tag_audio()
{
    var FoundErrors = '';

    var thesel = get_sel(eval('fombj.'+ selField))

    if (!thesel) {
        thesel ='http://';
    }

    var enterURL = prompt(text_enter_url, thesel);

    if (!enterURL) {
        FoundErrors += " " + error_no_url;
    }

    if (FoundErrors) {
        alert("Error!"+FoundErrors);
        return;
    }

	doInsert("[audio="+enterURL+"]", "", false);
};

function tag_email()
{
    var emailAddress = prompt(text_enter_email, "");

    if (!emailAddress) { 
		alert(error_no_email); 
		return; 
	}

    var thesel = get_sel(eval('fombj.'+ selField))

    if (!thesel) {
        thesel ='';
    }

	var Title = prompt(email_title, thesel);

if (!Title) Title = emailAddress;

	doInsert("[email="+emailAddress+"]"+Title+"[/email]", "", false);
};

function doInsert(ibTag, ibClsTag, isSingle)
{
	var isClose = false;
	var obj_ta = eval('fombj.'+ selField);

	if ( (ua_vers >= 4) && is_ie && is_win)
	{
		if (obj_ta.isTextEdit)
		{
			obj_ta.focus();
			var sel = document.selection;
			var rng = ie_range_cache ? ie_range_cache : sel.createRange();
			rng.colapse;
			if((sel.type == "Text" || sel.type == "None") && rng != null)
			{
				if(ibClsTag != "" && rng.text.length > 0)
					ibTag += rng.text + ibClsTag;
				else if(isSingle)
					ibTag += rng.text + ibClsTag;
	
				rng.text = ibTag;
			}
		}
		else
		{
				obj_ta.value += ibTag + ibClsTag;
			
		}
		rng.select();
	ie_range_cache = null;

	}
	else if ( obj_ta.selectionEnd )
	{ 
		var ss = obj_ta.selectionStart;
		var st = obj_ta.scrollTop;
		var es = obj_ta.selectionEnd;
		
		if (es <= 2)
		{
			es = obj_ta.textLength;
		}
		
		var start  = (obj_ta.value).substring(0, ss);
		var middle = (obj_ta.value).substring(ss, es);
		var end    = (obj_ta.value).substring(es, obj_ta.textLength);
		
		if (obj_ta.selectionEnd - obj_ta.selectionStart > 0)
		{
			middle = ibTag + middle + ibClsTag;
		}
		else
		{
			middle = ibTag + middle + ibClsTag;
		}
		
		obj_ta.value = start + middle + end;
		
		var cpos = ss + (middle.length);
		
		obj_ta.selectionStart = cpos;
		obj_ta.selectionEnd   = cpos;
		obj_ta.scrollTop      = st;


	}
	else
	{
		obj_ta.value += ibTag + ibClsTag;
	}

	obj_ta.focus();
	return isClose;
};

function ins_color(buttonElement)
{
	document.getElementById(selField).focus();
	if ( is_ie )
	{
			document.getElementById(selField).focus();
			ie_range_cache = document.selection.createRange();
	}
	$("#cp").remove();
	$("body").append("<div id='cp' title='Цвет' style='display:none'><br /><iframe width=\"154\" height=\"104\" src=\"" + dle_root + "templates/" + dle_skin + "/bbcodes/color.html\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"></iframe></div>");

	$('#cp').dialog({
		autoOpen: true,
		dialogClass: "modalfixed",
		width: 180
	});
	$('.modalfixed.ui-dialog').css({position:"fixed"});
	$('#cp').dialog( "option", "position", ['0','0'] );
};
function setColor(color)
{
		doInsert("[color=" +color+ "]", "[/color]", true );
		$('#cp').dialog("close");
};

function insert_font(value, tag)
{
    if (value == 0)
    {
    	return;
	} 

	doInsert("[" +tag+ "=" +value+ "]", "[/" +tag+ "]", true );
    fombj.bbfont.selectedIndex  = 0;
    fombj.bbsize.selectedIndex  = 0;
};

function get_sel(obj)
{
 if (document.selection)
 {
   if ( is_ie )
   {
		document.getElementById(selField).focus();
		ie_range_cache = document.selection.createRange();
   }
   var s = document.selection.createRange();
   if (s.text){return s.text;}
 }
 else if (typeof(obj.selectionStart)=="number")
 {
   if (obj.selectionStart!=obj.selectionEnd)
   {
     var start = obj.selectionStart;
     var end = obj.selectionEnd;
	 return (obj.value.substr(start,end-start));
   }
 }
 return false;
};

function b_hide_n() {var FoundErrors = '';var b_hide_n = prompt("Какой хайд поставить?",100); if (!b_hide_n){FoundErrors += " ";} if(FoundErrors){alert("ошибка!"+FoundErrors);return;} doInsert("[hide="+b_hide_n+"][/hide]", "", false); }
function spoiler() {var FoundErrors = '';var spoiler = prompt("Введите название спойлера"); if (!spoiler){FoundErrors += " ";} if(FoundErrors){alert("ошибка!"+FoundErrors);return;} doInsert("[spoiler="+spoiler+"][/spoiler]", "", false); }