function e(eid)
{	return document.getElementById(eid);
	}

function Show(eid)
	{
		document.getElementById(eid).style.display='inline';
		}

function ShowBlock(eid)
	{
		document.getElementById(eid).style.display='block';
		}

function Hide(eid)
	{
		document.getElementById(eid).style.display='none';
		}

function ShowHide(eid)
	{
		if (document.getElementById(eid).style.display!='none')
			document.getElementById(eid).style.display='none';
			else
				document.getElementById(eid).style.display='block';
		}


function ShowHideInline(eid)
	{
		if (document.getElementById(eid).style.display!='none')
			document.getElementById(eid).style.display='none';
			else
				document.getElementById(eid).style.display='inline'
		}

function Show_s(eid)
{	e(eid).className='display_block';
	}

function Hide_s(eid)
{
	e(eid).className='display_none';
	}

function ShowHide_s(eid)
{	if (e(eid).className!='display_block')
			e(eid).className='display_block';
			else
				e(eid).className='display_none'
	}

function massShow(idstring)
{
	var mas=idstring.split(',');
	for (var i=0;i<mas.length;i++)
		Show(mas[i]);
	}
function massHide(idstring)
{
	var mas=idstring.split(',');
	for (var i=0;i<mas.length;i++)
		Hide(mas[i]);
	}
function massShowHide(idstring)
{
	var mas=idstring.split(',');
	for (var i=0;i<mas.length;i++)
		ShowHide(mas[i]);
	}

function chPict(eid,pic1,pic2)
	{
		if (document.getElementById(eid).src.indexOf(pic2)<0)
			document.getElementById(eid).src='./images/'+pic2;
			else document.getElementById(eid).src='./images/'+pic1;
		}

function setValue(obj,hfield)
	{
		obj.form[hfield].value=obj.value;		}

function regselect(showId,hideId)
   		{
   			Show(showId);
   			Hide(hideId);
   			}

function fillCheckbox(str1,f,id_start,count)
	{  		for (i=1;i<=count;i++)
  			if (str1.indexOf(f[id_start+i.toString()].value)>=0) f[id_start+i.toString()].checked=true;		}

function formCheckbox(f,id_start,count,outfield)
	{
		i=1;
		rez='';
		for (i=1;i<=count;i++)
			{
				if (f[id_start+i.toString()].checked) rez=rez+', '+f[id_start+i.toString()].value;
				}
		rez=rez.substring(2,rez.length);
		f[outfield].value=rez;
		}

function fillChbox(id_start,count,val)
	{
  		for (i=0;i<count;i++)
  			document.getElementById(id_start+i.toString()).checked=val;
		}

function formChbox(id_start,count)
	{
		rez='';
		for (i=0;i<count;i++)
			{
				if (document.getElementById(id_start+i.toString()).checked) rez=rez+','+document.getElementById(id_start+i.toString()).value;
				}
		rez=rez.substring(1,rez.length);
		return rez;
		}

function valid_email(email_address) {

    // Check the length
    if (email_address.length < 5) {
        return false
    }

    // Check @ and .
    at_location = email_address.indexOf("@")
    dot_location = email_address.lastIndexOf(".")

    if (at_location == -1 || dot_location == -1 || at_location > dot_location ) {
        return false
    }

    // Is there at least one character before @?
    if (at_location == 0) {
        return false
    }

    // Is there at least one character between @ and .?
    if (dot_location - at_location < 2 ) {
        return false
    }

    // Is there at least one character after .?
    if (email_address.length - dot_location < 2) {
        return false
    }

    // Otherwise, it's a valid address, so return true
    return true
}
//
function isValidEmail(elid)
{
	return valid_email(document.getElementById(elid).value)
	}

function isEmpty(ar)
{
	var mas=ar.split(",");
	for (var i=0;i<mas.length;i++)
	{
		if (document.getElementById(mas[i]).value=="")
		{
			alert("Поле "+document.getElementById(mas[i]).caption+" не заполнено!");
			document.getElementById(mas[i]).focus();
			return true;
			}
		}
	return false;
	}

//проверка на пустое поле
function fieldEmpty(elem)
{	rez=false;
	if (elem.value=="" || elem.value==" ") rez=true;
	return rez;
	}

