var FlagMovingIsInited = false;
var FlagMoving = false;
var ForumsIsConfig = false;
var ForumsIsConfigIsInited = false;

var SortContainer = ".forum-container";
var SortForumsSequence = '';

var ResponsePage = "ajax/active-forums.php";

var ErrorShortDisable = 'Ошибка: Не удалось сохранить порядок форумов. Пожалуйста, обратитесь к администратору.';
var ErrorVisibilityDisable = 'Ошибка: Не удалось сохранить состояние форума (скрытие). Пожалуйста, обратитесь к администратору.';
var ErrorStatusesDisable = 'Ошибка: Не удалось сохранить состояние форума (отключение). Пожалуйста, обратитесь к администратору.';

var anchar_pic_1 = IMAGESET_PATH + '/active-forums-anchor.gif';
var anchar_pic_2 = IMAGESET_PATH + '/active-forums-anchor-2.gif';
var show_pic = IMAGESET_PATH + '/active-forums-show.gif';
var hide_pic = IMAGESET_PATH + '/active-forums-hide.gif';
var hide_d_pic = IMAGESET_PATH + '/active-forums-hide-disable.gif';
var close_pic = IMAGESET_PATH + '/active-forums-close.gif';
var close_d_pic = IMAGESET_PATH + '/active-forums-close-disable.gif';
var open_pic = IMAGESET_PATH + '/active-forums-start.gif';
var config_pic_1 = IMAGESET_PATH + '/active-forums-config.gif';
var config_pic_2 = IMAGESET_PATH + '/active-forums-config-2.gif';

var current_forum = null;
var forum_control_hide_show_icon = null;
var forum_control_open_close_icon = null;

var background_position_ie_fix = null;

