/*----------------------------------------------------------------------------//
// Javascript pour le site client  -------------------------------------------//
//----------------------------------------------------------------------------//
// Client : CESH
// Date   : Octobre 2010
//----------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------*/
// Inclusion dynamique des fichiers externes javascripts
/*----------------------------------------------------------------------------*/
function importJavascript(src){ document.write("<script type=\"text/javascript\" src=\"" + src + "\"></scr" + "ipt>"); }
function importCss(href, media){ document.write('<link rel="stylesheet" type="text/css" media="' + media + '" href="' + href + '" />'); }

/*----------------------------------------------------------------------------*/
// Importations de fichiers
/*----------------------------------------------------------------------------*/

importJavascript("/includes/js/plugins/abso.caroussel.js");
importJavascript("/includes/js/plugins/jquery.cookie.js");
importJavascript("/includes/js/plugins/jquery.tooltip.js");
importJavascript("http://s7.addthis.com/js/250/addthis_widget.js#username=xa-4ca202127009fed4");


/* Variables Globales */
var FS_OnePixel = 6.26;//1px in %
var FS_NormalPx = 10;
var FS_MoyenPx = 11;
var FS_GrandPx = 12;
var FS_MorePixel = 0;

/*----------------------------------------------------------------------------*/
// Declarations jQuery
/*----------------------------------------------------------------------------*/
$(document).ready(function() {

    /*  Fix Browsers  ------------------------------------*/
    $("hr").wrap("<div class=\"hr\">");
	

	setTimeout(function(){
		$("#MenuPrincipal > li > a").each(function(){
			var aItemHeight = $(this).height();
			var spanItemHeight = $(this).children("span").height();
			var difference = Math.floor((aItemHeight - spanItemHeight) / 2);
			
			if (difference > 0) {
				$(this).children("span").css("padding-top", difference + "px");
			}
		});
	},100);

	
    if ($('#SiteMap').length > 0) {
        $('#SiteMap > li > ul').each(function() {
            var $subitem = $(this).children('li');
			var maxitem = Math.ceil($subitem.length / 2);
            for (var i = 0; i < maxitem; ++i) {
                equalHeight($($subitem.splice(0, 2)));
            }
        });
    }

    /*  Caroussels  ------------------------------------*/
    AbsoCaroussel.init({
        id: 'Caroussel',
        transition: 'slideLeft',
        wrap: true,
        autostart: {
            interval: CarouselInterval
        },
        preSwitchCallback: function(data) {
            $('#AbsoCaroussel-Caroussel-Items li:nth-child(' + data.source.position + ') a').removeClass("On");
            $('#AbsoCaroussel-Caroussel-Items li:nth-child(' + data.target.position + ') a').addClass("On");
        }
    });

    AbsoCaroussel.init({
        id: 'Equipe',
        transition: 'slideLeft',
        wrap: true,
        autostart: {
            interval: 6000
        },
        preSwitchCallback: function(data) {
            $('#NavEquipe li:nth-child(' + (data.source.position + 1) + ') a').removeClass("On");
            $('#NavEquipe li:nth-child(' + (data.target.position + 1) + ') a').addClass("On");
        }
    });
	
	$("#Equipe").click(function(){
		document.location = $(this).attr("rel");
	});

    AbsoCaroussel.init({
        id: 'Articles',
        transition: 'slideLeft',
        wrap: true,
        preSwitchCallback: function(data) {
            $('#Articles li:nth-child(' + (data.source.position) + ') .Btn').animate({opacity: 0}, 250, function() {
                $(this).css('visibility','hidden').css('opacity','1');
            });
            $('#Articles li:nth-child(' + (data.target.position) + ') .Btn').css('visibility','visible').css('opacity','0').animate({opacity: 1}, 750);
        }
    });

    /*  Redimension du texte  ------------------------------------*/
    $("#OutilsTexte a.Btn").each(function() {
        $(this).attr("href", "javascript:void(0);");
        $(this).click(function() {
            //Get size type
            var sizeType = $(this).attr("rel");
            switch (sizeType) {
                case "Grand":
                    newSize = FS_GrandPx;
                    break;
                case "Moyen":
                    newSize = FS_MoyenPx;
                    break;
                case "Normal":
                default:
                    newSize = FS_NormalPx;
            }
            var formattedSize = ((newSize + FS_MorePixel) * FS_OnePixel) + "%";
		    $("body").css("font-size", formattedSize);
			//Save in cookie
		    $.cookie('font-size', newSize, { path: '/' });
			$.cookie('font-size-type', sizeType, { path: '/' });
            //Ajout de la classe active
            jQuery("#OutilsTexte a").removeClass("On");
            jQuery(this).addClass("On");
        });
    });


    /* 	Questionnaire et FAQ  -------------------------------------------*/
	$('#Faq div.ContenuEditeur, #Questionnaire div.ContenuEditeur').hide();
    $('#Faq h2').click(function() {
		if(!$(this).hasClass("On")) {
			$('#Faq div.ContenuEditeur').hide();
			$('#Faq *').removeClass("On");
			$(this).addClass("On").next("div.ContenuEditeur").addClass("On").slideDown("fast");
		}
    });
	$('#Questionnaire ul li input').click(function() {
		if(!$(this).hasClass("On")) {
			$('#Questionnaire div.ContenuEditeur').hide();
			$('#Questionnaire *').removeClass("On");
			$(this).addClass("On").parent().children("div.ContenuEditeur").addClass("On").slideDown("fast");
		}
    });


    /* 	Champ de recherche  --------------------------------------*/
    $('#txtKeywords').keydown(function(e) {
        if (e.keyCode == 13) {
            redirectToSearchPage(); return false;
        } else {
            return true;
        }
    });
    $('#SearchButton').click(redirectToSearchPage);


    /* 	Pop-up Sondage  --------------------------------------*/
    $("#BtnOuvrirSondage").click(function() {
        $("#PopupSondage").show();
    });
    $("#BtnFermerSondage").click(function() {
        $("#PopupSondage").hide();
    });

	/* 	Tooltip  --------------------------------------*/
    $(".tooltip").tooltip({
        delay: 0,
        showURL: false,
        bodyHandler: function() { return ttBodyHandler(this) }
    });


	$('#MenuPrincipal > li')
		.mouseenter(function(){
			$(this).children('ul').slideDown('fast');
		})
		.mouseleave(function(){
			$(this).children('ul').slideUp('fast');
		})
	;

});

