function conv($1,$2){
		 var text="";
	
         var foto = /\S+\.(jpg|jpeg)$/i;
         var image = /\S+\.(gif|png)$/i;
		 var youtube_match = /http:\/\/(www\.)?youtube\.com\/watch\?(?:.*&)?v=([A-Za-z0-9_\-]+)(&.*)?/i;
		 var smotri_match = /http:\/\/(www\.)?smotri\.com\/video\/view\/\?id=([A-Za-z0-9_\-]+)(&.*)?/i;
		 var rutube_match = /http:\/\/(www\.)?rutube\.ru\/tracks\/[0-9]+\.html\?v=([A-Za-z0-9_\-]+)(&.*)?/i;
		 var videomail_match = /http:\/\/(www\.)?video\.mail\.ru\/(.+)\.html(\?.+)?/i;
         var user = /http:\/\/(www\.)?shax-dag\.ru.*info_name=.*/i;
         var internal_link=/^(http:\/\/(www\.)?shax-dag\.ru)/i;
		 //фотография JPEG
         if(foto.test($2)) return " <div style='margin:10px'><a href='"+$2+"' class='highslide' onclick='return hs.expand(this)' target=_blank><img src='tools/resize.php?f="+$2+"&w=150' border=0 class='foto' width=150 hspace=10 vspace=5></a></div> ";
         //фотография GIF PNG
		 else if(image.test($2)) return " <img src='"+$2+"'> ";
		 // ссылка на страницу соседа
         else if(user.test($2)) return " <a href='"+$2+"'>ссылка на соседа</a> ";
		 //ссылка на видео youtube
		 else if  (youtube_match.test($2)){
			text=$2;
			text=text.replace(youtube_match,youtube_conv);	
			return text;
		 }	
		else if  (smotri_match.test($2)){
			text=$2;			
			text=text.replace(smotri_match,smotri_conv);		
			return text;
			
		}
		else if  (rutube_match.test($2)){
			text=$2;			
			text=text.replace(rutube_match,rutube_conv);		
			return text;
			
		 }	
		else if  (videomail_match.test($2)){
			text=$2;			
			text=text.replace(videomail_match,videomail_conv);		
			return text;
			
		 }			 
		 //внутренняя ссылка
         else if(internal_link.test($2)){
             var internal_link1=/http:\/\/(www\.)?shax-dag\.ru(\/)+(login\.php)|(logout\.php)|(profile\.php)|(messages\.php)|(friends\.php)|(ajax\/delete_usersfotos\.php)/i;
             if(internal_link1.test($2))
                 return $2;
             else
                 return " <a href='"+$2+"'>ссылка на страницу</a> ";
         }
		 //внешние ссылки
         else return " <a href='away.php?url="+encodeURIComponent($2)+"'>"+$2+"</a> ";
}
function source($1,$2,$3,$4){
         if($2=="video")
            return "<div> <a href='comments.php?base=clips&t_key="+$3+"'><span style='position: relative; left: 65px; bottom: 5px;'><img src='images/play_60.png' border=0></span><img src='http://video.shax-dag.ru/shots/"+$4+"' class='foto' width=200 border=0 title='Просмотреть видео'></a></div>";
         else
         if($2=="music")
            return "<a href=# onClick='ShowWindow(\"media/myWimpy.php?queryWhere=num&queryValue="+$3+"\",277,284);'><img src='images/play2.gif' border=0></a>  <a href='comments.php?base=music&t_key="+$3+"'>"+$4+"</a>";
         else
         if($2=="foto")
            return "<a href='comments.php?base=fotos&t_key="+$3+"'><img src='fotos/small/"+$4+"' class='foto' border=0></a>";
		else
         if($2=="users_fotos")
            return "<a href='comments2.php?t_key="+$3+"'><img src='users_fotos/small/"+$4+"' class='foto' border=0></a>";
         else
            return "";
}
function attachment($1,$2,$3){         
         if($2=="foto")
            return "<a href='attachments/fotos/"+$3+"' class='highslide' onclick='return hs.expand(this)' target=_blank><img src='attachments/fotos/small/"+$3+"' class='foto' border=0  hspace=10 vspace=5></a>";
         if($2=="graffiti")
            return "<a href='attachments/graffiti/"+$3+"' class='highslide' onclick='return hs.expand(this)' target=_blank><img src='attachments/graffiti/small/"+$3+"' class='foto' border=0  hspace=10 vspace=5></a>";
        
		 else
            return "";
}
function extsmiles($1,$2){
         return "<img src='images/users_smiles/"+$2+"' border='0'>";
}
function youtube_conv($1,$2,$3){
	var text="";
	text='<div align="center" style="padding:0px 10px;"><object width="450" height="325">';
	text+='<param name="movie" value="http://www.youtube.com/v/'+$3+'&amp;hl=ru_RU&amp;fs=1?rel=0&amp;color1=0xe1600f&amp;color2=0xfebd01&amp;version=3"></param>';
	text+='<param name="allowFullScreen" value="true"></param>';
	text+='<param name="allowscriptaccess" value="always"></param>';
	text+='<embed src="http://www.youtube.com/v/'+$3+'&amp;hl=ru_RU&amp;fs=1?rel=0&amp;color1=0xe1600f&amp;color2=0xfebd01&amp;version=3" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="450" height="325"></embed>';
	text+='</object></div>';
	return text;
}
function smotri_conv($1,$2,$3){
	var text="";
	text+='<div align="center" style="padding:0px 10px;"><object id="smotriComVideoPlayer" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="450" height="325">';
	text+='<param name="movie" value="http://pics.smotri.com/player.swf?file='+$3+'&bufferTime=3&autoStart=false&str_lang=rus&xmlsource=http%3A%2F%2Fpics.smotri.com%2Fcskins%2Fblue%2Fskin_color.xml&xmldatasource=http%3A%2F%2Fpics.smotri.com%2Fskin_ng.xml" />';
	text+='<param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="true" />';
	text+='<param name="bgcolor" value="#ffffff" />';
	text+='<embed src="http://pics.smotri.com/player.swf?file='+$3+'&bufferTime=3&autoStart=false&str_lang=rus&xmlsource=http%3A%2F%2Fpics.smotri.com%2Fcskins%2Fblue%2Fskin_color.xml&xmldatasource=http%3A%2F%2Fpics.smotri.com%2Fskin_ng.xml" quality="high" allowscriptaccess="always" allowfullscreen="true" wmode="opaque"  width="450" height="325" type="application/x-shockwave-flash"></embed>';
	text+='</object></div>';
	
	return text;
}
function rutube_conv($1,$2,$3){
	var text="";
	text+='<div align="center" style="padding:0px 10px;"><OBJECT width="450" height="325">';
	text+='<PARAM name="movie" value="http://video.rutube.ru/'+$3+'"></PARAM>';
	text+='<PARAM name="wmode" value="window"></PARAM>';
	text+='<PARAM name="allowFullScreen" value="true"></PARAM>';
	text+='<EMBED src="http://video.rutube.ru/'+$3+'" type="application/x-shockwave-flash" wmode="window" width="450" height="325" allowFullScreen="true" ></EMBED>';
	text+='</OBJECT></div>';
	
	return text;
}
function videomail_conv($1,$2,$3){
	var text="";
	text+='<div align="center" style="padding:0px 10px;"><object width="450" height="325">';
	text+='<param name="allowScriptAccess" value="always" />';
	text+='<param name="movie" value="http://img.mail.ru/r/video2/player_v2.swf?movieSrc='+$3+'" />';
	text+='<embed src=http://img.mail.ru/r/video2/player_v2.swf?movieSrc='+$3+' type="application/x-shockwave-flash" width="450" height="325" allowScriptAccess="always"></embed>';
	text+='</object></div>';
	
	return text;
}
function makesmile(text){
         var ret;
         var smile=/:D/g;
         text=text.replace(smile,"<img src='images/smiles/1.gif' border=0>");
         var smile=/\)\)\)/g;
         text=text.replace(smile,"<img src='images/smiles/1.gif' border=0>");
         smile=/:\)/g;
         text=text.replace(smile,"<img src='images/smiles/2.gif' border=0>");
         smile=/\)\)/g;
         text=text.replace(smile,"<img src='images/smiles/2.gif' border=0>");
         smile=/\-\)/g;
         text=text.replace(smile,"<img src='images/smiles/2.gif' border=0>");
         smile=/:\(/g;
         text=text.replace(smile,"<img src='images/smiles/3.gif' border=0>");
         smile=/:o/g;
         text=text.replace(smile,"<img src='images/smiles/27.gif' border=0>");
         smile=/:B/g;
         text=text.replace(smile,"<img src='images/smiles/14.gif' border=0>");
         smile=/:oops:/g;
         text=text.replace(smile,"<img src='images/smiles/44.gif' border=0>");
         smile=/:cry:/g;
         text=text.replace(smile,"<img src='images/smiles/12.gif' border=0>");
         smile=/:roll:/g;
         text=text.replace(smile,"<img src='images/smiles/15.gif' border=0>");
         smile=/:surp:/g;
         text=text.replace(smile,"<img src='images/smiles/7.gif' border=0>");
         smile=/;\)/g;
         text=text.replace(smile,"<img src='images/smiles/6.gif' border=0>");
         smile=/:P/g;
         text=text.replace(smile,"<img src='images/smiles/11.gif' border=0>");
         smile=/@}\-/g;
         text=text.replace(smile,"<img src='images/smiles/rose2.gif' border=0>");
         smile=/:ir:/g;
         text=text.replace(smile,"<img src='images/smiles/9.gif' border=0>");
         smile=/:appl:/g;
         text=text.replace(smile,"<img src='images/smiles/31.gif' border=0>");
         smile=/:adore:/g;
         text=text.replace(smile,"<img src='images/smiles/65.gif' border=0>");
         smile=/:\[/g;
         text=text.replace(smile,"<img src='images/smiles/ah.gif'>");
         
         smile=/:\-\*/g;
         text=text.replace(smile,"<img src='images/smiles/aj.gif' border=0>");
         smile=/:\-X/g;
         text=text.replace(smile,"<img src='images/smiles/al.gif' border=0>");
         smile=/:\-z/g;
         text=text.replace(smile,"<img src='images/smiles/ao.gif' border=0>");
         smile=/\*JOKINGLY\*/g;
         text=text.replace(smile,"<img src='images/smiles/ap.gif' border=0>");
         smile=/\[:\-/g;
         text=text.replace(smile,"<img src='images/smiles/ar.gif' border=0>");
         smile=/\]:\-/g;
         text=text.replace(smile,"<img src='images/smiles/aq.gif' border=0>");
         smile=/\|m\|/g;
         text=text.replace(smile,"<img src='images/smiles/bd.gif' border=0>");
         smile=/@=/g;
         text=text.replace(smile,"<img src='images/smiles/bb.gif' border=0>");
         return text;

}
function return_text2richtext(txt){
		text =  new String();
		text=txt;
         var url_match = /(?:[^"]|^)(https?:\/\/([A-Za-z0-9\-]+\.)+[a-z]{2,4}(:\d+)?((\/|\?)\S*)?)(?:\s|$)/g;
         var source_match = /\[a (video|music|foto|users_fotos)\=([0-9]+)]([^\[]+)\[\/a\]/g;
         var attachment_match_foto = /\[(foto)]([^\[]+)\[\/foto\]/g;
		 var attachment_match_graffiti = /\[(graffiti)]([^\[]+)\[\/graffiti\]/g;
         var extsmiles_match = /\*([0-9]+\.(gif|png|GIF|PNG))\*/g;
         text=makesmile(text);
         text=text.replace(url_match,conv);
         text=text.replace(source_match,source);
         text=text.replace(attachment_match_foto,attachment);
		 text=text.replace(attachment_match_graffiti,attachment);
         text=text.replace(extsmiles_match,extsmiles);
         //text=text.replace(/\n/g,"<br>");
         //text=text.replace(/\r/g,"<br>");
         return text;


}
function text2richtext(id){  
		 text=document.getElementById(id).innerHTML; 
         document.getElementById(id).innerHTML=return_text2richtext(text);
}
function put1(text) {
            document.forms['myform'].msg.value  += text;
	        document.forms['myform'].msg.focus();
}
function put_in_id(id,text) {
            document.getElementById(id).value  += text;
}
function help(s) {
  parameters="width=300,  height=300, toolbar=no, location=no, directories=no, menubar=no";
  s="../tools/help.php?p="+s;
  newWindow=window.open (s, null,  parameters);
  newWindow.focus();
}
function print_smiles(){
		 var smile="";
		 smile+="<div style='background-color:#FBEAC6; padding:5px;'><table width=100%><tr><td width=100>Вставить ресурс:</td><td align='right'>";
		 smile+="<span id='postform_foto' style='font-weight: normal; margin-left:5px;'><img src='photo.png'> <a href='javascript: choosePostVariant(\"foto\")' class='adotted'>Фотографию</a></span>";
		 smile+="<span id='postform_video' style='font-weight: normal; margin-left:5px;'><img src='video.png'> <a href='javascript: choosePostVariant(\"video\")' class='adotted'>Видео</a></span>";
		 smile+="<span id='postform_music' style='font-weight: normal; margin-left:5px;'><img src='music.png'> <a href='javascript: choosePostVariant(\"music\")' class='adotted'>Музыку</a></span>";
         smile+="<span id='postform_graffiti' style='font-weight: normal; margin-left:5px;'> <img src='images/graffiti_1.png'> <a href='javascript: ShowWindow(\"graffiti.php\",620,400);' class='adotted' > Нарисовать</a></span>";
         smile+="</td></tr></table>";
		 smile+="<div id='postform_menu' align='right' style='margin-top:5px;'></div>";
		 smile+="</div>";
		 
		 smile+="<a href='javascript: put1(\":)\");'><img src='images/smiles/2.gif' border=0></a> ";
         smile+="<a href='javascript: put1(\":D\");'><img src='images/smiles/1.gif' border=0></a> ";
         smile+="<a href='javascript: put1(\":(\");'><img src='images/smiles/3.gif' border=0></a> ";
         smile+="<a href='javascript: put1(\":o\");'><img src='images/smiles/27.gif' border=0></a> ";
         smile+="<a href='javascript: put1(\":B\");'><img src='images/smiles/14.gif' border=0></a> ";
         smile+="<a href='javascript: put1(\":[\");'><img src='images/smiles/ah.gif' border=0></a> ";
         smile+="<a href='javascript: put1(\":cry:\");'><img src='images/smiles/12.gif' border=0></a> ";
         smile+="<a href='javascript: put1(\":roll:\");'><img src='images/smiles/15.gif' border=0></a> ";
         smile+="<a href='javascript: put1(\":surp:\");'><img src='images/smiles/7.gif' border=0></a> ";
         smile+="<a href='javascript: put1(\";)\");'><img src='images/smiles/6.gif' border=0></a> ";
         smile+="<a href='javascript: put1(\":P\");'><img src='images/smiles/11.gif' border=0></a> ";
         smile+="<a href='javascript: put1(\"@}-\");'><img src='images/smiles/rose2.gif' border=0></a> ";
         smile+="<a href='javascript: put1(\":ir:\");'><img src='images/smiles/9.gif' border=0></a> ";
         smile+="<a href='javascript: put1(\":appl:\");'><img src='images/smiles/31.gif' border=0></a> ";
         smile+="<a href='javascript: put1(\":adore:\");'><img src='images/smiles/65.gif' border=0></a> ";
         smile+="<a href='javascript: put1(\":-*\");'><img src='images/smiles/aj.gif' border=0></a> ";
         smile+="<a href='javascript: put1(\":-X\");'><img src='images/smiles/al.gif' border=0></a> ";
         smile+="<a href='javascript: put1(\"*JOKINGLY*\");'><img src='images/smiles/ap.gif' border=0></a> ";
         smile+="<a href='javascript: put1(\"[:-\");'><img src='images/smiles/ar.gif' border=0></a> ";
         smile+="<a href='javascript: put1(\"]:-\");'><img src='images/smiles/aq.gif' border=0></a> ";
         smile+="<a href='javascript: put1(\"@=\");'><img src='images/smiles/bb.gif' border=0></a> ";
         smile+="<a href='javascript: put1(\"|m|\");'><img src='images/smiles/bd.gif' border=0></a> ";
         smile+=" ... <a href='ajax/smiles.php?opt=view'  onclick=\"return hs.htmlExpand(this,{ objectType: 'ajax', outlineType: 'rounded-white', preserveContent: false, align : 'center'} )\" class='adotted'>все смайлики</a> ";

         
         /*
         smile+="<div style='background-color:#FBEAC6; padding:5px;'>Вставить ресурс: ";
         smile+="<img src='images/exchanger.png'> <a href='exchanger.php?source_id=video'  onclick=\"return hs.htmlExpand(this,{ objectType: 'ajax', outlineType: 'rounded-white', preserveContent: false} )\" class='agreen' style='margin-right:8px;'> С Шах-Дага</a>   ";
         smile += "<img src='images/picture_link.png'> <a href='javascript: help(\"pastfoto\");' class='agreen' style='margin-right:8px;'>Из Интернета</a> ";
         smile += "<img src='images/picture_att.png'> <a href='attach.php?att_base=fotos'  onclick=\"return hs.htmlExpand(this,{ objectType: 'ajax', outlineType: 'rounded-white', preserveContent: false} )\" class='agreen' style='margin-right:8px;'>С компьютера</a> ";
		 smile += "<img src='images/graffiti_1.png'> <a href='javascript: ShowWindow(\"graffiti.php\",620,400);'  > Нарисовать</a>";
         smile +="</div>";
		 */
		 smile="<div style='padding:5px; border:1px #ffcc99 dotted;'>"+smile+"</div>";
         return smile;

}
function choosePostVariant(type){
	var menu=document.getElementById("postform_menu");
	if(type=='foto'){
		menu.innerHTML="<a href='ajax/my_sources.php?source_base=users_fotos&opt=show_my_sources&post=1'  onclick=\"return hs.htmlExpand(this,{ objectType: 'ajax', outlineType: 'rounded-white', preserveContent: false} )\" class='adotted' style='margin-left:5px; font-size:11px;'> Мои фотографии</a>";
		menu.innerHTML+="<a href='attach.php?att_base=fotos'  onclick=\"return hs.htmlExpand(this,{ objectType: 'ajax', outlineType: 'rounded-white', preserveContent: false} )\" class='adotted' style='margin-left:5px; font-size:11px;'> С компьютера</a>";
		menu.innerHTML+="<a href='javascript: help(\"pastfoto\");'   class='adotted' style='margin-left:5px; font-size:11px;'> Из интернета</a>";
		menu.innerHTML+="<a href='exchanger.php?source_id=video'  onclick=\"return hs.htmlExpand(this,{ objectType: 'ajax', outlineType: 'rounded-white', preserveContent: false} )\" class='adotted' style='margin-left:5px; font-size:11px;'> Из обменника</a>";
		
		document.getElementById("postform_foto").style.fontWeight="bold";
		document.getElementById("postform_video").style.fontWeight="normal";
		document.getElementById("postform_music").style.fontWeight="normal";
	}
	else
	if(type=='video'){
		menu.innerHTML="<a href='ajax/my_sources.php?source_base=clips&opt=show_my_sources&post=1'  onclick=\"return hs.htmlExpand(this,{ objectType: 'ajax', outlineType: 'rounded-white', preserveContent: false} )\" class='adotted' style='margin-left:5px; font-size:11px;'> Мои видеозаписи</a>";
		menu.innerHTML+="<a href='javascript: help(\"pastvideo\");'   class='adotted' style='margin-left:5px; font-size:11px;'> Из интернета</a>";
		menu.innerHTML+="<a href='exchanger.php?source_id=video'  onclick=\"return hs.htmlExpand(this,{ objectType: 'ajax', outlineType: 'rounded-white', preserveContent: false} )\" class='adotted' style='margin-left:5px; font-size:11px;'> Из обменника</a>";
		
		document.getElementById("postform_foto").style.fontWeight="normal";
		document.getElementById("postform_video").style.fontWeight="bold";
		document.getElementById("postform_music").style.fontWeight="normal";
	}
	else
	if(type=='music'){
		menu.innerHTML="<a href='ajax/my_sources.php?source_base=music&opt=show_my_sources&post=1'  onclick=\"return hs.htmlExpand(this,{ objectType: 'ajax', outlineType: 'rounded-white', preserveContent: false} )\" class='adotted' style='margin-left:5px; font-size:11px;'> Моя музыка</a>";
		menu.innerHTML+="<a href='exchanger.php?source_id=video'  onclick=\"return hs.htmlExpand(this,{ objectType: 'ajax', outlineType: 'rounded-white', preserveContent: false} )\" class='adotted' style='margin-left:5px; font-size:11px;'> Из обменника</a>";
		document.getElementById("postform_foto").style.fontWeight="normal";
		document.getElementById("postform_video").style.fontWeight="normal";
		document.getElementById("postform_music").style.fontWeight="bold";
	}
}
function showhide_div(id){
    if(document.getElementById(id).style.display=='none')
        document.getElementById(id).style.display='block';
    else
        document.getElementById(id).style.display='none';

}
function translit(id){
         var mapEn1 = "eh|ju|ja|shh|" +"ch|sh|kh|jo|" +"zh|a|b|v|g|" +"d|e|z|i|j|" +"k|l|m|" +"n|o|p|r|s|t|" +"u|f|c|\"|y|'";
         var mapEn=mapEn1.split("|");
         var mapRu1 = "э|ю|я|щ|" +"ч|ш|х|ё|" +"ж|а|б|в|г|" +"д|е|з|и|й|"+"к|л|м|" +"н|о|п|р|с|т|"+"у|ф|ц|ъ|ы|ь";
         var mapRu=mapRu1.split("|");
         function translateStr(str){
                  var str= str.toLowerCase();
                  for(i = 0; i < mapEn.length; ++i)
                      while (str.indexOf(mapEn[i]) >= 0)
                      str = str.replace(mapEn[i], mapRu[i]);
                      return str
                  }
         document.getElementById(id).value=translateStr(document.getElementById(id).value);
}
function setCookie (name, value, expires, path, domain, secure) {
         document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}
function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}
function copy_source(source_id,num,title){
    var cookie_name='';
    var max_vars=5;
    var i=0;
    var free_i=0;
    var cur_cookie_name='';
    
    if( (cookie_name=gen_cookie_prefix(source_id)) == -1)
        return "Ошибка. Такого ресурса не существует";
    //ищем свободную переменную   
	cur_cookie_name=cookie_name+"_num_"+i;	
    while( (i<max_vars)&&(getCookie(cur_cookie_name)!=null)&&(getCookie(cur_cookie_name)!=0) ){
		    i++;
		    cur_cookie_name=cookie_name+"_num_"+i;
    }
    free_i=i;
    //если все заполнено, то очищаем весь массив и свободный:=0
    if(free_i>=max_vars){
       for(i=0;i<max_vars;i++){
		   delete_source(source_id,i);		          
       }
       free_i=0;       
    }
    //Записываем значение в индекс free_i    
    //num:
    cur_cookie_name=cookie_name+"_num_"+free_i;
    setCookie(cur_cookie_name,num);
    //title:
    cur_cookie_name=cookie_name+"_title_"+free_i;
    setCookie(cur_cookie_name,title);
    
    document.getElementById("exchanger_button").innerHTML="Скопировано";
    
}

function make_teg(source_id,i){
    var result='';
    var cookie_name_num='';
    var cookie_name_title='';
    var cookie_name='';
    var num=0;
    var title="";
    
    if( (cookie_name=gen_cookie_prefix(source_id)) == -1)
        return "";
    
    cookie_name_num=cookie_name+"_num_"+i;
    cookie_name_title=cookie_name+"_title_"+i;
    //если кукис не пустой
    if((getCookie(cookie_name_num)!=null)&&(getCookie(cookie_name_title)!=null)&&(getCookie(cookie_name_num)!=0)&&(getCookie(cookie_name_title)!="") ){
       num=getCookie(cookie_name_num);
       title=getCookie(cookie_name_title);
       result="[a "+source_id+"="+num+"]"+title+"[/a]";
    }
    else
       result="";
    
    return result;   
}
function delete_source(source_id,i){
    var cookie_name="";
    
    if((cookie_name=gen_cookie_prefix(source_id))==-1)
        return "Ошибка. Такого ресурса не существует";
        
    //удаляем куки   	
    setCookie(cookie_name+"_num_"+i,0);		
	setCookie(cookie_name+"_title_"+i,"");   
}

function past_source(source_id,i){
    var teg="";
    var div_id="div_"+source_id+"_"+i;
    //если тег извлекся
	if((teg=make_teg(source_id,i))!=""){
        put1(teg);
        document.getElementById(div_id).innerHTML="<div class='warn' style='font-size:12px; padding:5px'><b>Добавлено.</b> После отправки обновите страницу, чтобы увидеть изменения</div>";
        delete_source(source_id,i)
	}
	else
	    alert("Ошибка. Очистите обменник и повторите попытку");
}
function past_source2(teg,span_class){
    put1(teg);
    document.getElementById(span_class).innerHTML="<b>Добавлено.</b>";
}
function build_exchanger(source_id){
    var html="";
    var total=0;
    var cookie_name="";
    var cur_cookie_name="";
    var i=0;
    var max_vars=5;
    var num=0;
    var title=0;
    
    if((cookie_name=gen_cookie_prefix(source_id))==-1){        
       document.write("Ошибка. Такого ресурса не существует");
       return -1;
    }
    
    	
    for(i=0;(i<max_vars); i++ ){
      cur_cookie_name=cookie_name+"_num_"+i;		  
	  if( (getCookie(cur_cookie_name)!=null)&&(getCookie(cur_cookie_name)!=0) ){  
	    total++;
	    //считываем значения
	    cur_cookie_name=cookie_name+"_num_"+i;
	    num=getCookie(cur_cookie_name);
	    cur_cookie_name=cookie_name+"_title_"+i;
	    title=getCookie(cur_cookie_name);
	    //строим вывод
	    if(source_id=="video"){
		   html+="<div id='div_"+source_id+"_"+i+"' style='margin-bottom:5px;'>";
		   html+="<table><tr valign='middle'><td style='margin-right:20px'>";
		   html+="<a href='comments.php?base=clips&t_key="+num+"'><img src='http://video.shax-dag.ru/shots/small/"+title+"' class='foto' border=0 title='Просмотреть видео'></a>";
		   html+="</td><td>";
		   html+="<a href='javascript: past_source(\""+source_id+"\","+i+");' class='agreen'> Добавить >></a>";
		   html+="</td></tr></table></div>";
	    }
		else
		if(source_id=="music"){
		   html+="<div id='div_"+source_id+"_"+i+"' style='margin-bottom:5px;'>";
		   html+="<table><tr valign='bottom'><td style='margin-right:20px'>";
		   html+="<a href='javascript: ShowWindow(\"media/myWimpy.php?queryWhere=num&queryValue="+num+"\",277,284);'><img src='images/play2.gif' border=0></a>  <a href='comments.php?base=music&t_key="+num+"'>"+title+"</a>";
		   html+="</td><td>";
		   html+="<a href='javascript: past_source(\""+source_id+"\","+i+");' class='agreen'> Добавить >></a>";
		   html+="</td></tr><table></div>";
		}
		else
		if(source_id=="foto"){
		   html+="<div id='div_"+source_id+"_"+i+"' style='margin-bottom:5px;'>";
		   html+="<table><tr valign='middle'><td style='margin-right:20px'>";
		   html+="<a href='comments.php?base=fotos&t_key="+num+"'><img src='fotos/small/"+title+"' class='foto' border=0></a>";
		   html+="</td><td>";
		   html+="<a href='javascript: past_source(\""+source_id+"\","+i+");' class='agreen'> Добавить >></a>";		   
		   html+="</td></tr></table></div>";
		}
	  }	
    }
    if(total>0){
       html="<div style='color:gray;'>Ресурсов в обменнике: <b>"+total+"</b>.</div>"+html;
    }
    else{
       html="<div style='color:gray;'><p><b>В обменнике пусто.</b></p> <i>Скопируйте нужный Вам ресурс в обменник, используя функцию \"Скопировать в обменник\" в разделе комментариев к этому ресурсу</i></div>";
    }
    document.getElementById("exchanger_div").innerHTML=html;
}
function gen_cookie_prefix(source_id){
    var cookie_name="";
     
    if(source_id=="video")
       cookie_name="video_source";
    else
    if(source_id=="music")
       cookie_name="music_source";
    else
    if(source_id=="foto")
       cookie_name="foto_source";
    else
       cookie_name=-1;
       
    return cookie_name;  
}

   function past_attachment(id,teg,obj){
       document.getElementById(id).value  += teg;
       hs.close(obj);
       text2richtext('msg');
   }
   
   function startUpload_att(){
           document.getElementById('f1_upload_process').style.visibility = 'visible';
           document.getElementById('f1_upload_form').style.visibility = 'hidden';
           document.getElementById('result').style.visibility = 'hidden';
           return true;

   }

   function stopUpload_att(success,file_name){
      var result = '';
      if (success == 1){
         result = "<table><tr><td>";
         result += "<a href='#22' onClick='past_attachment(\"msg\",\"[foto]"+file_name+"[/foto]\",this);'><img src='attachments/fotos/small/"+file_name+"' border=0 title='Вставить в текст'></a>";
         result += "</td><td class='warn'>";
         result += "<div >Загрузка завершена. Нажмите на изображение для вставки в текст<\/div>";
         result += "</td></tr></table>";
      }
      else if(success == 2){
           result = '<span style="color:red;">Ошибка авторизации<\/span>';
      }
      else if(success == 3){
           result = '<span style="color:red;">Вы не заполнили поля, помеченные звездочкой *<\/span><br>';
      }
      else if(success == 4){
           result = '<span style="color:red;">Ошибка на сервере базы данных<\/span><br>';
      }
      else {
         result = '<span style="color:red;">Сервер временно недоступен<\/span><br/>';
      }
      document.getElementById('f1_upload_process').style.visibility = 'hidden';
      document.getElementById('result').style.visibility = 'visible';
      document.getElementById('result').innerHTML = result;
      if(success!=1)
                    document.getElementById('f1_upload_form').style.visibility = 'visible';
      return true;
   }

function make_bold_by_id(id, element_type){
    if(element_type=="chkbox"){
       if(document.getElementById(id).style.fontWeight!='bold')
          document.getElementById(id).style.fontWeight='bold';
       else
          document.getElementById(id).style.fontWeight='normal';
    }
}

function ch_value(var_id, new_val){
    document.getElementById(var_id).value=new_val;
}
function send_complaint(){
    var poststr="?base="+encodeURIComponent( document.getElementById("base").value )+
                "&t_key="+encodeURIComponent( document.getElementById("t_key").value )+
                "&complaint_type="+encodeURIComponent( document.getElementById("complaint_type").value )+
                "&confirm=1";

    var send_url="ajax/complaints.php"+poststr;
    loadHTML2(send_url,'div_complaints1');

}
function send_ajax_form(obj_ids,script_url,div_id){
    var objArray=obj_ids.split(",");
    var poststr="";
    var send_url=script_url;
    for(i=0;i<objArray.length;i++){    //>
        if(i==0)
           poststr+="?";
        else
           poststr+="&";
        poststr+=objArray[i]+"="+encodeURIComponent( document.getElementById(objArray[i]).value );
    }
    send_url+=poststr;
    loadHTML2(send_url,div_id);
}
function add_to_blacklist(id){
    var loc="profile.php?opt=edit_settings&act=ban&num="+id;
    
    if(confirm('Вы уверены, что хотите добавить этого пользователя в свой черный список? После добавления он не сможет комментировать ни один Ваш ресурс.')){
       window.location=loc;
    }
}
function confirm_click(url, dest, quest){
		if(dest!=""){
			if(confirm(quest))
				loadHTML2(url,dest);
		}
		else{
			if(confirm(quest))
				window.location=url;
		}
}
function getFile(url) {
  if (window.XMLHttpRequest) {              
    AJAX=new XMLHttpRequest();              
  } else {                                  
    AJAX=new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (AJAX) {
     AJAX.open("GET", url, false);                             
     AJAX.send(null);
     return AJAX.responseText;                                         
  } else {
     return false;
  }                                             
}
function getUnixTime(){
	return(Math.round(new Date().getTime() / 1000));
}
function ntfy_JSON_decode(json_string){
	var json_obj=JSON.parse(json_string);
	return(json_obj);
	
}
function ntfy_SetTime(json_string, timestamp){
	var json_obj=ntfy_JSON_decode(json_string);
	var new_json_string="";
	json_obj.time=timestamp;
	new_json_string=JSON.stringify(json_obj);
	return(new_json_string);	
}
function handleNewComments(r_obj,valid_user_name){
	var newtitle="";
	if(r_obj.fotos>0){
		document.getElementById('u_fotos').innerHTML="<b>("+r_obj.fotos+")</b>";
		newtitle="===============================";
	}
	else
		document.getElementById('u_fotos').innerHTML="";
	if(r_obj.board>0){
		document.getElementById('u_board').innerHTML="<b>("+r_obj.board+")</b>";
		document.getElementById('my_page_link').href='user_info.php#board';
		newtitle="===============================";
	}
	else{
		document.getElementById('u_board').innerHTML="";
		document.getElementById('my_page_link').href='user_info.php';
		}
	if(r_obj.marks>0){
		document.getElementById('u_marks').innerHTML="<b>("+r_obj.marks+")</b>";
	}
	else
		document.getElementById('u_marks').innerHTML="";
	if(r_obj.messages>0){
		document.getElementById('u_msg').innerHTML="<b>("+r_obj.messages+")</b>";
		newtitle="===============================";
	}
	else
		document.getElementById('u_msg').innerHTML="";
	if(r_obj.friends>0){
		document.getElementById('u_friends').innerHTML="<b>("+r_obj.friends+")</b>";
		document.getElementById('my_fr_link').href='friends.php';
	}
	else{
		document.getElementById('u_friends').innerHTML="";
		document.getElementById('my_fr_link').href='friends.php?opt=show&info_name='+valid_user_name;
	}
	if(r_obj.gifts>0){
		document.getElementById('u_gifts').innerHTML='<table class=\"gift\" align=\"center\"><tr><td><img src=\"../images/gift.png\"></td><td><a href=\"../gifts.php?opt=view\" class=\"agreen\">Новый подарок</a> <b class=\"new_coms_blinked\">('+r_obj.gifts+')</b></td></tr></table>';
	}
	else
		document.getElementById('u_gifts').innerHTML='';
	if(r_obj.groups>0){
		document.getElementById('u_groups').innerHTML="<b>("+r_obj.groups+")</b>";
		document.getElementById('my_gr_link').href='my_groups.php?opt=invites&info_name='+valid_user_name;
	}
	else{
		document.getElementById('u_groups').innerHTML="";
		document.getElementById('my_gr_link').href='my_groups.php?opt=show&info_name='+valid_user_name;
	}
		
	
	//мигание заголовка
	if((newtitle!="")&&(title_blinks==0))
		 blink_title(newtitle);
	else
	//остановка мигания
	if((newtitle=="")&&(title_blinks!=0))
		stop_title_blink("Шах-Даг портал");
}
function countNewComments(r_obj){
	var countComments=0;
	if(r_obj.fotos>0){
		countComments=countComments+r_obj.fotos;
	}
	if(r_obj.board>0){
		countComments=countComments+r_obj.board;
	}
	if(r_obj.marks>0){
		countComments=countComments+r_obj.marks;
	}
	if(r_obj.messages>0){
		countComments=countComments+r_obj.messages;
	}
	if(r_obj.friends>0){
		countComments=countComments+r_obj.friends;
	}
	if(r_obj.gifts>0){
		countComments=countComments+r_obj.gifts;
	}
	if(r_obj.groups>0){
		countComments=countComments+r_obj.groups;
	}
	return countComments;
}
function blink_title(new_title){
	var newTxt=new_title;
	var oldTxt=document.title;
	function blnk1(){
	 if(document.title==oldTxt){
		document.title=newTxt;
	 }else{
		document.title=oldTxt;
	 }
	}
	blink_timerId = setInterval(blnk1,1000);
	title_blinks=1;
}
function stop_title_blink(static_title){
	clearInterval(blink_timerId);
	document.title=static_title;	
}
function reply_comment(name,user_id){
	if(opened_id>0)
		showform("post",""); //закрываем, чтоб открыть с нуля
	showform("post",""); 
	put1(name+", ");
	ch_value('comment_reply_to', user_id);
}

function blockPop(DivId) {
	$("#"+DivId).fadeOut("normal", function(){
		var elem=document.getElementById(DivId);
		document.body.removeChild(elem);
	}
	);
	$(window).unbind("scroll");
}

function showPop(DivId, html, title) {
		function getClientHeight(){
			var x,y;	
			// общий синтаксис	
			if (self.innerHeight) {	
				x = self.innerWidth;	
				y = self.innerHeight;	
			// IE 6 Strict Mode	
			} else if (document.documentElement && document.documentElement.clientHeight) {	
				x = document.documentElement.clientWidth;	
				y = document.documentElement.clientHeight;	
			// Остальные версии IE	
			} else if (document.body) {	
				x = document.body.clientWidth;	
				y = document.body.clientHeight;	
			}	
			return y;
		}
		var topOffset = getClientHeight()-110;
		var divElement;
		var divattributes;
		var myDocument = document;
		var htmlElement = myDocument.documentElement;
		var headElement = htmlElement.getElementsByTagName("head")[0];
		if (headElement != null) {
		  var bodyElement = headElement.nextSibling;
		  while (bodyElement.nodeName.toLowerCase() != "body") {
			bodyElement = bodyElement.nextSibling;
		  }
		}
		if(document.getElementById(DivId)==null){
			//добавляем слой-контейнер
			divElement = document.createElement("div");
			divattributes = "position: absolute; width: 250px; height: 100px; top:"+topOffset+"px; right:10px; display:none; border: 1px solid #ffc73e; background-color:#fbfbd6";
			divElement.setAttribute("style", divattributes);
			divElement.style.position='absolute';
			divElement.style.width=250;
			divElement.style.height=100;
			divElement.style.top=topOffset;
			divElement.style.right=10;
			divElement.style.border="1px solid #ffc73e";
			divElement.style.backgroundColor="#fbfbd6";
			divElement.setAttribute("id", DivId);
			bodyElement.appendChild(divElement);
			
			document.getElementById(DivId).innerHTML="<div style='height:30px; background-color:#ffe385;'><table width=100%><tr><td><b>"+title+"</b></td><td align='right'><a href='javascript:blockPop(\""+DivId+"\");'><img src='images/design/delete_sm.png' border=0></a></td></tr></table></div>";
			document.getElementById(DivId).innerHTML+=html;
			var win_scrl = $(document).scrollTop();
			var top = parseInt(topOffset + win_scrl);
			$("#"+DivId).css('top', top + 'px').fadeIn("slow", function() {
				
				$(window).scroll(function() {
					win_scrl = $(document).scrollTop();
					top = parseInt(topOffset + win_scrl);
					$("#"+DivId).css('top', top + 'px');
				});
				setTimeout(function() {
					blockPop(DivId);
				}, 10000);
			});
		}
		
}
function imgGender(gender){
	if(gender=="Ж")
		return "<img src='user_female.png' border=0>";
	else
		return "<img src='user_male.png' border=0>";
}
function showhideAjax(url, dest){
	var dest_obj=document.getElementById(dest);
	if(dest_obj.innerHTML=="")
		loadHTML2(url,dest);
	else
		dest_obj.innerHTML="";
}
function sendVote(quest_id){
	var script_url="ajax/voter.php?quest_id="+quest_id+"&answ_id="+document.getElementById("quest_"+quest_id+"_answ").value+"&opt=vote";
	var div_id="vot_"+quest_id;	
	if(document.getElementById("quest_"+quest_id+"_answ").value>0)
		loadHTML2(script_url,div_id);
}
function newAnswVariant(){
   if(document.getElementById("add_answ")!=null){
		var last=document.getElementById("answ_total").value;
		var new_id=last*1+1;
		document.getElementById("add_answ").innerHTML+="<div id='div_answ_"+new_id+"'><table width=418><tr><td width=150>Вариант ответа: </td><td><input type='text' id='answ_"+new_id+"' style='width:100%'> </td><td width=18><a href='javascript:delAnswVariant("+new_id+");'><img src='delete.png' border=0></a></td></tr></table>";
		document.getElementById("answ_total").value=new_id;
   }
}
function delAnswVariant(new_id){
   var div_id="div_answ_"+new_id;
   var input_id="answ_"+new_id;
   if(document.getElementById(div_id)!=null){
		document.getElementById(input_id).value="";
		document.getElementById(div_id).style.display="none";
   }
}
function CreateVoter(t_key, base){
	var error=0;
	var not_empty = 0;
	if(document.getElementById("answ_total")!=null){
		var last=document.getElementById("answ_total").value;
		last=last*1;
		var url="ajax/voter.php?opt=add&t_key="+t_key+"&base="+base+"&vot_quest="+encodeURIComponent(document.getElementById("vot_quest").value)+"&answ_total="+last;
		var answ="";
		for(i=1; i<=last; i++){
			answ_id="answ_"+i;
			if(document.getElementById(answ_id)!=null){
				answ=document.getElementById(answ_id).value
				if(answ!="")
					not_empty++;
			}
			else
				answ="";
			url+="&answ_"+i+"="+encodeURIComponent(answ);
		}
		if((document.getElementById("vot_quest")==null)||(not_empty<2)){
			document.getElementById("quest_error").innerHTML="<div style='color: red;'> Вы должны указать вопрос и, как минимум, два варианта ответа</div>";
		}
		else
			loadHTML2(url,"quest_form");
	}
}

