/*
	Zestaw funkcji do zarządzania ulubionymi
*/


var Favorites = Favorites || {};

//ilość wyświetlanych elementów - od 0
Favorites.limit = 5;
Favorites.count = 0;
Favorites.current = 1;
Favorites.favs;
Favorites.fadeDuration = 200;

Favorites.initialize = function(){
	
	Favorites.refresh();
	
}//initialize

/**
	Pobieranie ulubionych
*/
Favorites.refresh = function(){
	
//	$('#userfavorites').hide();
	
	$.get(getRelativeURL() + "/ajax.php", { op: 'getFavorites' }, function(data){
			
			$('#userfavorites').html(data);
			Favorites.display();
			
	}, 'html');
	
	
	
}//refresh

/**
	Wyświetlenie ulubionych
*/
Favorites.display = function(){
	
	// porcjujemy UL po 5 elementów i włączamy guziki, gdy są potrzebne
	this.favs = $('#favorites-data');
	this.count = $('#favorites-data>*').length;
	
	
	if( this.count > (this.limit ) ){
		$('#favorites-data>*:gt('+ (this.limit - 1 ) +')').hide();
		this.current = 1;
		
		
		$('#favorites-nav>#down').click(function(){
				Favorites.down();
		});
		
		
		$('#favorites-nav>#up').click(function(){
				Favorites.up();
		});
		
	}//
	
	
	$('#userfavorites').fadeIn(Favorites.fadeDuration);
	
}//

/**
	Przesuwanie w górę
*/
Favorites.up = function(){
	
	if( this.current > 1 ){
		this.current--;	
		
		var start = (this.limit * (this.current - 1));
		var end = (this.limit * (this.current));
		
		$('#favorites-data>li').slice(0, start).hide();
		$('#favorites-data>li').slice(end, this.count).hide();
		$('#favorites-data>li').slice(start, end).fadeIn(this.fadeDuration);
		
	}//
	
}//

/**
	Przesuwanie w dół
*/
Favorites.down = function(){
	
	if( (this.limit * this.current) < this.count ){
		
		
		var start = (this.limit * this.current);
		var end = (this.limit * (this.current + 1));
		
		$('#favorites-data>li').slice(0, start).hide();
		$('#favorites-data>li').slice(end, this.count).hide();
		$('#favorites-data>li').slice(start, end).fadeIn(this.fadeDuration);
		
		this.current++;
		
	}//
	
}//down

/**
	Dodawanie strony do ulubionych
*/
Favorites.add = function(){
	
	if( isLoggedIn() ){
		var title = getPageTitle();
		var url = $(document).attr('baseURI');
		
		$.post(getRelativeURL() + "/ajax.php?op=addFavorite", { title: title, url: url }, function(data){
				
				alert(data);
				
				Favorites.refresh();

		}, 'text');
		
	}//
	
}//Favorites.add

/**
	Usuwanie strony z ulubionych
*/
Favorites.del = function(id){
	
	$.post( getRelativeURL() + "/ajax.php?op=delFavorite", { fav_id: id }, function(data){
			alert(data);
			Favorites.refresh();
	}, 'text');
	
}//delete


$(document).ready( Favorites.initialize );