$(function() {
		   
	// ======================================================================
	// Категории
	// ======================================================================
		   		   
	// -------------------------------------
	// Настройка перемещения форумов
	// -------------------------------------
	
	$( SortContainer ).sortable({
		axis: 'y',
		cursor: 'crosshair',
		opacity: 0.8,
		scroll: true,
		handle: '.drag-handle',
		distance: 0,
		
		update: function(event, ui) {
			SortForumsSequence = '';
			
			$( SortContainer + ' *[category_id]').each( function( i ) {
				var category_id = $( this ).attr('category_id');
				
				if ( SortForumsSequence == '' ) {
					SortForumsSequence += category_id;
				} else {
					SortForumsSequence += ',' + category_id;
				}
			});
			
			$.post( 
				ResponsePage,
				{ 
					'IsAjax': "yes", 
					'Action': "Sort",
					'SortForumsSequence': SortForumsSequence
				},
				function(data){
					if ( data != '1' ) {
						alert( ErrorShortDisable );
					}
				}
			);
		}
	
	});
	
	$( SortContainer ).sortable( 'disable' );
	
	$( SortContainer ).disableSelection();

	// ------------------------------------------
	// Скрытие и отображение форумов
	// ------------------------------------------
	$('.show-hide-icon').each( function( i ) {
										
		$( this ).click( function () {
			var src = $( this ).attr( 'src' );
			var category_id = GetCategory( this ).attr('category_id'); 
			var category_content = GetCategoryContent( this ); 
			var category_cab_be_fliped = GetCategory( this ).attr('can_be_fliped');  

			if ( src == show_pic  ) {

				$( this ).attr( 'src', hide_pic );
				SetVisibility( category_content, true, true ); 
				hidden_categories_count -= 1;
				var state = 'on'; 
				SaveState( "Visibility", category_id, 0, state );
				
			} else {
				if ( category_cab_be_fliped == 'yes' ) {
					$( this ).attr( 'src', show_pic );
					SetVisibility( category_content, false, true );  
					hidden_categories_count += 1;
					var state = 'off';
					SaveState( "Visibility", category_id, 0, state );
				}				
			}
			
			$('#active-forums-hidden-cat').text( hidden_categories_count );			
		});
		
	});
	
	// ------------------------------------------
	// Закрытие форумов
	// ------------------------------------------
	$('.close-open-icon').each( function( i ) {
										
		$( this ).click( function () {
			var src = $( this ).attr( 'src' );
			var category = GetCategory( this ); 
			
			if ( category ) {
				
				var category_id = category.attr('category_id'); 
				var category_status = category.attr('category_status');
				var category_cab_be_deleted = category.attr('can_be_deleted');  
				
				if ( showing_all_forums ) {
					
					if ( category_status == 'closed' ) {
						$( this ).attr( 'src', close_pic );
						category.removeClass('category-invisible');	
						category.attr('category_status', 'opened');
						closed_categories_count -= 1;
						var state = 'on'; 
						SaveState( "Statuses", category_id, 0, state );
						
					} else {
						if ( category_cab_be_deleted == 'yes' ) {
							$( this ).attr( 'src', open_pic );
							category.addClass('category-invisible');
							category.attr('category_status', 'closed');
							closed_categories_count += 1;
							var state = 'off'; 
							SaveState( "Statuses", category_id, 0, state );
						}
					}
					
				} else {
					if ( category_cab_be_deleted == 'yes' ) {
						category.css('display', 'none');
						category.attr('category_status', 'closed');
						closed_categories_count += 1;
						SaveState( "Statuses", category_id, 0, state );
					}
				}
								
			}			
			
			$('#active-forums-closed-cat').text( closed_categories_count );			
			
		});
	});
	
	// ------------------------------------------
	// Перемещение форумов
	// ------------------------------------------
	$('.drag-icon').each( function( i ) {
		$( this ).click( function () {
			if ( ( FlagMoving == true ) || ( FlagMovingIsInited == false ) ) {
				
				FlagMoving = false;
				FlagMovingIsInited = true;
				
				$('.drag-icon').attr( 'src', anchar_pic_2 );
				
				$( 'ul.forums' ).each( function() {
					SetVisibility( this, false, false );
				})
				
				$(".forum-container").sortable( 'enable' );
				
				$('.show-hide-icon').addClass( 'icon-hidden' );
				$('.close-open-icon').addClass( 'icon-hidden' );
				$('.drag-handle').removeClass( 'icon-hidden' );
				$('.drag-handle2').removeClass( 'icon-hidden' );
				
			} else {
				
				FlagMoving = true;
				
				$('.drag-icon').attr( 'src', anchar_pic_1 );
								
				$( 'ul.forums' ).each( function() {
					SetVisibility( this, true, false );
				})
				
				$(".forum-container").sortable( 'disable' );
				
				$('.show-hide-icon').removeClass( 'icon-hidden' );
				$('.close-open-icon').removeClass( 'icon-hidden' );
				$('.drag-handle').addClass( 'icon-hidden' );
				$('.drag-handle2').addClass( 'icon-hidden' );

			}
		});
	});
	
	// ------------------------------------------
	// Конфигурирование
	// ------------------------------------------
	$('.config-icon').each( function( i ) {
		$( this ).click( function () {

			if ( ( ForumsIsConfig == false ) || ( ForumsIsConfigIsInited == false ) ) {
				
				ForumsIsConfig = true;
				ForumsIsConfigIsInited = true;
				
				$('.config-icon').attr( 'src', config_pic_2 );
				
			} else {

				ForumsIsConfig = false;
				$(".forum-container .af-fly-control").css('display', 'none');
				$('.config-icon').attr( 'src', config_pic_1 );
				
			}
		});
	});
	
	// ======================================================================
	// Форумы/Подкатегории
	// ======================================================================

	// -------------------------------------
	// Плавующая панель управления
	// -------------------------------------
	
	$('li.row').each( function() {
		$( this ).hover(
			function() {
				current_forum = $( this );

				if ( ForumsIsConfig )
					DisplayForumControls( this ); 
								
			},
			function() {}
		)
	});
	
	// -------------------------------------
	// Кнопка сворачивания/разворачивания	
	// -------------------------------------
	
	$(".forum-container .af-fly-control .forum-show-hide-icon").click( function() {
		if ( current_forum ) {
			
			var content_visibility = current_forum.attr('forum_content_visibility');
			
			var can_be_fliped = current_forum.attr('can_be_fliped');
			
			var forum_id = current_forum.attr('forum_id'); 
			var category_id = current_forum.attr('category_id'); 	
			
			if ( !content_visibility || content_visibility == 'yes' ) {
				if ( can_be_fliped == 'yes' ) {
					CloseForum( current_forum );
					forum_control_open_close_icon.attr( 'src', show_pic );	
					var state = 'off'; 
					hidden_forums_count += 1;
				}
			} else {
				Openforum( current_forum );
				forum_control_open_close_icon.attr( 'src', hide_pic );
				var state = 'on'; 
				hidden_forums_count -= 1;
			}
			
			$('#active-forums-hidden-for').text( hidden_forums_count );	
			SaveState( "Visibility", forum_id, category_id, state );
			
		}
	});
	
	forum_control_open_close_icon = $(".forum-container .af-fly-control .forum-show-hide-icon");
	
	// -------------------------------------
	// Кнопка удаления/отображения	
	// -------------------------------------
	
	$(".forum-container .af-fly-control .forum-close-open-icon").click( function() {
		if ( current_forum ) {
			
			var forum_visibility = current_forum.attr('forum_visibility');
			
			var can_be_deleted = current_forum.attr('can_be_deleted');
			
			var forum_id = current_forum.attr('forum_id'); 
			var category_id = current_forum.attr('category_id');
			
			if ( !forum_visibility || forum_visibility == 'yes' ) {
				if ( can_be_deleted == 'yes' ) {
					forum_control_hide_show_icon.attr( 'src', close_pic );
					HideForum( current_forum );
					var state = 'off'; 
					closed_forums_count += 1;
				}
			} else {
				forum_control_hide_show_icon.attr( 'src', open_pic );
				ShowForum( current_forum );
				var state = 'on'; 
				closed_forums_count -= 1;
			}
			
			SaveState( "Statuses", forum_id, category_id, state );
			
			$('#active-forums-closed-for').text( closed_forums_count );	
			
		}
	});
	

	forum_control_hide_show_icon = $(".forum-container .af-fly-control .forum-close-open-icon");

});

