//==============================
// Автор: REZER
// http://delicated.ru/ 
// Специально для модуля блогов
//==============================

var window_none = true;
var about_cache = "";
var allnews_ShowOrHide = new Array();

// Принятие каких либо действий

function blog_confirm(url, text){

    var del_agree  = text;
    var agree=confirm( del_agree );

    if (agree)
    document.location=url;
};

// Меню для редактирования личного меню пользователя

function menu_block_edit_user(){

var menu=new Array()
var lang_action = "";

menu[0]='<a href="' + domen_sait + '/blog/menu/">Меню</a>';
menu[1]='<a href="' + domen_sait + '/blog/menu/edit/">Редактировать</a>';
menu[2]='<a href="' + domen_sait + '/blog/menu/sort/">Отсортировать блоги</a>';
menu[3]='<a href="' + domen_sait + '/blog/menu/selection/">Управление подборкой</a>';

return menu;
}

// Меню для редактирования новости в админке

function menu_news_edit_admin( id, blog_alt, link_del_sait, link_del_blog, link_restore ){

var menu=new Array()
var lang_action = "";

menu[0]='<a onclick="window.open(\'$PHP_SELF?mod=blog&action=news_blog&id=' + id + '\', \'response\', \'width=570, height=270, top=200, left=200, scrollbars=1\');" href="javascript://">Сменить блог для новости</a>';

if(link_restore != "")
	{
	  menu[1]='<a onClick="blog_confirm(\'' + link_restore + '\', \'Восстановить статью на сайте?\'); return(false)" href="' + link_restore + '">Восстановить на сайте</a>';	
	}

if(blog_alt != "")
	{
	  menu[2]='<a onClick="blog_confirm(\'' + link_del_blog + '\', \'Вы действительно хотите удалить данную статью из блога?\'); return(false)" href="' + link_del_blog + '">Удалить из блога</a>';		  	
	}
	
if(link_del_sait != "")
	{
      if(blog_alt != "")
	    {
	      menu[3]='<a onClick="blog_confirm(\'' + link_del_sait + '\', \'Данная статья будет удалена с сайта, но будет показываться в блоге, продолжить?\'); return(false)" href="' + link_del_sait + '">Удалить с сайта</a>';	
		}
	}

return menu;
}

// Меню для новости

function menu_news_edit( blog_name, news_id, action , del ){

var menu=new Array()
var lang_action = "";

menu[0]='<a onclick="ajax_prep_for_edit( \''+ news_id + '\', \'' + action + '\' ); return false;" href="javascript://">Быстрое редактирование</a>';
menu[1]='<a href="' + blog_name + '">Полное редактирование</a>';
menu[2]='<a onClick="javascript:if(!confirm(\'Удалить эту статью? Данная действие невозможно будет отменить.\'))return false"; href="' + del + '">Удалить статью</a>';

return menu;
}

// Меню для пользователя

function menu_user( profile, user_news, user_name ){

var menu=new Array()
var lang_action = "";

menu[0]='<a href="' + profile + '">Профиль пользователя</a>';
menu[1]='<a href="' + user_news + '">Найти все публикации</a>';
menu[2]='<a href="/index.php?do=pm&doaction=newpm&username=' + user_name + '">Отправить сообщение</a>';

return menu;
}

// Меню для админка блога

function menu_admin( admin_link, options_link, rss_link, user_link, moder_news, about_link, addnews_link ){

var menu=new Array()
var lang_action = "";

menu[0]='<a href="' + admin_link + '">Админцентр</a>';
menu[1]='<a href="' + user_link + '">Пользователи</a>';
menu[2]='<a href="' + rss_link + '">Настройки RSS</a>';
menu[3]='<a href="' + options_link + '">Основные настройки</a>';
menu[4]='<a href="' + moder_news + '">Модерация новостей</a>';
menu[5]='<a href="' + addnews_link + '">Добавить статью в блог</a>';
menu[6]='<a href="' + about_link + '">Изменить описание блога</a>';

return menu;
}

// Меню для модератора блога

function menu_moder( moder_news, addnews_link ){

var menu=new Array()
var lang_action = "";

menu[0]='<a href="' + moder_news + '">Модерация новостей</a>';
menu[1]='<a href="' + addnews_link + '">Добавить статью в блог</a>';

return menu;
}

// Меню для редактирования полного описания блога

function menu_about( blog_name, edit_link ){

var menu=new Array()
var lang_action = "";

menu[0]='<a onclick="dofullabout( \'' + blog_name + '\' ); return false;" href="javascript://">Быстрое редактирование</a>';
menu[1]='<a href="' + edit_link + '">Полное редактирование</a>';

return menu;
}

// Меню для пользователя, которому разрешено добавлять новости в блог

function menu_addnews( addnews_link ){

var menu=new Array()
var lang_action = "";

menu[0]='<a href="' + addnews_link + '">Добавить статью в блог</a>';

return menu;
}