//validates that the entry is a positive or negative number
function isNumber(elem) {
    return isNum(elem.value);
}
function isNum(str) {
    var re= /^[-]?\d*\.?\d*$/;
    str=str.toString();
    if (!str.match(re)) {
        return false;
    }
    return true;
}

function isNumberById(eid)
{
	return isNumber(document.getElementById(eid));	}

function areNumbers(ar)
{
	var mas=ar.split(",");
	for (var i=0;i<mas.length;i++)
	{
		if (!isNumberById(mas[i]))
		{
			alert("Поле  должно быть числом!");
			document.getElementById(mas[i]).focus();
			return false;
			}
		}
	return true;	}

function validateForm(f)
   	{
   		rez=true;
   		rez1=true;
   		rez2=true;
   		rez3=true;
   		rez4=true;
   		for(var i=0;i<f.length;i++)
   			{
   				if (f[i].type=='text' || f[i].type=='password')
   					if ((f[i].id==1)||(f[i].mandatory==1))
   						if (f[i].value=='') rez=false;
   				}
   		if (!rez) {alert('Не все поля заполнены!'); return false};

		if (f['password']!=null)
		if (f['password2']!=null)
		{
   			if (f['password'].value!=f['password2'].value) rez1=false;
   			if (!rez1) alert('Пароль не подтвержден!');
   			}
  		if (f['email']!=null)
  		{
   			if (!valid_email(f['email'].value)) rez2=false;
   			}
   		if (f['price']!=null)
   		{
   			if (!isNumber(f['price'])) {rez3=false;alert('Цена должна являться числом!');return false;}   			}
        if (f['id_catalog']!=null)
        {
        	if (f['id_catalog'].value=='') {rez4=false;alert('Выберите область деятельности из списка!');return false;}        	}

   		if (!rez2) alert('Формат почтового ящика неправильный!');
   		return (rez&&rez2)&&rez1;
   		}

//новая проверка на заполненность формы
function newValidateForm(f)
{	var rez=true;
	for (var i=0;i<f.length && rez==true;i++)
	{        obligatory=f[i].id;
        if (obligatory>0)
        	if (obligatory>=2 && !isNumber(f[i])) {alert('Значение должно быть числом!');f[i].focus();rez=false;}
        		else if (obligatory>=1 && fieldEmpty(f[i])) {alert('Не все поля заполнены!');f[i].focus();rez=false;}
		}
	return rez;
}

function validateField(eid)
{	var rez=true;
	if(document.getElementById(eid).value==''){ alert('Не все поля заполнены!');document.getElementById(eid).focus();rez=false;}
	return rez;
}


//новая проверка на заполненность формы
function newValidateForm(f)
{
	var rez=true;
	for (var i=0;i<f.length && rez==true;i++)
	{
        obligatory=f[i].id;
        if (obligatory>0)
        {
        	if (f[i].name=="pass" && f[i].value!=f['pass2'].value) {alert('Пароль не подтвержден!');f['pass2'].focus();rez=false;}
        	else if (f[i].name=="email" && !valid_email(f[i].value)) {alert('Формат почтового ящика неправильный!');f[i].focus();rez=false;}
        	else if (obligatory>=2 && !isNumber(f[i])) {alert('Значение должно быть числом!');f[i].focus();rez=false;}
        		else if (obligatory>=1 && fieldEmpty(f[i])) {alert('Не все обязательные поля заполнены!');f[i].focus();rez=false;}
		}
	}
	return rez;
}

function TaskbarButtonPress(bnum)
{	e('bt_'+bnum.toString()+'_l').className='bl_pressed';
	e('bt_'+bnum.toString()+'_c').className='content_pressed black';
	e('bt_'+bnum.toString()+'_r').className='br_pressed';
	}

function TaskbarButtonRelease(bnum)
{
	e('bt_'+bnum.toString()+'_l').className='bl';
	e('bt_'+bnum.toString()+'_c').className='content black';
	e('bt_'+bnum.toString()+'_r').className='br';
	}

function excel()
{
	var content="<table>"+document.getElementById('excel').innerHTML+"</table>";
	//var exc=window.open('tools/excel.php','','toolbar,status,titlebar');
	//exc.document.write(content);
	f=document.forms['excel_form'];
	f['exc'].value=content;
	//alert(f['exc'].value);
	f.submit();
	}