// ---
// Получение категории по любому вложенному объекту
// ---
function GetCategory( obj ) {
	obj = $( obj );
	if ( obj ) {
		var parent = obj.parent();
		while ( parent ) {
			if ( parent.attr( 'category_id' ) ) break;
			parent = parent.parent();
		}
		if ( parent ) return parent;
	}
	return null;
}

// ---
// Получение категории по любому вложенному объекту
// ---
function GetCategoryContent( obj ) {
	var category = GetCategory( obj );
	if ( category ) return category.find( '.forums' );
	return null;
}

// ---
// Устанвока видимости объекта
// ---
function SetVisibility( obj, state, force ) {
	
	if ( obj ) {
		
		obj = $( obj );
		
		var display = 'none';
		var visibility_attr = 'no';
		
		if ( state ) {
			display = 'block';
			visibility_attr = 'yes';
		}
		
		if ( force ) {
			
			obj.attr( 'item_visibility', visibility_attr );
			obj.css( 'display', display );
			
		} else {
			
			visibility_attr = obj.attr( 'item_visibility' );
			var force_state = ( visibility_attr == 'yes' ) ? true : false;
			
			if ( force_state ) {
				obj.css( 'display', display );	
			}
			
		}
	}
	
}

// -------------------------------------
// Форумы/Подкатегории
// -------------------------------------

// ---
// Позиционирование элемента управления формумом
// ---
function DisplayForumControls( forum ) {
	var forum = $( forum );
	
	var coords = forum.offset();
	var title = forum.find('dt');
	
	var can_be_deleted = forum.attr('can_be_deleted');
	var can_be_fliped = forum.attr('can_be_fliped');

	
	$(".forum-container .af-fly-control")
		.css( {'top': coords.top})
		.css('left', coords.left + title.width() - 15 )
		.css('display', 'block');
		
	var forum_content_visibility = current_forum.attr('forum_content_visibility');

	if ( !forum_content_visibility || forum_content_visibility == 'yes' ) {
		if ( can_be_deleted == 'yes' ) {
			forum_control_open_close_icon.attr( 'src', hide_pic );
		} else {
			forum_control_open_close_icon.attr( 'src', hide_d_pic );
		}
	} else {
		forum_control_open_close_icon.attr( 'src', show_pic );	
	}
	
	var forum_visibility = current_forum.attr('forum_visibility');

	if ( !forum_visibility || forum_visibility == 'yes' ) {
		if ( can_be_deleted == 'yes' ) {
			forum_control_hide_show_icon.attr( 'src', close_pic );
		} else {
			forum_control_hide_show_icon.attr( 'src', close_d_pic );
		}
	} else {
		forum_control_hide_show_icon.attr( 'src', open_pic );	
	}
}

function CloseForum( forum ) {
	var forum = $( forum );
	
	forum.find('dt div, dd').each( function() {
		if ( !$( this ).hasClass('forumtitle') ) $( this ).css('display','none');
	});
	
	forum.find('.icon')
		.css( 'background-position', '-200px' )
		.css( 'min-height', '18px' )
		.css( 'height', '18px' );
		
	forum.attr('forum_content_visibility', 'no');
}

function Openforum( forum ) {
	var forum = $( forum );

	forum.find('dt div, dd').each( function() {
		if ( !$( this ).hasClass('forumtitle') ) $( this ).css('display','block');
	});
	
	forum.find('.icon')
		.css( 'background-position', '10px' )
		.css( 'overflow', 'hidden' )
		.css( 'min-height', '35px' )
		.css( 'height', '' );
		
	forum.attr('forum_content_visibility', 'yes');
}

function HideForum( forum ) {
	var forum = $( forum );
	
	if ( showing_all_forums ) {
		forum.addClass('forum-invisible');
		forum.attr('forum_visibility', 'no');
	} else {
		forum.css('display', 'none');
		$(".forum-container .af-fly-control").css('display', 'none');
		forum.attr('forum_visibility', 'no');
	}
}

function ShowForum( forum ) {
	var forum = $( forum );
	
	forum.removeClass('forum-invisible');
	forum.attr('forum_visibility', 'yes');
}

// -------------------------------------
// Ajax-функции
// -------------------------------------

function SaveState( Action, ForumID, ParentID, State ) {
	$.post( 
		ResponsePage,
		{ 
			'IsAjax': "yes", 
			'Action': Action,
			'ForumID': ForumID,
			'ParentID': ParentID,
			'State': State
		},
		function(data){
			if ( data != '1' ) {
				alert( data );
			}
		}
	);
}