// Календарь при просмотре подборки

function doBlogcalendar(blogmonth, blogyear){
       var ajax = new dle_ajax();
	    document.getElementById("calendar-layer").innerHTML = '<center><img src="/templates/' + dle_skin + '/blogimages/ajax/ajax.gif" border="0"><br><br><b>Пожалуйста подождите...</b></center>';
       var varsString = "";
       ajax.setVar("year", blogyear);
       ajax.setVar("month", blogmonth);
       ajax.requestFile = dle_root + "engine/ajax/blog/calendar.php";
       ajax.method = 'GET';
       ajax.element = 'calendar-layer';
       ajax.sendAJAX(varsString);
};

// Добавление/удаление блога из подборки

function doSelection( blog_name, action_type )
{
       var ajax = new dle_ajax();
       document.getElementById("blog-name-" + blog_name).innerHTML = '<img src="/templates/' + dle_skin + '/blogimages/ajax/mini-ajax.gif" border="0" align="absmiddle">';
       var varsString = "blog_name=" + blog_name;
       ajax.setVar("action", action_type);
       ajax.setVar("skin", dle_skin);
       ajax.requestFile = dle_root + "engine/ajax/blog/selection.php";
       ajax.method = 'GET';
       ajax.element = 'blog-name-'+blog_name;
       ajax.sendAJAX(varsString);

       return false;
}

// Подключение/отключение от блога

function doStatus( blog_alt_name, status_type ){
  
  if(status_type == "remove"){
	  
	formCheck = confirm("Вы уверены, что хотите отключиться от данного блога..?");
    if(formCheck == true)
      {
        doStatus_ok( blog_alt_name, status_type );
      }
       else
      {
        return false;
      }
	
  }
   else
  {
	doStatus_ok( blog_alt_name, status_type );
  }
 return false;       
}

function doStatus_ok( blog_name, action_type )
{
       var ajax = new dle_ajax();
	   document.getElementById(blog_name).innerHTML = '<img src="/templates/' + dle_skin + '/blogimages/ajax/status.gif" border="0">';
       var varsString = "blog_name=" + blog_name;
       ajax.setVar("action", action_type);
       ajax.setVar("skin", dle_skin);
       ajax.requestFile = dle_root + "engine/ajax/blog/status.php";
       ajax.method = 'GET';
       ajax.element = blog_name;
	   ajax.onCompletion = status_reload;
       ajax.sendAJAX(varsString);

       return false;
}

function status_reload(){
	
    blog_ajax_navigation('name=' + blog_alt);
	  
}

// Проверка свободности домена при создании блога

function empty_blog()
{
       var ajax = new dle_ajax();
	   var form = document.getElementById('entryform');
	   
	  if ( form.alt_name.value == '') {		
	    alert("Заполните поле альтернативного имени блога!");
	    return false;	  
	  }
	   
       document.getElementById("empty_blog").innerHTML = '<img src="/templates/' + dle_skin + '/blogimages/ajax/status.gif" border="0">';
       var varsString = "empty_blog";
	   ajax.setVar("blog_name", form.alt_name.value);
       ajax.requestFile = dle_root + "engine/ajax/blog/empty_blog.php";
       ajax.method = 'GET';
	   ajax.element = 'empty_blog';
       ajax.sendAJAX(varsString);

       return false;
};

// Обновление капчи

function reload_ajax()
{
       var ajax = new dle_ajax();
	   document.getElementById("dle-captcha").innerHTML = '<center><img src="/templates/' + dle_skin + '/blogimages/ajax/ajax.gif" border="0"><br></center>';
       var varsString = "dle-captcha";
       ajax.element = 'dle-captcha';
       ajax.sendAJAX(varsString);
	   
	  
       return false;
};

// Добавление новости в закладки

function doFavorites_blog( fav_id, event )
{
	var ajax = new dle_ajax();
	document.getElementById('fav-id-'+fav_id).innerHTML = '<img src="/templates/' + dle_skin + '/blogimages/ajax/mini-ajax.gif" border="0" align="absmiddle">';
	var varsString = "fav_id=" + fav_id;
	ajax.setVar("action", event);
	ajax.setVar("skin", dle_skin);
	ajax.requestFile = dle_root + "engine/ajax/favorites.php";
	ajax.method = 'GET';
	ajax.element = 'fav-id-'+fav_id;
	ajax.sendAJAX(varsString);

	return false;
};

// Редактирование полного описания блога

function dofullabout( blog_name ){
	
	   if(!about_cache)
	   		{
				about_cache = document.getElementById('about').innerHTML;
			}	   	
	
       var ajax = new dle_ajax();
      
	   document.getElementById("about").innerHTML = '<center><img src="/templates/' + dle_skin + '/blogimages/ajax/about.gif" border="0" align="absmiddle"><br><br><b>Загрузка, пожалуйста подождите...</b></center>';
	  
       var varsString = "about";
	   ajax.setVar("blog_name", blog_name);
	   ajax.setVar("action", "edit");
       ajax.requestFile = dle_root + "engine/ajax/blog/about.php";
       ajax.method = 'GET';
	   ajax.execute = true;
       ajax.element = 'about';
       ajax.sendAJAX(varsString);

       return false;
};