function wordDate(data)
{
	var monthNames=new Array('января','февраля','марта','апреля','мая','июня','июля','августа','сентября','октября','ноября','декабря');
	if (data=="") return "";
	return parseInt(data.substring(8,10),10).toString()+' '+monthNames[parseInt(data.substring(5,7),10)-1]+' '+data.substring(0,4);
	}

function setExtData()
{
	e('i_from').value=e('from_ext_id').value;
	e('i_to').value=e('to_ext_id').value;
	e('res_data').innerHTML=wordDate(e('from_ext_id').value)+' - '+wordDate(e('to_ext_id').value);
	Hide('calendarExt');
	}

function updateExtData()
{
	e('res_data').innerHTML=wordDate(e('i_from').value)+' - '+wordDate(e('i_to').value);
	e('from_ext_id').value=e('i_from').value;
	e('to_ext_id').value=e('i_to').value;
	if (e('i_from').value=="" && e('i_to').value==0)
	{		$('#datePick').DatePickerSetDate(['',''],false);
		e('res_data').innerHTML="Весь период";
		}
		else $('#datePick').DatePickerSetDate([e('i_from').value,e('i_to').value], true);
	}

function showExt(x,y)
{
    Show('calendarExt');
    e('calendarExt').style.top=(y+18).toString()+'px';
    e('calendarExt').style.left=(x-200).toString()+'px';
    //$('#datePicker').DatePickerShow();
	}

function setSelectorDate(fromdate,todate)
{	e('i_from').value=fromdate.toString();
	e('i_to').value=todate.toString();
	updateExtData()
	}

function exit_skm() //выход
{	document.forms['exit_form'].submit();
	}

function startSelect()
{	document.forms['selector'].submit();
	}

function selectAllFilials(val) //выбор всех филиалов в селекторе
{
	var content=e('filials_div').innerHTML;
	var parts=content.split('name=');
	var filials=new Array();
	for (var i=1;i<parts.length;i++)
	{
		var tmp=parts[i].split('>');
		var tmp1=tmp[0].split(' ');
		var nm=tmp1[0];
		//alert(nm.charAt(0));
		if (nm.charAt(0)=='"') nm=nm.substr(1,nm.length-2);
		//alert(nm);
		document.forms['selector'][nm].checked=val;
		}
	}

function selectFilials(str1)
{    var f=document.forms['selector'];
    var mas=str1.split(",");
    for (var i=0;i<mas.length;i++) f[mas[i]].checked=true;
	}

function letterNum(numb,gender,valuta,printNull)
{
	hundreds=["","сто","двести","триста","четыреста","пятьсот","шестьсот","семьсот","восемьсот","девятьсот"];
	decimals=["","","двадцать","тридцать","сорок","пятьдесят","шестьдесят","семьдесят","восемьдесят","девяносто"];
	teens=["десять","одиннадцать","двенадцать","тринадцать","четырнадцать","пятнадцать","шестнадцать","семнадцать","восемнадцать","девятнадцать"];
	ones_male=["","один","два","три","четыре","пять","шесть","семь","восемь","девять"];
	ones_female=["","одна","две","три","четыре","пять","шесть","семь","восемь","девять"];

    var rez=hundreds[Math.floor(numb / 100)];
    decim=numb % 100;
    if (decim>=10 && decim<20) rez+=" "+teens[decim-10];
    	else rez+=" "+decimals[Math.floor(decim / 10)]+" "+(gender=="male" ? ones_male[decim % 10] : ones_female[decim % 10]);

	//if (num==0 && printNull) rez="ноль";

    edin=numb % 10;
    decim=numb % 100;
    if (decim>10 && decim<20) padej=2;
    	else if (edin==1) padej=0;
    		else if (edin >=2 && edin<=4) padej=1;
    			else padej=2;

    return rez+" "+(numb!=0 || printNull  ? valuta[padej] : "");
	}

function numToString(number,val,sex)
{
	var result="";
	gender=['','female','male','male'];
	gender[0]=sex;
	valuta=[['','',''],['тысяча','тысячи','тысяч'],['миллион','миллиона','миллионов'],['миллиард','миллиарда','миллиардов']]
	valuta[0]=val;
	for (i=0;number.length>0;i++)
	{
		if (number.length<=3)
		{
			num=number;
			number="";
			}
			else
			{
				num=number.substring(number.length-3);
				number=number.substring(0,number.length-3);
				}
		result=letterNum(num,gender[i],valuta[i],(i>0 ? false : true))+" "+result;
		}
	return result;
	}


