/* Script permettant d'animer les blocs sous les articles

   Auteur : F. ALBERT
   
   Le script attache un comportement à toutes les div qui ont la classe bloc-article.
   Il redimentsionne la div contenue qui porte la classe bloc-article-sizeable.
   Trois positions sont gérées :
   		- caché : le bloc bloc-article-sizeable est entièrement caché.
   		- petit : le bloc prend la valeur min-size.
   		- grand : le bloc prend la valeur max-size.

*/

var stringtable = new Array;
stringtable['fr'] = new Array;
stringtable['en'] = new Array;
stringtable['fr']['btn-down'] = "Agrandir ce chapitre";
stringtable['en']['btn-down'] = "Drop-down";
stringtable['fr']['btn-up'] = "Réduire la taille de ce chapitre";
stringtable['en']['btn-up'] = "Colapse";

// Helpers pour gérer un semblant de muiltilinguisme
function _T(code)
{
    var lang = 'fr';
    if (typeof(navigator.language) != 'undefined')
        lang = navigator.language;
    if (typeof(navigator.userLanguage) != 'undefined')
        lang = navigator.userLanguage;
    if (typeof(navigator.browserLanguage) != 'undefined')
        lang = navigator.browserLanguage;
    lang = lang.substring(0, 2);
    if (typeof(stringtable[lang]) != 'array')
        lang = 'fr';
    return stringtable[lang][code];
}

// Tester si un élement est visible
// On peut le faire de plusieurs façon...
jQuery.fn.vba_isVisible = function()
{
    return (this.css('display') == 'none') ? false : true;
};

// Renvoyer les attributs min-height et max-height
jQuery.fn.vba_min_height = function()
{
    var _height = 0;
    var heightText = this.css('min-height');
    if ((typeof(heightText) == 'string') && (heightText != 'none') && /([^ ]+)px/.test(heightText))
    	_height = parseInt(heightText.match(/([^ ]+)px/)); // seulement une taille en pixels...
	return _height;
};
jQuery.fn.vba_max_height = function()
{
    var _height = 0;
    var heightText = this.css('max-height');
    if ((typeof(heightText) == 'string') && (heightText != 'none') && /([^ ]+)px/.test(heightText))
    	_height = parseInt(heightText.match(/([^ ]+)px/)); // seulement une taille en pixels...
	return _height;
};


// Renvoyer la taille du contenu
jQuery.fn.vba_contentHeight = function()
{
    var contents = this.children(".bloc-article-content");
    if (contents.length != 1)
    {
        return -1;
    }
    else
    {
        var contentBloc = contents.eq(0);
        return contentBloc.height();
	}
};

// Test des possibilités de mouvement
jQuery.fn.vba_canGoDown = function(childBloc)
{
    // D'abord, si on est caché, on peut sans aucun doute se rendre visible
    if (childBloc.vba_isVisible() == false)
        return true;
        
    // Si une taille max est définie, on peut s'agrandir tant qu'on ne l'a pas
    // atteinte
    var sizeMax = childBloc.vba_max_height();
    if (sizeMax > 0)
        return (childBloc.height() < sizeMax) ? true : false;
    
    // Sinon, si la taille max est déjà sur auto, on est au maxi (car on n'a pas fixé de taille)
    else if (childBloc.css('height') == 'auto')
    	return false;
    	
    // Sinon, la taille max est atteinte quand on supprime la propriété height
    // du CSS, mais seulement si le contenu est effectivement supérieure à la
    // taille...
    else
    {
        var contentHeight = childBloc.vba_contentHeight();
        if (contentHeight >= 0)
    	    return (childBloc.height() < contentHeight) ? true : false;
    	else
    	    return true;
	}
};
jQuery.fn.vba_canGoUp = function(childBloc)
{
	// On peut se cacher tant qu'on est visible, mais on ne peut plus
	// rien faire quand on est caché, donc c'est le seul paramètre...
    return childBloc.vba_isVisible();
};

