var lien_actif;
var etat = "/accueil/ajax";
var menu_imprimer = "";

$(document).ready(function(){
		
	$.ajaxSetup({'timeout':10000});
	
	//insertion de l'objet flash
	var fo = new SWFObject("/flash/animation_logo.swf", "Logo", "150", "150", "9.0");
	fo.addParam("wmode", "transparent");
	fo.write("logo_soleil"); 
	
	//on définit le premier lien (accueil) comme actif
	lien_actif = $('#menu a:first');
	
	//texte défilant
	//$('#marquee').html(multiplie_texte(5,$('marquee').html()));
	//$('#marquee').marquee();
	
	//on met à jour les liens pour être du ajax
	$('#menu a').each(ajaxifier);
	$('#cartouche a').addClass('force_ajax');
	$('#cartouche a').each(ajaxifier);
	$('#contenu a').each(ajaxifier);
	affiche_lien($('#menu a:first'));
	
	//on accordéonise le menu
	accordeon();
	
	//on s'occupe du marquee : on retire la balise et on met juste le ul :
	$("#cartouche").html($("#cartouche marquee").remove().html());
	$('#cartouche ul').addClass("marquee").marquee({
			yScroll: "top"                          // the position of the marquee initially scroll (can be                                                   	// either "top" or "bottom")
			, showSpeed: 850                          // the speed of to animate the initial dropdown of the messages        
			, scrollSpeed: 12                         // the speed of the scrolling (keep number low)
			, pauseSpeed: 5000                        // the time to wait before showing the next message or                                                   // scrolling current message        
			, pauseOnHover: false                      // determine if we should pause on mouse hover        
			, loop: -1                                // determine how many times to loop through the marquees                                                   // (#'s < 0 = infinite)       
			, fxEasingShow: "swing"                   // the animition easing to use when showing a new marquee        
			, fxEasingScroll: "linear"                // the animition easing to use when showing a new marquee         
			// define the class statements        
			, cssShowing: "marquee-showing"         
			// event handlers        
			, init: null                              // callback that occurs when a marquee is initialized        
			, beforeshow: null                        // callback that occurs before message starts scrolling on screen       
			, show: null                             // callback that occurs when a new marquee message is displayed        
			, aftershow: null                         // callback that occurs after the message has scrolled 
	});
	
		ajaxer();
	
	$.History.bind(function(state){
	// Our Generic Handler - Always runs last.	
		if (state.length==0) {
			state = "/accueil/";
			$.get(state + 'ajax', function(data){
			  	$("#contenu").html(data);
				$('#contenu a').each(ajaxifier);
				obj = $('#menu a:first');
				ajaxer();
				affiche_lien(obj);
				lien_actif = obj;
				lien_print();
				etat = obj.attr("href").replace(/ajax/,'');
				$.History.setHash('');
				document.title = "Espace Calorie - " + titre;
			});
		}
		else {
			if (state != etat && state.length!=0){
				$.get(state + 'ajax', function(data){
					$("#contenu").html(data);
					$('#contenu a').each(ajaxifier);
					obj = $("<div></div>");
					obj.attr("href",state + 'ajax');
					ajaxer();
					affiche_lien(obj);
					lien_actif = obj;
					if (printable){
						$("#contenu").append(menu_imprimer.html());
						lien_print();
						//evenement lors d'un clic sur "Version PDF"
						$('#lien_pdf').attr('href',lien_pdf_click());
					}
					etat = obj.attr("href").replace(/ajax/,'');
					$.History.setHash(etat);
					document.title = "Espace Calorie - " + titre;;
				});
			}
		}
	});	
	menu_imprimer = $('#menu_droite');
	menu_imprimer.remove();
});

function multiplie_texte(nb,texte){
	if (nb==1){
		return texte;
	}
	else{
		return texte + multiplie_texte(nb-1,texte);
	}
}

function lien_pdf_click(){
		tab = lien_actif.attr('href').split("/");
		tab.pop();
		tab = tab.join("/")+ ".pdf";		
		
		return tab;
}

function galerie(gal){	
	$('#' + gal).cycle({ 
			fx: 'fade,scrollUp,shuffle,scrollDown,curtainX,turnDown' 
	});
}