function currencyToString(currency,val1,sex1,subval,subsex)
{
	var currencyArray=currency.split(".");
	var str_cur=numToString(currencyArray[0],val1,sex1);
	if (currencyArray.length>1)
	{
		if (currencyArray[1].length>2) currencyArray[1]=currencyArray[1].substring(0,2);
			else if (currencyArray[1].length==1) currencyArray[1]=currencyArray[1].toString()+"0";
		str_cur+=" "+numToString(currencyArray[1],subval,subsex);
		}
	return str_cur;
	}

function checkWM(wmStr)
{
	if (wmStr.length==13)
	{
		if (lettersOnly(wmStr.substring(0,1)) && numbersOnly(wmStr.substring(1))) return true;
			else return false;
		}
	return false;
	}

function isLatin(str1)
{
	var rez=true;
	for (var i=0;i<str1.length;i++)
	{
		var cod=str1.charCodeAt(i);
		rez=(rez && (cod>=65 && cod<=90 || cod>=97 && cod<=122 || cod>=48 && cod<=57 || cod==32));
		}
    return rez;
	}

function lettersOnly(str1)
{
    for (var i=0;i<str1.length;i++)
    {
    	charCode=str1[i];
    	if ((charCode < 'a' || charCode > 'z') && (charCode < 'A' || charCode > 'Z')) return false;
    	}
    return true;
	}
function numbersOnly(str1)
{
    for (var i=0;i<str1.length;i++)
    {
    	charCode=str1[i];
    	if (charCode < '0' || charCode > '9') return false;
    	}
    return true;
	}

function getExtension(str1)
{	if (str1=="") return "";
	var tmp=str1.split(".");
	var ext=tmp[tmp.length-1];
	return ext;
	}

function getClientSTop()
{
	return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop)
}

function getClientSLeft()
{
	return self.pageXOffset || (document.documentElement && document.documentElement.scrollLeft) || (document.body && document.body.scrollLeft)
}

function getClientHeight()
{
  return document.compatMode=='CSS1Compat' ? document.documentElement.clientHeight : window.innerHeight;
}

// utility function to retrieve an expiration date in proper
// format; pass three integer parameters for the number of days, hours,
// and minutes from now you want the cookie to expire (or negative
// values for a past date); all three parameters are required,
// so use zeros where appropriate
function getExpDate(days, hours, minutes) {
    var expDate = new Date( );
    if (typeof days == "number" && typeof hours == "number" &&
        typeof hours == "number") {
        expDate.setDate(expDate.getDate( ) + parseInt(days));
        expDate.setHours(expDate.getHours( ) + parseInt(hours));
        expDate.setMinutes(expDate.getMinutes( ) + parseInt(minutes));
        return expDate.toGMTString( );
    }
}

// utility function called by getCookie( )
function getCookieVal(offset) {
    var endstr = document.cookie.indexOf (";", offset);
    if (endstr == -1) {
        endstr = document.cookie.length;
    }
    return unescape(document.cookie.substring(offset, endstr));
}

// primary function to retrieve cookie by name
function getCookie(name) {
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg) {
            return getCookieVal(j);
        }
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break;
    }
    return "";
}