function cancel_about()
{
		document.getElementById( 'about' ).innerHTML = about_cache;
		return false;
};

function about_full_save( blog_name, title, story, story_small )
{

   var ajax = new dle_ajax();
	   
     story = ajax.encodeVAR( story );	
	 title = ajax.encodeVAR( title );	
	 story_small = ajax.encodeVAR( story_small );	
	   
	   document.getElementById("about").innerHTML = '<center><img src="/templates/' + dle_skin + '/blogimages/ajax/about.gif" border="0" align="absmiddle"><br><br><b>Сохранение, пожалуйста подождите...</b></center>';
	   
       var varsString = "about";
	   ajax.setVar("story", story);
	   ajax.setVar("title", title);
	   ajax.setVar("story_small", story_small);
	   ajax.setVar("blog_name", blog_name);
	   ajax.setVar("action", "save");
       ajax.requestFile = dle_root + "engine/ajax/blog/about.php";
       ajax.method = 'GET';
       ajax.element = 'about';
       ajax.sendAJAX(varsString);
	   about_cache = "";

       return false;
};

// Предварительный просмотр новости перед добавлением

function dopreview( title,short_story,full_story, type )
{
   var ajax = new dle_ajax();
       document.getElementById("blogpreview").innerHTML = '<center><img src="/templates/' + dle_skin + '/blogimages/ajax/ajax.gif" border="0"><br /><b>Пожалуйста подождите...</b></center>';
	   
if (blog_wysiwyg == "yes") {

		short_story = ajax.encodeVAR( tinyMCE.get('short_story').getContent() );
		full_story = ajax.encodeVAR( tinyMCE.get('full_story').getContent() );

	} else {

		short_story = ajax.encodeVAR( document.getElementById('short_story').value );
		full_story = ajax.encodeVAR( document.getElementById('full_story').value );

	}		   
	   ajax.setVar("title", title);
	   ajax.setVar("short_story", short_story);
	   ajax.setVar("full_story", full_story);
	   ajax.setVar("type", type);
       ajax.setVar("skin", dle_skin);
       ajax.requestFile = dle_root + "engine/ajax/blog/news_preview.php";
       ajax.method = 'POST';
       ajax.element = "blogpreview";
       ajax.sendAJAX("blogpreview");

       return false;
};

// Добавление отзыва репутации

function doreputation(reason)
{
   var form = document.getElementById('edit_reputation');
   var ajax = new dle_ajax();	
	
	if ( form.reason.value == '') {
		
	  alert("Заполните поле отзыва");
	  return false;
	  
	  }
	  
	if ( form.blog_id.value == '') {
		
	  alert("Нет всех обязательных данных, повторите попытку позднее.");
	  return false;
	  
	  }
	  
	if ( form.blog_name.value == '') {
		
	  alert("Нет всех обязательных данных, повторите попытку позднее.");
	  return false;
	  
	  }  

	if ( form.sum_add_com ) {

	   ajax.setVar("sum_add_com", form.sum_add_com.value);

      }
	
	ajax.onShow ('');	
	var varsString = "blog_repa_add";
	ajax.setVar("reason", ajax.encodeVAR(form.reason.value));
	ajax.setVar("blog_id", form.blog_id.value);
	ajax.setVar("blog_name", form.blog_name.value);
	ajax.setVar("type", form.type.value);
	ajax.setVar("skin", dle_skin);
	ajax.requestFile = dle_root + "engine/ajax/blog/add_repa.php";
	ajax.method = 'POST';
	ajax.execute = true;
	ajax.element = 'blog_repa_add';
	ajax.sendAJAX('blog_repa_add');


};



// Проверка на свободность для окна справки

function empty_window()
{
   var ajax = new dle_ajax();
	 if (document.getElementById("title").value == '') {		
	    alert("Заполните поле названия окошка!");
	    return false;	  
	  }
	  
	 var alt_name = ajax.encodeVAR( document.getElementById("title").value );	   
     document.getElementById("empty_name").innerHTML = '<img src="/templates/' + dle_skin + '/blogimages/ajax/status.gif" border="0">';
      var varsString = "empty_name";
	   ajax.setVar("alt_name", alt_name);
       ajax.requestFile = dle_root + "engine/ajax/blog/empty_window.php";
       ajax.method = 'GET';
	   ajax.element = 'empty_name';
       ajax.sendAJAX(varsString);

       return false;
};

// Вывод окна справки