// Tootip body handler
function ttBodyHandler(obj) {
    var data = obj.rel;
	var output = "<div class=\"pointeur\"></div>";
    if (data.charAt(0) == "#")
        output += eval(data.substr(1, data.length));
    else
        output += data;
		
	return output;
}

/* - Equalize Cols ----------------------------------------*/
function equalHeight(group) {
	if(group.length <= 1) return;
	var tallest = 0;
	group.each(function() {
		var thisHeight = $(this).height();
		if(thisHeight > tallest) {
			tallest = thisHeight;
		}
	});
	group.height(tallest);
}

/* - Search Coveo Redirect ----------------------------------------*/
function redirectToSearchPage() {
	var q = $('#txtKeywords');
	var query = q.val();
	if (query != null && query != '' && query != q.attr('title')) {
		document.location = CeshSearchPage + '?q=' + query;
		return false;
	}
}

/* - Image Chercheurs ----------------------------------------*/
function initImageEquipe() {
	$("div.BlocChercheurs").hover(function(){
		$(this).children(".ImagePortrait").fadeOut("fast");
		$(this).children(".Contenu").animate({right: "0px"});
	},function () {
		$(this).children(".ImagePortrait").fadeIn("fast");
		$(this).children(".Contenu").animate({right: "-160px"});
	});
}

/*-----------------------------------------------------------------------
// Fonctions pour le font sizer
-----------------------------------------------------------------------*/

/* Fonction initialisation Taille du texte */
function initFontSize(morePx){
	//Set last size
	var cookieSize = $.cookie("font-size");
	var cookieSizeType = $.cookie("font-size-type");
	if(cookieSize) {
		var formattedSize = ((parseInt(cookieSize) + FS_MorePixel) * FS_OnePixel) + "%";
	    //Ajout de la classe active
	    jQuery("#OutilsTexte a").removeClass("On");
	    jQuery("#OutilsTexte a." + cookieSizeType).addClass("On");
	}
	else {
	    var formattedSize = ((FS_NormalPx + FS_MorePixel) * FS_OnePixel) + "%";
	}
	$("body").css("font-size", formattedSize);
}
	
/*-----------------------------------------------------------------------
// Fonctions pour le player video
-----------------------------------------------------------------------*/
var currentVideoToPlay = "";
var firstVideo = "";

function initVideoPlayer() {
    jQuery("a.BtnVideo").each(function(i) {
        var videoID = jQuery(this).attr("rel");
        if (videoID) {
            if (i == 0) firstVideo = videoID;
            jQuery(this).click(function() {
                changeVideo(jQuery(this).attr("rel"));
            });
            jQuery(this).attr("href", "#VideoPrincipal");
            jQuery("#BoiteVideo-" + videoID).find(".SavoirPlus").hide();
        }
    });
    // Load Default
    if (jQuery("a.BtnVideo").length > 0) {
        if (window.location.href.indexOf('?v=')) {
            var url = window.location.href;
            if (url.indexOf('?') != -1) {
                startID = url.indexOf('?') + 3;
                if (url.indexOf('#') != -1)
                    urlID = url.substr(startID, url.indexOf('#')- startID);
                else
                    urlID = url.substr(startID);
                changeVideo(urlID);
                return;
            }
        }
        changeVideo(firstVideo, false);
       
		var $videoBox = $(".Video");
		var videoMax = Math.ceil($videoBox.length/3);
		for(var i=0; i< videoMax; ++i) {
			equalHeight($($videoBox.splice(0,3)));
		}
    }
}
function changeVideo(id, autostart){
	//Vérification du id s'il existe et/ou s'il joue déjà
    if (id && currentVideoToPlay != id) {
        var as = (autostart== false ? "" : "&autoplay=1");
        // Clear on item
        jQuery("a.BtnVideo").removeClass("On");
        // Load Player
		var player = "<object width=\"438\" height=\"271\">";
		    player += "<param name=\"movie\" value=\"http://www.youtube.com/v/" + id + "&hl=fr&fs=1" + as + "&rel=0&iv_load_policy=3\"></param>";
			player += "<param name=\"allowFullScreen\" value=\"true\"></param>";
			player += "<param name=\"allowscriptaccess\" value=\"always\"></param>";
			player += "<param name=\"bgcolor\" value=\"#000000\"></param>";
			player += "<param name=\"wmode\" value=\"opaque\"></param>";
			player += "<embed src=\"http://www.youtube.com/v/" + id + "&hl=fr&fs=1" + as + "&rel=0&iv_load_policy=3\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" bgcolor=\"#000000\" wmode=\"opaque\" allowfullscreen=\"true\" width=\"438\" height=\"271\"></embed>";
			player += "</object>";
		jQuery("#ConteneurVideo").html(player);
		// Copy data info
		jQuery("#InfoVideo").html(jQuery("#BoiteVideo-" + id).children(".Information").html());
		// Add on state
		jQuery("#BoiteVideo-" + id).children(".BtnVideo").addClass("On");
		currentVideoToPlay = id;
	}
}