// store cookie value with optional details as needed
function setCookie(name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + escape (value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

// remove the cookie by setting ancient expiration date
function deleteCookie(name,path,domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

function hideTab(page)
{
    Hide('left_pad');
    Show('img_show_tab');
    Hide('img_hide_tab');
    e('main_pad').style.width="100%";
    setCookie('hide_tab_'+page, 1);
}

function showTab(page)
{
	Hide('img_show_tab');
    Show('img_hide_tab');
    e('left_pad').style.display="block";
    e('left_pad').style.width="200px";
    deleteCookie('hide_tab_'+page);
}

function ShowHideTab(page)
{	if(getCookie('hide_tab_'+page)==1)	//показать панель
	{    	e('left_pad').style.display="block";
    	e('left_pad').style.width="200px";
    	e('main_pad').style.width="100%";
    	e('show_pad').title="Скрыть панель";
    	deleteCookie('hide_tab_'+page);
	}else{ //скрыть
    	Hide('left_pad');
    	e('show_pad').title="Показать панель";
    	e('main_pad').style.width="100%";
    	setCookie('hide_tab_'+page, 1);
	}
}

function str_replace(searchStr,replaceStr,str)
{
	var re = new RegExp(searchStr , "g");
	return str.replace(re, replaceStr);
}

function trimLeft(str) {
  return str.replace(/^\s+/, '');
}

function trimRight(str) {
  return str.replace(/\s+$/, '');
}

function trimBoth(str) {
  return trimRight(trimLeft(str));
}

function ShowHideTitle(eid,x,y)
{
	var div_title=document.getElementById(eid);
 	div_title.style.left=(parseInt(x)-265).toString()+'px';
	if (parseInt(div_title.style.left)+250>screen.width) div_title.style.left=screen.width-210;
	div_title.style.top=(parseInt(y)+5).toString()+'px';
	if (div_title.style.display!='none')
		div_title.style.display='none';
		else
			div_title.style.display='block';
}

function SetHelpMode(mode)
{
	if(getCookie('help_mode')!=mode)
	{
    	setCookie('help_mode',mode);
    	location.reload();
	}
}

//------комментарии----------
function deleteSkmComment(cid,tip)
{
	if (confirm ('Вы уверены, что хотите удалить комментарий/указание?'))
	{
		f=document.forms['comment_del_form'];
		f['delete_comment'].value=cid;
		f['tip'].value=tip;
		f.submit();
		}
	}

function editSkmComment(cid,tip)
{
	Show('skm_comment_edit_'+tip.toString()+'_'+cid.toString());
    Show('skm_edit_edit_'+tip.toString()+'_'+cid.toString());
    Hide('skm_comment_'+tip.toString()+'_'+cid.toString());
    Hide('skm_edit_'+tip.toString()+'_'+cid.toString());
	}

function cancelSkmComment(cid,tip)
{
	Hide('skm_comment_edit_'+tip.toString()+'_'+cid.toString());
    Hide('skm_edit_edit_'+tip.toString()+'_'+cid.toString());
    Show('skm_comment_'+tip.toString()+'_'+cid.toString());
    Show('skm_edit_'+tip.toString()+'_'+cid.toString());
	}

function showHideFilter(pos)
{
	if (e('filter').style.display=='none')
	{
		ShowBlock('filter');
		ShowBlock('filter_top');
		e('filter').style.width="100%";
		e('filter_left').className="inactive_"+pos;
		}
		else
		{
			Hide('filter');
			Hide('filter_top');
			e('filter_left').className="active_"+pos;
			}
	}

function showHidePeriod()
{
	if (e('period').style.display=='none')
	{
		ShowBlock('period');
		ShowBlock('period_top');
		e('period').style.width="100%";
		e('filter_right').className="inactive_right";
		}
		else
		{
			Hide('period');
			Hide('period_top');
			e('filter_right').className="active_right";
			}
	}

function hideLeftTab(page)
{
    Hide('left_tab');
    e('main_tab').style.width="100%";
    e('show_hide_lp_img').src="img/left_panel_show.png";
    setCookie('hide_tab_'+page, 1);
}

function showHideLeftTab(page)
{
	if(getCookie('hide_tab_'+page)==1)	//показать панель
	{
    	e('left_tab').style.display="block";
    	e('left_tab').style.width="157px";
    	e('main_tab').style.width="100%";
    	e('show_hide_lp_img').src="img/left_panel_hide.png";
    	deleteCookie('hide_tab_'+page);
	}else{ //скрыть
    	Hide('left_tab');
    	e('show_hide_lp_img').src="img/left_panel_show.png";
    	e('main_tab').style.width="100%";
    	setCookie('hide_tab_'+page, 1);
	}
}

function ShowHidePopup(id,x,y)
{
	var div_title=document.getElementById('popup_panel');
	if (div_title.style.display!='none')
		div_title.style.display='none';
	else{
		div_title.innerHTML=e(id).innerHTML;
		div_title.style.display='block';
		div_title.style.display='block';
		div_title.style.left=(parseInt(x)-34).toString()+'px';
		div_title.style.top=(parseInt(y)+16).toString()+'px';
	}
}

function check_dir_checkbox(f)
{
	var res=false;
	for (var i=0;i<f.length;i++)
	{
		if (f[i].name.substring(0,13)=="newdirective_")
		{
			if(f[i].checked==true)
				res=true;
		}
	}
	if(res==false)
	{
		alert('Ни один подчиненный не выбран!');
		return false;
	}else return true;
}

function check_add_dir()
{
	if(e('add_to_user').style.display=='none')
	{
		e('add_dir_to1').checked=true;
		e('add_dir_to2').checked=false;
		e('add_dir_to3').checked=false;
	}else{
    	e('add_dir_to1').checked=false;
		e('add_dir_to2').checked=true;
		e('add_dir_to3').checked=false;
	}
}

function set_on_control(id)
{
	if(id=='id_on_control')
	{
		if(e('id_on_control').checked)
		{
			e('add_to_user').style.display='none';
			e('add_dir_to1').checked=true;
		}
	}
	else if(id=='add_to_user')
	{
		if(e('add_to_user').style.display=='block')
			e('id_on_control').checked=false;
	}

}

function directive_submit(f)
{
	if(e('add_to_user').style.display!='none' && e('add_dir_to1').checked!=true)
	{
		f['result'].id='1';
		if(e('add_dir_to4').checked==true || e('add_dir_to2').checked==true)
		{
			f['plan_result'].id='1';
			f['plan_time'].id='1';
		}
		else
		{
			f['plan_result'].id='qwerty';
			f['plan_time'].id='qwerty2';
		}
	}
	else
	{
		f['result'].id='qwerty';
		f['plan_time'].id='qwerty2';
	}
	if(newValidateForm(f) && check_dir_checkbox(f))
		f.submit();
}

function editBookmark(id)
{
	e('edit_bookmark_id').value=id.toString();
	e('bookmark_name').value=e('bookmark_name_'+id.toString()).value;
	e('bookmark_href').value=e('bookmark_href_'+id.toString()).value;
	e('f_edit_bookmark').submit();
}

function deleteBook(id)
{
	if (confirm('Вы уверены, что хотите удалить закладку?'))
	{
		f=document.forms['book_del_form'];
		f['delete_bookmark'].value=id;
		f.submit();
		}
	}

function change_icq_author(val)
{	var s=e('txt_mes').value;
	var arr=s.split('\n');
	arr[arr.length-1]='С уважением, '+val;
	s=arr.join('\n');
	e('txt_mes').value=s;
}

//---------вставка тэгов, смайликов и проч
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_webtv  = (uagent.indexOf('webtv') != -1);
var is_ie     = ( (uagent.indexOf('msie') != -1) && (!is_opera) && (!is_safari) && (!is_webtv) );
var is_ie4    = ( (is_ie) && (uagent.indexOf("msie 4.") != -1) );
var is_moz    = ( (navigator.product == 'Gecko')  && (!is_opera) && (!is_webtv) && (!is_safari) );
var is_ns     = ( (uagent.indexOf('compatible') == -1) && (uagent.indexOf('mozilla') != -1) && (!is_opera) && (!is_webtv) && (!is_safari) );
var is_ns4    = ( (is_ns) && (parseInt(navigator.appVersion) == 4) );
var is_kon    = (uagent.indexOf('konqueror') != -1);

var is_win    =  ( (uagent.indexOf("win") != -1) || (uagent.indexOf("16bit") !=- 1) );
var is_mac    = ( (uagent.indexOf("mac") != -1) || (navigator.vendor == "Apple Computer, Inc.") );
var ua_vers   = parseInt(navigator.appVersion);

function doInsert(ibTag, ibClsTag, isSingle,txt_id)
{
	var isClose = false;
	var obj_ta = e(txt_id);
	//----------------------------------------
	// It's IE!
	//----------------------------------------
	if ( (ua_vers >= 4) && is_ie && is_win)
	{
		if (obj_ta.isTextEdit)
		{
			obj_ta.focus();
			var sel = document.selection;
			var rng = 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)
					isClose = true;
				else
					ibTag += ibClsTag;
				rng.text = ibTag;
			}
		}
		else
		{
			if(isSingle)
			{
				isClose = true;
			}
			obj_ta.value += ibTag;
		}
	}
	//----------------------------------------
	// It's MOZZY!
	//----------------------------------------
	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);
		//-----------------------------------
		// text range?
		//-----------------------------------
		if (obj_ta.selectionEnd - obj_ta.selectionStart > 0)
		{
			middle = ibTag + middle + ibClsTag;
		}
		else
		{
			middle = ibTag + middle + ibClsTag;
			if (isSingle)
			{
				isClose = true;
			}
		}
		obj_ta.value = start + middle + end;
		var cpos = ss + (middle.length);
		obj_ta.selectionStart = cpos;
		obj_ta.selectionEnd   = cpos;
		obj_ta.scrollTop      = st;
	}
	//----------------------------------------
	// It's CRAPPY!
	//----------------------------------------
	else
	{
		if (isSingle)
		{
			isClose = true;
		}
		obj_ta.value = ibTag + ibClsTag+obj_ta.value;
	}
	obj_ta.focus();
	return isClose;
}