function blog_window(width,height,alt_name,title, resize){

  var ajax = new dle_ajax();
  
    if(!window_none)
	  {
        document.getElementById("blog_repa_text").innerHTML = '<center><img src="/templates/' + dle_skin + '/blogimages/ajax/ajax.gif" border="0"></center>';
      }
	   else
	  { 
	    showBusyLayer();
	    ajax.onShow ('');
	  }	 
	
	ajax.setVar("skin", dle_skin);
	ajax.setVar("alt_name", alt_name);
	ajax.requestFile = dle_root + "engine/ajax/blog/window.php";
	ajax.method = 'POST';
    ajax.element = 'blog_repa_text';
    ajax.onCompletion = winshow;
	
    if(resize == 'yes')
	  {
	    document.getElementById('blog_resize').style.display='block';
		document.getElementById('blog_no_resize').style.display='none';
	} else {
		document.getElementById('blog_resize').style.display='none';
		document.getElementById('blog_no_resize').style.display='block';
	  }
	
	document.getElementById('blog_repa').style['width']=width+"px";
    document.getElementById('blog_repa').style['height']=height+"px";
	document.getElementById('blog_repa_title').innerHTML = title;
	ajax.setVar("window_height",document.getElementById('blog_repa').style['height']) ;
    ajax.sendAJAX('');
	window_none = false;

  return false;
};

// Предварительный просмотр окна справки перед созданием

function blog_window_preview(){

  var ajax = new dle_ajax();
	ajax.onShow ('');	
	 
	 var content = ajax.encodeVAR( document.getElementById('content').value );

	ajax.setVar("skin", dle_skin);
	ajax.setVar("background",  document.getElementById('background').value);	
	ajax.setVar("window_height", document.getElementById('height').value);
	ajax.setVar("content", content);
	ajax.setVar("templates", document.getElementById('templates').value);

	if(document.getElementById('border').checked == true)
	  {
		 ajax.setVar("border", 1);
	  }
	
	ajax.requestFile = dle_root + "engine/ajax/blog/window_preview.php";
	ajax.method = 'POST';
    ajax.element = 'blog_repa_text';
    ajax.onCompletion = winshow;
	
	if(document.getElementById('resize').checked == true)
	  {
	    document.getElementById('blog_resize').style.display='block';
		document.getElementById('blog_no_resize').style.display='none';
	} else {
		document.getElementById('blog_resize').style.display='none';
		document.getElementById('blog_no_resize').style.display='block';
	  }
    
	document.getElementById('blog_repa').style['width']= document.getElementById('width').value+"px";
    document.getElementById('blog_repa').style['height']= document.getElementById('height').value+"px";
	document.getElementById('blog_repa_title').innerHTML = document.getElementById('title').value;
	
	
	ajax.setVar("window_height",document.getElementById('height').value) ;
    ajax.sendAJAX('');

  return false;
};

// Закрытие окна справки
function blog_repa_close(){
 document.getElementById('blog_repa').style.display="none";
 document.getElementById( 'blog_repa_text' ).innerHTML="";
 window_none = true;
};

// Открытие окна справки
function winshow(){
  blog_repa_compile('blog_repa','blog_repa_header','blog_resize');
  hideBusyLayer();
  return false;
};

// Отчистка кэша, просмотр html кода для окна справки

function other_window(width,height,alt_name,title, resize, id, type)
{
   var ajax = new dle_ajax();
	  
	 var title = ajax.encodeVAR( title );	
	 
	 if(type == "code")
	   {
         document.getElementById("title_link-" + id).innerHTML = '<img src="/templates/' + dle_skin + '/blogimages/ajax/status.gif" border="0">';
         var varsString = "title_link-" + id;
	   }else{
		  document.getElementById("cashe-" + id).innerHTML = '&nbsp;<img src="/templates/' + dle_skin + '/blogimages/ajax/mini-ajax.gif" border="0">';
         var varsString = "cashe-" + id;
	   }
	  
	  ajax.setVar("width", width);
	  ajax.setVar("height", height);
	  ajax.setVar("alt_name", alt_name);
	  ajax.setVar("title", title);
	  ajax.setVar("resize", resize);
	  ajax.setVar("id", id);
	  ajax.setVar("type", type);
	  
       ajax.requestFile = dle_root + "engine/ajax/blog/other_window.php";
       ajax.method = 'POST';
	   ajax.element = varsString;
       ajax.sendAJAX(varsString);

       return false;
};

// Функция для навигации (редактируем как угодно, даже можете удалить)

function navigation_blog(page, url, count_page, user_page, prefix, cpu)
{
	if (!page)
	  {
	   	alert("Введите номер страницы!");
		return false;
	  }
	  
	if (page == user_page)
	  {
	   	alert("Вы и так уже находитесь на этой странице!");
		return false;
	  }
	  
	if (page > count_page)
	  {
	   	alert("Данной страницы не существует: максимум = " + count_page + "!");
		return false;
	  }
	  
	if (page < 1)
	  {
	   	alert("Вы ввели некорректный номер страницы, пожалуйста повторите попытку ещё раз!");
		return false;
	  }
	
	if (!page.match(/[1-9]+/g))
	  {
	   	alert("Разрешены только цифры (0-9). Буквы, пробелы, запятые, дефисы, кавычки и т.д. запрещены.");
		return false;
	  }
	  		
	if(page == 1)
	  {
		 window.location.href = url;
	  }
		 else
	  {  
		 window.location.href = url + prefix + page + cpu;
	  }

};