function ajaxifier(){
	var href = $(this).attr('href');
	tab = href.split("/");	
	if(jQuery.browser['msie'] && parseInt(jQuery.browser['version'])<7 ){
		return;
	}
	if (tab[0].indexOf(":") == -1 && tab[tab.length - 1] != "ajax" && !$(this).hasClass("noajax") || $(this).hasClass("force_ajax")){		
		href += "/ajax";
		$(this).attr({href : href});
		$(this).addClass("ajax");
	}
	else {
		$(this).attr({target : "_blank"});
	}

}

//on transforme en dynamique
function ajaxer() {
	$('.ajax').die();
	$('.ajax').unbind();
	$('.ajax').ajaxContent({   
		target:'#contenu',
		loadingMsg:'Chargement en cours...',
		errorMsg:'Erreur de chargement de la page, veuillez réessayer.',
		extend:'true',   
		filter:'.ajax',   
		ex_target:'#contenu',
		success: function(obj,target,msg){		
			$('#contenu a').each(ajaxifier);
			ajaxer();
			affiche_lien(obj);
			lien_actif = obj;			
			etat = obj.attr("href").replace(/ajax/,'');
			if (printable){
				$("#contenu").append(menu_imprimer.html());
				lien_print();
				//evenement lors d'un clic sur "Version PDF"
				$('#lien_pdf').attr('href',lien_pdf_click());
			}
			$.History.setHash(etat); 
			document.title = "Espace Calorie - " + titre;
		}
	});
};

function lien_print(){
		tab = lien_actif.attr('href').split("/");
		tab[tab.length - 1] = "print";
   		$('#lien_print').attr('href',tab.join("/")); 
		return false;
}

function affiche_lien(obj){
	$('#menu a').each(function () {		
		if(obj.attr("href") == $(this).attr("href")){
			if($(this).hasClass("submenu")){
				$(this).css({'background-image' : 'url(/images/puce_arbre_select.png)', 'color' : '#000'});
				if(! $(this).parents('li').parents('li').hasClass("open")){
					$(this).parents('li').parents('li').children('a').click();
				}
			}
			else{
				$(this).css({'background-image' : 'url(/images/puce_goutte_select.png)', 'color' : '#000'});
			}
		}
		else{
			$(this).css({'background-image' : '', 'color' : ''});
		};
		$(this).blur();
	});
};

function isInteger(s)
{ 
	var i;
	for (i = 0; i < s.length; i++)
	{
		// Check that current character is number.
		var c = s.charAt(i);
		if (((c < "0") || (c > "9"))) return false;
	}
	// All characters are numbers.
	return true;
}

function stripCharsInBag(s, bag)
{
	var i;
	var returnString = "";
	// Search through string's characters one by one.
	// If character is not in bag, append to returnString.
	for (i = 0; i < s.length; i++)
	{
		// Check that current character isn't whitespace.
		var c = s.charAt(i);
		if (bag.indexOf(c) == -1) returnString += c;
	}
	return returnString;
}

function accordeon(){
	// On cache les sous-menus
        // sauf celui qui porte la classe "open_at_load" :
        $("ul.subMenu:not('.open_at_load')").hide();
        // On selectionne tous les items de liste portant la classe "toggleSubMenu"
    
        // et on remplace l'element span qu'ils contiennent par un lien :
        $("li.toggleSubMenu span").each( function () {
            // On stocke le contenu du span :
            var TexteSpan = $(this).text();
            $(this).replaceWith('<a href="" title="Afficher le sous-menu">' + TexteSpan + '</a>') ;
        } ) ;
    
        // On modifie l'evenement "click" sur les liens dans les items de liste
        // qui portent la classe "toggleSubMenu" :
        $("li.toggleSubMenu > a").click( function () {
            // Si le sous-menu etait deja ouvert, on le referme :
            if ($(this).next("ul.subMenu:visible").length != 0) {
                $(this).next("ul.subMenu").slideUp("normal", function () { $(this).parent().removeClass("open") } );
            }
            // Si le sous-menu est cache, on ferme les autres et on l'affiche :
            else {
                $("ul.subMenu").slideUp("normal", function () { $(this).parent().removeClass("open") } );
                $(this).next("ul.subMenu").slideDown("normal", function () { $(this).parent().addClass("open") } );
            }
            // On empêche le navigateur de suivre le lien :
            return false;
        });
}