function emoticon(theSmilie)
{
	doInsert(" " + theSmilie + " ", "", false,"txt");
}

function insert_tag(tag,id)
{
	doInsert("["+tag+"]", "[/"+tag+"]", false,id);
}

function insert_href(href,id)
{
	doInsert("[a href=\""+href+"\" target=_blank]", "[/a]", false,id);
}

function insert_image(src,src_orig,al,make_link,id)
{
    if(make_link==1)
		doInsert("[a href=\""+src_orig+"\" title=\"Нажмите для увеличения\" target=_blank]"+"[img]"+src+"\" "+al+" class=\"img_top_news\" alt=\"[/img][/a]","",true,id);
    else
		doInsert("[img]"+src+"\" "+al+" class=\"img_top_news\" alt=\"[/img]","",true,id);
}

function insert_image_new(src,al,id)
{
    doInsert("<img src=\""+src+"\" "+al+" class=\"cssshadow mr20 ml-25 mb10 ft\">","",true,id);
}

function preventSelection(element){
  var preventSelection = false;

  function addHandler(element, event, handler){
    if (element.attachEvent)
      element.attachEvent('on' + event, handler);
    else
      if (element.addEventListener)
        element.addEventListener(event, handler, false);
  }
  function removeSelection(){
    if (window.getSelection) { window.getSelection().removeAllRanges(); }
    else if (document.selection && document.selection.clear)
      document.selection.clear();
  }
  function killCtrlA(event){
    var event = event || window.event;
    var sender = event.target || event.srcElement;

    if (sender.tagName.match(/INPUT|TEXTAREA/i))
      return;

    var key = event.keyCode || event.which;
    if (event.ctrlKey && key == 'A'.charCodeAt(0))  // 'A'.charCodeAt(0) можно заменить на 65
    {
      removeSelection();

      if (event.preventDefault)
        event.preventDefault();
      else
        event.returnValue = false;
    }
  }

  // не даем выделять текст мышкой
  addHandler(element, 'mousemove', function(){
    if(preventSelection)
      removeSelection();
  });
  addHandler(element, 'mousedown', function(event){
    var event = event || window.event;
    var sender = event.target || event.srcElement;
    preventSelection = !sender.tagName.match(/INPUT|TEXTAREA/i);
  });

  // борем dblclick
  // если вешать функцию не на событие dblclick, можно избежать
  // временное выделение текста в некоторых браузерах
  addHandler(element, 'mouseup', function(){
    if (preventSelection)
      removeSelection();
    preventSelection = false;
  });

  // борем ctrl+A
  // скорей всего это и не надо, к тому же есть подозрение
  // что в случае все же такой необходимости функцию нужно
  // вешать один раз и на document, а не на элемент
  addHandler(element, 'keydown', killCtrlA);
  addHandler(element, 'keyup', killCtrlA);
}

function restrictRightMouse(evt) {
    evt = (evt) ? evt : ((window.event) ? event : null);
    if (evt) {
        var rightButton = false;
        if ((typeof evt.button != "undefined" && evt.button == 2) ||
            (evt.which && evt.which == 3)) {
            rightButton = true;
        }
        if (rightButton) {
            // process right-click here
            alert("Denied");
            return false;
        } else {
            // process all other clicks here
        }
    }
}

function getMinutes(from,to)
{	if (from=="" || to=="") return 0;
	//echo substr($from,0,2)." ".substr($from,3,2)."<br>";
	var min1=60*(parseInt(from.substring(0,2),10))+parseInt(from.substring(3,5),10);
	var min2=60*(parseInt(to.substring(0,2),10))+ parseInt(to.substring(3,5),10);
	var res=min2-min1;
	if (res<0) res=0;
	if (isNaN(res)) res=0;
	return res;
	}