// Формирование окна справки и сам движок этого окна (автор не известен)

var Drag2 = {

	obj : null,

	init : function(o, oRoot,oResize, minX, maxX, minY, maxY)
	{

    o.onmousedown	= Drag2.start;
 	  o.hmode			= true ;
		o.vmode			= true ;
		o.root = oRoot && oRoot != null ? oRoot : o ;
	},

	start : function(e)
	{
		var o = Drag2.obj = this;
		e = Drag2.fixE(e);
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );

		o.lastMouseX	= e.clientX;
		o.lastMouseY	= e.clientY;

  	o.minMouseX	= e.clientX - x + o.minX;
	  o.maxMouseX	= o.minMouseX + o.maxX - o.minX;

    o.minMouseY	= e.clientY - y + o.minY;
    o.maxMouseY	= o.minMouseY + o.maxY - o.minY;

		document.onmousemove	= Drag2.resize;
		document.onmouseup		= Drag2.end;

		return false;
	},

	resize : function(e)
	{
		e = Drag2.fixE(e);
		var o = Drag2.obj;

		var ey	= e.clientY;
		var ex	= e.clientX;
		var y = parseInt( o.root.style.height);
		var x = parseInt( o.root.style.width );
		var nx, ny;

		nx = x + (ex - o.lastMouseX) ;
		ny = y + (ey - o.lastMouseY) ;

   
   if(ny > 49)
     {		 
		Drag2.obj.root.style[ "height" ] = ny + "px";
	 }
	 
   if(nx > 49)
     {		 
		Drag2.obj.root.style[ "width" ] = nx + "px";
	 }
		
		

    document.getElementById('window_height').style[ "height" ] = (ny - 35) + "px";

    Drag2.obj.lastMouseX	= ex;
    Drag2.obj.lastMouseY	= ey;

		return false;
	},

	end : function()
	{
		document.onmousemove = null;
		document.onmouseup   = null;
		Drag2.obj = null;
	},

	fixE : function(e)
	{
		if (typeof e == 'undefined') e = window.event;
		if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
		if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
		return e;
	}
};

 var Drag = {

	obj : null,

	init : function(o, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
	{
		o.onmousedown	= Drag.start;

		o.hmode			= bSwapHorzRef ? false : true ;
		o.vmode			= bSwapVertRef ? false : true ;

		o.root = oRoot && oRoot != null ? oRoot : o ;

		if (o.hmode  && isNaN(parseInt(o.root.style.left  ))) o.root.style.left   = "0px";
		if (o.vmode  && isNaN(parseInt(o.root.style.top   ))) o.root.style.top    = "0px";
		if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right  = "0px";
		if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px";

		o.minX	= typeof minX != 'undefined' ? minX : 0;
		o.minY	= typeof minY != 'undefined' ? minY : 0;
		o.maxX	= typeof maxX != 'undefined' ? maxX : null;
		o.maxY	= typeof maxY != 'undefined' ? maxY : null;

		o.xMapper = fXMapper ? fXMapper : null;
		o.yMapper = fYMapper ? fYMapper : null;

		o.root.onDragStart	= new Function();
		o.root.onDragEnd	= new Function();
		o.root.onDrag		= new Function();
	},

	start : function(e)
	{
		var o = Drag.obj = this;
		e = Drag.fixE(e);
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		o.root.onDragStart(x, y);

		o.lastMouseX	= e.clientX;
		o.lastMouseY	= e.clientY;

		if (o.hmode) {
			if (o.minX != null)	o.minMouseX	= e.clientX - x + o.minX;
			if (o.maxX != null)	o.maxMouseX	= o.minMouseX + o.maxX - o.minX;
		} else {
			if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x;
			if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x;
		}

		if (o.vmode) {
			if (o.minY != null)	o.minMouseY	= e.clientY - y + o.minY;
			if (o.maxY != null)	o.maxMouseY	= o.minMouseY + o.maxY - o.minY;
		} else {
			if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y;
			if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y;
		}

		document.onmousemove	= Drag.drag;
		document.onmouseup		= Drag.end;

		return false;
	},

	drag : function(e)
	{
		e = Drag.fixE(e);
		var o = Drag.obj;

		var ey	= e.clientY;
		var ex	= e.clientX;
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		var nx, ny;

 	if (o.minX != null) ex = o.hmode ? Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX);
		if (o.maxX != null) ex = o.hmode ? Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX);
		if (o.minY != null) ey = o.vmode ? Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY);
		if (o.maxY != null) ey = o.vmode ? Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY);

		nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1));
		ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));

  if (o.xMapper)		nx = o.xMapper(y)
		else if (o.yMapper)	ny = o.yMapper(x)

		Drag.obj.root.style[o.hmode ? "left" : "right"] = nx + "px";
		Drag.obj.root.style[o.vmode ? "top" : "bottom"] = ny + "px";
		Drag.obj.lastMouseX	= ex;
		Drag.obj.lastMouseY	= ey;

  Drag.obj.root.onDrag(nx, ny);
		return false;
	},

	end : function()
	{
		document.onmousemove = null;
		document.onmouseup   = null;
		Drag.obj.root.onDragEnd(	parseInt(Drag.obj.root.style[Drag.obj.hmode ? "left" : "right"]),
									parseInt(Drag.obj.root.style[Drag.obj.vmode ? "top" : "bottom"]));
		Drag.obj = null;
	},

	fixE : function(e)
	{
		if (typeof e == 'undefined') e = window.event;
		if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
		if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
		return e;
	}
};