// Mise à jour des boutons
jQuery.fn.vba_updateDownButton = function(childBloc)
{
   	var parentBloc = this;
   	var btn = jQuery('#' + parentBloc.attr('id') + '-btn-down', parentBloc);
	if (parentBloc.vba_canGoDown(childBloc))
	{
    	btn.removeClass('vba-btn-disabled').addClass('vba-btn-down');
    	btn.attr('title', _T('btn-down'));
		return true;
	}
    else
    {
    	btn.removeClass('vba-btn-down').addClass('vba-btn-disabled');
    	btn.attr('title', '');
		return false;
	}
};
jQuery.fn.vba_updateUpButton = function(childBloc)
{
   	var parentBloc = this;
   	var btn = jQuery('#' + parentBloc.attr('id') + '-btn-up', parentBloc);
	if (parentBloc.vba_canGoUp(childBloc))
	{
    	btn.removeClass('vba-btn-disabled').addClass('vba-btn-up');
    	btn.attr('title', _T('btn-up'));
		return true;
	}
    else
    {
    	btn.removeClass('vba-btn-up').addClass('vba-btn-disabled');
    	btn.attr('title', '');
		return false;
	}
};
jQuery.fn.vba_updateButtons = function(childBloc)
{
   	var btnContainer = jQuery('.vba-btn-bloc', this);
	var bShow = false;
    bShow |= this.vba_updateDownButton(childBloc);
	bShow |= this.vba_updateUpButton(childBloc);
	if (bShow == true)
        btnContainer.removeClass('vba-btn-bloc-empty').addClass('vba-btn-bloc-filled');
    else
        btnContainer.removeClass('vba-btn-bloc-filled').addClass('vba-btn-bloc-empty');
};

// Actions de redimmensionnement
jQuery.fn.vba_goDown = function(childBloc, onDone)
{
    // Récupérer les tailles
    var sizeMax = childBloc.vba_max_height();
    var sizeMid = childBloc.vba_min_height();
    var sizeCurrent = 0;
    var isVisible = childBloc.vba_isVisible();
    if (isVisible == true)
	    sizeCurrent = childBloc.height();
    
    // Calculer la taille à laquelle on doit s'ouvrir en fonction de la
    // taille actuelle (0 si le panneau est caché).
    var sizeNext = 0;
	if (sizeMid > sizeCurrent)
		sizeNext = sizeMid;
	else if (sizeMax > sizeCurrent)
		sizeNext = sizeMax;
		
	// Fonction callback appelée après les déplacements
    var parentBloc = this;
	function on_go_down()
	{
    	// Si la taille est supérieure au contenu, on a pu agrandir trop
    	// (on ne peut pas fair ece test avant de rendre le panneau visible car
    	// le contenu a une taille 0 s'il n'est pas visible)
        var contentHeight = childBloc.vba_contentHeight();
    	if ((contentHeight >= 0) && (childBloc.height() > contentHeight))
    		childBloc.css('height', 'auto');
    
    	// Signaler le redimensionnement
        childBloc.trigger('vba_resize');
        
        // Mise à jour des boutons
        parentBloc.vba_updateButtons(childBloc);
		
		// Appeler la callback
		if (typeof(onDone) == 'function')
			onDone();
	}
		
	// Fixer la visibilité
	if (isVisible == false)
	{
    	// Fixer la taille future
    	if (sizeNext > 0)
    		childBloc.css('height', '' + sizeNext + 'px');
    	else
    		childBloc.css('height', 'auto');
    
    	// Animation de l'affichage
        childBloc.slideDown('fast', function()
        {
		    childBloc.css('display', 'block');
		    on_go_down();
	    });
	}
	
	// Si on grandit jusqu'à une taille inconnue, peut essayer d'animer
	// jusqu'à la taille du contenu, mais il faut ensuite corriger
	else if (sizeNext <= 0)
	{
    	// Récupérer la taille du contenu et animer si on en récupère une
        var contentHeight = childBloc.vba_contentHeight();
        if (contentHeight >= 0)
        {
            childBloc.animate({'height':''+contentHeight+'px'}, 'fast', function()
            {
    		    childBloc.css('height', 'auto');
		        on_go_down();
            });
        }
        // On n'a pas de taille du contenu, se passer de l'animation
        else
        {
    		childBloc.css('height', 'auto');
		    on_go_down();
	    }
	}
	
	// Sinon animer la taille
	else
	{
        childBloc.animate({'height':''+sizeNext+'px'}, 'fast', function()
        {
    		//childBloc.css('height', '' + sizeNext + 'px');
	        on_go_down();
        });
	}
};
jQuery.fn.vba_goUp = function(childBloc, onDone)
{
    // Récupérer les tailles
    var sizeMid = childBloc.vba_min_height();
    var sizeCurrent = 0;
    var isVisible = childBloc.vba_isVisible();
    if (isVisible == true)
	    sizeCurrent = childBloc.height();
	    
	// Calculer la taille cible
	var sizeNext = 0;
	if (sizeCurrent > sizeMid)
		sizeNext = sizeMid;
    
	// Si la taille est supérieure au contenu, ne pas fixer de taille
    var contentHeight = childBloc.vba_contentHeight();
	if ((contentHeight >= 0) && (sizeNext > contentHeight))
		sizeNext = 0;

	// Fonction callback appelée après les déplacements
    var parentBloc = this;
	function on_go_up()
	{
    	// Signaler le redimensionnement
        childBloc.trigger('vba_resize');
    
        // Mise à jour des boutons
        parentBloc.vba_updateButtons(childBloc);
		
		// Appeler la callback
		if (typeof(onDone) == 'function')
			onDone();
	}
	
	// Fixer la visibilité
	if (sizeNext == 0)
	{
        childBloc.slideUp('fast', function()
        {
		    childBloc.css('display', 'none');
		    on_go_up();
	    });
	}

	// Fixer la taille future
	else
	{
        childBloc.animate({'height':''+sizeNext+'px'}, 'fast', function()
        {
    		//childBloc.css('height', '' + sizeNext + 'px');
    	    on_go_up();
	    });
    }
};

