//==============================
// Автор: REZER
// http://delicated.ru/ 
// Специально для модуля блогов
//==============================

// Меню для новости

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/blogcalendar.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/selection.php";
       ajax.method = 'GET';
       ajax.element = 'blog-name-'+blog_name;
       ajax.sendAJAX(varsString);

       return false;
};

// Подключение/отключение от блога

function doStatus( 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/status.php";
       ajax.method = 'GET';
       ajax.element = blog_name;
       ajax.sendAJAX(varsString);

       return false;
};

// Проверка свободности домена при создании блога

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/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 )
{
	
	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/full_about.php";
       ajax.method = 'GET';
       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/full_about.php";
       ajax.method = 'GET';
       ajax.element = 'about';
       ajax.sendAJAX(varsString);

       return false;
};

// Предварительный просмотр новости перед добавлением

function dopreview( title,short_story,full_story )
{
   var ajax = new dle_ajax();
       document.getElementById("blogpreview").innerHTML = '<center><img src="/templates/' + dle_skin + '/blogimages/ajax/ajax.gif" border="0"> Пожалуйста подождите...</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("skin", dle_skin);
       ajax.requestFile = dle_root + "engine/ajax/blog_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";
	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/add_blog_repa.php";
	ajax.method = 'POST';
	ajax.element = 'blog_repa';
	ajax.sendAJAX('blog_repa');


};

// Проверка на свободность для окна справки

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/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();
	ajax.onShow ('');	
	 
	ajax.setVar("skin", dle_skin);
	ajax.setVar("alt_name", alt_name);
	ajax.requestFile = dle_root + "engine/modules/us_rating/ajax.php";
	ajax.method = 'POST';
    ajax.element = 'blog_repa_text';
    ajax.onCompletion = winshow;
	
    if(resize == 'yes')
	  {
	     document.getElementById('blog_resize').style.display='block';
	} else {
		 document.getElementById('blog_resize').style.display='none';
	  }
	
	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('');

  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/modules/us_rating/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';
	} else {
		 document.getElementById('blog_resize').style.display='none';
	  }
    
	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="";
};

// Открытие окна справки
function winshow(){
  blog_repa_compile('blog_repa','blog_repa_header','blog_resize');
  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/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 == 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 > 200)
     {		 
		Drag2.obj.root.style[ "height" ] = ny + "px";
	 }
	 
   if(nx > 200)
     {		 
		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);
}