// Компиляция окна справки
function blog_repa_compile(win,move,resize,title)
{
	content = document.getElementById( win );

		var my_width  = 0;
		var my_height = 0;



		if ( typeof( window.innerWidth ) == 'number' )
		{
			my_width  = window.innerWidth;
			my_height = window.innerHeight;
		}
		else if ( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
		{
			my_width  = document.documentElement.clientWidth;
			my_height = document.documentElement.clientHeight;
		}
		else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) )
		{
			my_width  = document.body.clientWidth;
			my_height = document.body.clientHeight;
		}

		var divheight = parseInt( content.style.Height );
		var divwidth  = parseInt( content.style.Width );

		divheight = divheight ? divheight : 250;
		divwidth  = divwidth  ? divwidth  : 400;

		content.style.left =  (my_width  / 2  - (divwidth / 2))+document.documentElement.scrollLeft+'px';
		content.style.top  =  (my_height / 2 - (divheight / 2 ))+document.documentElement.scrollTop+ 'px';

    	content.style.position = 'absolute';
		content.style.display  = 'block';

		content.style.zIndex   = 99;

		var theHandle = document.getElementById(move);
		var theRoot   = document.getElementById(win);
        var theResize   = document.getElementById(resize);


  	Drag.init(theHandle, theRoot);	
	Drag2.init(theResize, theRoot);
}

// Секретная опция

function hidden_showrow( name )
{
  if(!name){return false;}	
  
  if(document.getElementById( name ).value=="+")
    {
	  document.getElementById( name ).value="-";
	  document.getElementById( name ).title="Скрыть дополнителые опции";	  
	  return false;
	}
  if(document.getElementById( name ).value=="-")
    {
	  document.getElementById( name ).value="+";
	  document.getElementById( name ).title="Показать дополнителье опции";
	  return false;
	}
}

// Предпросмотр дизайна блога

function showstyle()
{
  var style = window.document.getElementById("style").value;
  
  if (style !=='---')
    {
	  document.getElementById("style_demo").style.display = "block";
	  document.getElementById("style_demo").innerHTML = '<center><a href="/templates/'+dle_skin+'/blog/'+style+'/preview.jpg" onclick="return hs.expand(this)"><img src="/templates/'+dle_skin+'/blog/'+style+'/preview.jpg" border="0" style="width:300px;" title="Увеличить картинку" alt="Картинка не найдена"></a></center>';
	}
	 else
	{
	  document.getElementById("style_demo").style.display = "none";	
	}
}

// Смена языка для редактирования

function change_lang( url )
{
  var lang_edit = window.document.getElementById("lang").value;
  if(lang_edit != "")
    {
	  window.location.href = url+lang_edit;
	}
  return false;
}

//---------------------------------------------------
// Репутация блогов
//---------------------------------------------------

function blog_repa_all(width,height,blog_alt_name,blog_name,action,relation){

  var ajax = new dle_ajax();
	ajax.onShow ('');	
	
	if(action)
	  {
	    ajax.setVar("action", action);
		document.getElementById('blog_resize').style.display='none';
		document.getElementById('blog_no_resize').style.display='block';
	  }
	   else
	  {
		document.getElementById('blog_resize').style.display='block';
		document.getElementById('blog_no_resize').style.display='none'  
	  }		  
	
	if(action == "add")
	  {
		  var reason = document.getElementById('reason').value;
		  reason = ajax.encodeVAR( reason );
		  ajax.setVar("reason", reason);
		  ajax.setVar("relation", relation);
	  }
	 
	ajax.setVar("relation", relation);
	ajax.setVar("skin", dle_skin);
	ajax.setVar("blog_alt_name", blog_alt_name);
	ajax.requestFile = dle_root + "engine/ajax/blog/reputation.php";
	ajax.method = 'POST';
    ajax.element = 'blog_repa_text';
    ajax.onCompletion = winshow;    
	document.getElementById('blog_repa').style['width']=width+"px";
    document.getElementById('blog_repa').style['height']=height+"px";
	document.getElementById('blog_repa_title').innerHTML = 'Репутация блога: ' + blog_name;
	ajax.setVar("window_height",document.getElementById('blog_repa').style['height']) ;
    ajax.sendAJAX('');

  return false;
};