// Fonction appelée sur un div.bloc-article pour rentre le contenu dimensionnable
jQuery.fn.vba_setResizableBloc = function()
{
	// Exécuter sur toutes les div
    return this.each(function()
    {
        // Tester s'il y a un bloc redimensionnable dessous
        var parentBloc = jQuery(this);
        var parentBlocId = parentBloc.attr('id');
        var childs = jQuery('div.bloc-article-sizeable', parentBloc).eq(0);
        if (childs.length == 0)
            return;
            
        // Récupérer le bloc fils
        var childBloc = jQuery(childs[0]);

        // Ajouter les boutons
        var btnHtml = '<div class="vba-btn-bloc">';
        btnHtml += '<a href="#" id="' + parentBlocId + '-btn-down" class="vba-btn vba-btn-disabled"></a>';
        btnHtml += '<a href="#" id="' + parentBlocId + '-btn-up" class="vba-btn vba-btn-disabled"></a>';
        btnHtml += '</div>';
        parentBloc.prepend(btnHtml);
        
        // Mise à jour de l'apparence des boutons
        parentBloc.vba_updateButtons(childBloc);
        
        // Ajout des handlers d'évènement
        jQuery('#' + parentBlocId + '-btn-down', parentBloc).click(function(event)
        {
            if (parentBloc.vba_canGoDown(childBloc))
                parentBloc.vba_goDown(childBloc);
            event.preventDefault();
            return false;
        });
        jQuery('#' + parentBlocId + '-btn-up', parentBloc).click(function(event)
        {
            if (parentBloc.vba_canGoUp(childBloc))
                parentBloc.vba_goUp(childBloc);
            event.preventDefault();
            return false;
        });
        
        // Tester si un des blocs est plus grand que son contenu
        var contentHeight = childBloc.vba_contentHeight();
    	if ((contentHeight >= 0) && (childBloc.height() > contentHeight))
    		childBloc.css('height', 'auto');
        
        // Poster un évènement de redimensionnement, au cas où le contenu en dépende
        childBloc.trigger('vba_resize');
    });
};

// Fonction appelée pour s'assurer qu'un bloc est visible
jQuery.fn.vba_setVisible = function(onDone)
{
	// Tester s'il y a un bloc redimensionnable dessous
	var parentBloc = jQuery(this);
	var childs = jQuery('div.bloc-article-sizeable', parentBloc).eq(0);
	if (childs.length == 0)
		return;
		
	// Récupérer le bloc fils
	var childBloc = jQuery(childs[0]);
	
	// S'il est cacher, simuler un clic down
	if (childBloc.vba_isVisible() == false)
		this.vba_goDown(childBloc, onDone);
	else if (typeof(onDone) == 'function')
		onDone();
};

// Mettre en place au chargement du document
$(document).ready(function()
{
	jQuery("div.bloc-article").vba_setResizableBloc();
});