// Альтернатива функции $_GET в php
function php_get(type){
  if(location.href.match(type))
    {
      return location.href.split(type+'=')[1].split('&')[0];
    }
}

// Свёртывание и развёртывание блоков в админке
var hidden_showorhide = new Array();
function hidden_ShowOrHide( name )
{
  if(!name){return false;}	
  
  if(hidden_showorhide[ name ] == 1)
    {
	  document.getElementById( name ).title="Свернуть";
	  document.getElementById( name ).alt="Свернуть";
	  document.getElementById( name ).src="/templates/" + dle_skin + "/blog/admin/images/minus.gif";	  
	  hidden_showorhide[ name ] = 0;	  
	}
     else
    {
	  document.getElementById( name ).title="Раскрыть";
	  document.getElementById( name ).alt="Раскрыть";
	  document.getElementById( name ).src="/templates/" + dle_skin + "/blog/admin/images/plus.gif";	 
	  hidden_showorhide[ name ] = 1;
	}
  return false;
}

// Подтверждение удаления пользователя
function del_user( user_id, user, blog_alt ) { 
    formCheck = confirm("Вы уверены, что хотите удалить данного пользователя? Данное действие невозможно будет отменить.");
    if(formCheck == true)
      {
         del_user_ok( user_id, user, blog_alt )
      }
       else
      {
        return false;
      }
   }

// Удаление пользователя
function del_user_ok( id, name, blog ){
	
  var ajax = new dle_ajax();
	ajax.onShow ('');	
	 
	name = ajax.encodeVAR( name );
	ajax.setVar("user_id", id);
	ajax.setVar("user", name);
	ajax.setVar("blog", blog);
	ajax.requestFile = dle_root + "engine/ajax/blog/deluser.php";
	ajax.method = 'POST';
	ajax.execute = true;
    ajax.element = 'users-' + id;
    ajax.sendAJAX('users-' + id);
	  
}

// Подтверждение удаления новости
function del_news( news_id, blog_alt ) { 
    formCheck = confirm("Вы уверены, что хотите удалить данную статью? Данное действие невозможно будет отменить.");
    if(formCheck == true)
      {
         del_news_ok( news_id, blog_alt )
      }
       else
      {
        return false;
      }
   }

// Удаление новости
function del_news_ok( id, blog ){
	
  var ajax = new dle_ajax();
	document.getElementById("news-del-" + id).innerHTML = '<img src="/templates/' + dle_skin + '/blogimages/ajax/mini-ajax.gif" border="0">';
	 
	ajax.setVar("news_id", id);
	ajax.setVar("blog", blog);
	ajax.requestFile = dle_root + "engine/ajax/blog/delnews.php";
	ajax.method = 'POST';
    ajax.element = 'news-' + id;
    ajax.sendAJAX('news-' + id);
	  
}

// AJAX навигация по блогу
function blog_ajax_navigation( url ){
	
	showBusyLayer();
	
	var ajax = new dle_ajax();
	ajax.onShow ('');
	ajax.requestFile = dle_root + "engine/ajax/blog/ajax_navigation.php";
	ajax.method = 'GET';
	ajax.execute = true;
    ajax.element = 'dle-content';
	ajax.onCompletion = hideBusyLayer;
    ajax.sendAJAX( url );
	
}


//---------------------------------------------
// "Начало" Комментарии
//---------------------------------------------

var answer_comments_id = new Array();
var answer_array = new Array();

// Функция показа формы ответа на комментарий

function answer_comments( id, title_addcomments ){

	if(!answer_comments_id[ id ])
		{
			answer_comments_false();			
			document.getElementById('tree_comments_form-' + id).innerHTML = form_test;
			answer_comments_id[ id ] = 1;
			document.getElementById('addcomments_form').innerHTML = "";
			document.getElementById('cancel_answer').style['display'] = "";
			document.getElementById('cancel_answer').innerHTML = "<input type=\"button\" onClick=\"answer_comments("+id+"); return false;\" value=\"Отмена\" class=\"bbcodes\"><input type=\"hidden\" name=\"answer_id\" value=\""+id+"\">";
			document.getElementById('title_add_comments').innerHTML = title_addcomments;
		}
			else
		{
			answer_comments_false();
			document.getElementById('addcomments_form').innerHTML = form_test;
			document.getElementById('cancel_answer').style['display'] = "none";
			document.getElementById('title_add_comments').innerHTML = "Добавление комментария";
		}
}

// Функция отмены ответа на комментарий

function answer_comments_false(){

	for(var i=1; i<= count_com; i++)
				{
					document.getElementById('tree_comments_form-' + answer_array[i]).innerHTML = "";
					answer_comments_id[ answer_array[i] ] = 0;
				}
	
}

// Функция добавление комментария

function add_blog_comments(){

	var form = document.getElementById('dle-comments-form');
    var dle_comments_ajax = new dle_ajax();

	if (dle_wysiwyg == "yes") {
		document.getElementById('comments').value = tinyMCE.get('comments').getContent();
		dle_comments_ajax.setVar("editor_mode", 'wysiwyg');
	} 

	if (form.comments.value == '' || form.name.value == '')
	{
		alert ( dle_req_field );
		return false;
	}

	dle_comments_ajax.onShow ('');
	var varsString = "post_id=" + form.post_id.value;
	dle_comments_ajax.setVar("blog", form.blog.value);
	dle_comments_ajax.setVar("comments", dle_comments_ajax.encodeVAR(form.comments.value));
	dle_comments_ajax.setVar("name", dle_comments_ajax.encodeVAR(form.name.value));
	dle_comments_ajax.setVar("mail", dle_comments_ajax.encodeVAR(form.mail.value));
	dle_comments_ajax.setVar("skin", dle_skin);

	if ( form.sec_code ) {

	   dle_comments_ajax.setVar("sec_code", form.sec_code.value);

    }

	if(form.answer_id)
		{
			dle_comments_ajax.setVar("answer_id", form.answer_id.value);
		}

	dle_comments_ajax.requestFile = dle_root + "engine/ajax/addcomments.php";
	dle_comments_ajax.method = 'POST';
	dle_comments_ajax.execute = true;
	
	if(form.answer_id)
		{
			dle_comments_ajax.element = 'tree_comments_form-' + form.answer_id.value;
			document.getElementById('button_answer_to_' + form.answer_id.value).innerHTML = "Ответить";
		}
			else
		{
			dle_comments_ajax.element = 'dle-ajax-comments';
		}
		
	dle_comments_ajax.sendAJAX(varsString);

};

//---------------------------------------------
// "Конец" Комментарии
//---------------------------------------------

// Массовое управление пользователями

function mass_users(){

	if(document.forms['mass_user']['mass_del'].checked)
		{
			alert('Внимание! При нажатии на кнопку отправить, если вы не снимите галочку с данного флажка, то у вас удалятся все подключенные пользователи.');
			!document.forms['mass_user']['mass_moder'].setAttribute('disabled', 'disabled'); 
			!document.forms['mass_user']['mass_com'].setAttribute('disabled', 'disabled'); 
			!document.forms['mass_user']['mass_news'].setAttribute('disabled', 'disabled'); 
			!document.forms['mass_user']['mass_ban'].setAttribute('disabled', 'disabled'); 
		}
			else
		{
			!document.forms['mass_user']['mass_moder'].removeAttribute('disabled');
			!document.forms['mass_user']['mass_com'].removeAttribute('disabled');
			!document.forms['mass_user']['mass_news'].removeAttribute('disabled'); 
			!document.forms['mass_user']['mass_ban'].removeAttribute('disabled');
		}

}

// Просмотр краткой статьи в списке новостей блога

function blog_allnews( id ){
	
	var ajax = new dle_ajax();
	
	document.getElementById('img_allnews-'+id).innerHTML = '<img src="/templates/' + dle_skin + '/blogimages/ajax/mini-ajax.gif" border="0" align="absmiddle">';
	
	ajax.setVar("skin", dle_skin);
	ajax.setVar("id", id);
	ajax.setVar("blog_alt", blog_alt);
	ajax.requestFile = dle_root + "engine/ajax/blog/allnews.php";
	ajax.method = 'GET';
	ajax.execute = true;
    ajax.element = 'allnews-'+id;
    ajax.sendAJAX( 'allnews-'+id );
	
}

// Смена картинки при скрытии краткой статьи в листе новостей блога

function allnews_ShowOrHide( id ){
	
	if(!allnews_ShowOrHide[ id ])
		{
			document.getElementById('img_allnews-'+id).innerHTML = '<img style="cursor: pointer;" src="{THEME}/blogimages/allnews_plus.gif" onclick="javascript:ShowOrHide(\'short_allnews-{$id}\'); allnews_ShowOrHide(\'img_allnews-{$id}\');" align="absmiddle" border="0">';	
			allnews_ShowOrHide[ id ] = true;
		}
			else
		{
			document.getElementById('img_allnews-'+id).innerHTML = '<img style="cursor: pointer;" src="{THEME}/blogimages/allnews_minus.gif" onclick="javascript:ShowOrHide(\'short_allnews-{$id}\'); allnews_ShowOrHide(\'img_allnews-{$id}\');" align="absmiddle" border="0">';	
			allnews_ShowOrHide[ id ] = false;	
		}

}