/*----------------------------------------------------------------------------//
// Javascript pour le site client  -------------------------------------------//
//----------------------------------------------------------------------------//

/*----------------------------------------------------------------------------*/
// 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/jquery.plugin.js");
// importCss("/includes/js/plugins/jquery.plugin.css", "screen");
importJavascript("/includes/abso.navigateur.js");
importJavascript("http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js");
importJavascript("/includes/js/plugins/jquery.thicker.js");
importJavascript("/includes/js/plugins/jquery.watermarkinput.js");

importCss("/includes/js/plugins/abso.thickbox.css", "screen");
importJavascript("/includes/js/plugins/abso.thickbox.js");

/*----------------------------------------------------------------------------*/
// Declarations jQuery
/*----------------------------------------------------------------------------*/
$(document).ready(function() {

	InitOldBrowser();
	
	$("#Contenu table").each(function(){
		var $table = $(this), $pp = $table.parent(), $clone = $table.clone();
		if ($pp.is("p"))
			$pp.replaceWith($clone);
	});
	

    //Taille de police
    $("#Entete .NavFixe li.Police a").click(function() {
        $("#Entete .NavFixe li.Police a").removeClass("On");
        $(this).addClass("On");
        $("body").css("font-size", $(this).attr("rel"));
    });

    //Recherche rapide en entete
    $("#Entete .Recherche .Filtre").each(function() {
        var ref = $(this);
        $("p a", ref).click(function() {
            $(".Liste", ref).slideToggle(150);
            var hasItemSelected = false;
            $("input:checkbox", ref).each(function() {
                if ($(this).attr("checked"))
                    hasItemSelected = true;
            });
        });
    });

    // Champ de recherche
    $("#Entete .Recherche input:text").each(function() {
        var defaultText = $(this).attr("title");
        $(this).Watermark(defaultText);
    });

    //Promos en accueil
    if ($("#AccPromo").size() != 0) {
        $("#AccPromo").thicker({
            childrens: ".Promo",
            idThickerPrevious: "#AccPromo .Nav li.Prec a",
            idThickerNext: "#AccPromo .Nav li.Suiv a",
            idThickerGoTo: "#AccPromo .Nav li.No a"
        });
    }

    //Filtres de repertoire de publications
    $("body.Publi .FormBloc.Filter p.Mode a").click(function() {
        $("body.Publi .FormBloc.Filter span.Groupe").toggle();
        $(this).toggleClass("On");
        return true;
    });

	//Collapse des liens utiles
	$("body.LiensUtiles #Contenu div.Sujet, body.LiensUtiles #Contenu div.Dossier, body.LiensUtiles #Contenu div.Collection").each(function(){
		var curr = $(this);
		if (curr.children("ul, div.Dossier, div.Collection").size() > 0) {
			curr.children("ul, div.Dossier, div.Collection").hide();
			curr.children("h2, h3, h4").prepend('<a href="javascript:void(0);"><img src="/images/Puce_Collapse.gif" alt="" align="baseline" /></a>&nbsp;&nbsp;');
		}
	});
	
	$("body.LiensUtiles #Contenu div.Sujet h2 a").click(function(){
		$("img", $(this).parents("h2")).toggleClass("On");
		$(this).parents("div.Sujet").children("ul, div.Dossier, div.Collection").toggle();
		return false;
	});
	$("body.LiensUtiles #Contenu div.Sujet").each(function(){
		$(this).children("h2").append('&nbsp;&nbsp;<a href="' + $("a:last-child", this).attr("href") + '"><img src="/images/Puce_NewWin.gif" alt="" align="baseline" /></a>');
	});
	
	$("body.LiensUtiles #Contenu div.Dossier h3 a").click(function(){
		$("img", $(this).parents("h3")).toggleClass("On");
		$(this).parents("div.Dossier").children("ul, .Collection").toggle();
		return false;
	});
	$("body.LiensUtiles #Contenu div.Dossier").each(function(){
		$(this).children("h3").append('&nbsp;&nbsp;<a href="' + $("a:last-child", this).attr("href") + '"><img src="/images/Puce_NewWin.gif" alt="" align="baseline" /></a>');
	});
	
	$("body.LiensUtiles #Contenu div.Collection h4 a").click(function(){
		$("img", $(this).parents("h4")).toggleClass("On");
		$(this).parents("div.Collection").children("ul").toggle();
		return false;
	});

	//Formation, tootltip
	$("a.PlusInfo").each(function(){
		var currDiv = $("div#" + $(this).attr("rel"));
		var closeBtn = $('<a href="javascript:void(0);" class="Fermer"><img src="/images/Puce_Fermer.gif" width="14" height="14" alt="" /></a>');
		closeBtn.bind("click", function(){ currDiv.hide(); });
		$(this).click(function(){
			currDiv
				.css({ top: $(this).position().top - 14, left: $(this).position().left - currDiv.outerWidth() + 14 })
				.prepend(closeBtn)
				.toggle();
		});
	});

	//Panier d'achat, MAJ de total
	$("table.Panier tr").not(":first-child").each(function(){
		var currRow = $(this);
		$("span.PrixItem", currRow).text($("input.PrixItem", currRow).val());
		$("input:text", currRow).keyup(function(){
			if (Page_ClientValidate("ShoppingCart"))
				calculTotalPanier();
		});
//		if (Page_ClientValidate("ShoppingCart"))
//			calculTotalPanier();
	});
	
	//EqualHeight pour les FormBloc adjacents
	$(".FormBloc.Demi").not(".EdgeItem").each(function(){
		equalHeight($(this).add($(this).next(".FormBloc.EdgeItem")));
	});
	
	// Ceci ajoute un curseur lors des requêtes ajax
	if (typeof(Sys) != "undefined") {
		Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginAjaxLoading);
		Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(EndAjaxLoading);
    }

//    $('#btnRecherche').click(function() {
//        redirectToSearchPage();
//    });

	$("a.LecteurVideo").click(function(){
		var flashvars = { videoPath: $(this).attr("href") };
		var params = { wmode: "transparent", allowFullScreen: "true" };
		swfobject.embedSWF("/includes/swf/Video.swf", "LecteurFlash", "820", "470", "10.0.0", "", flashvars, params);
		swfobject.createCSS("#LecteurFlash", "outline:none");
		
		tb_show("LecteurFlashWindow", "#TB_inline?height=470&width=820&inlineId=LecteurFlashWindow");
		return false;
	});

});

// -- Saut de champ texte pour téléphone, code postal, etc... -------------
function jumpToNext(self) {
	//alert($(self).attr("id") + "  >  " + $(self).parent().next().children("input:text").attr("id"));//.html());
	if ( $(self).val().length >= parseInt($(self).attr("maxlength")) )
		$(self).parent().next().children("input:text").focus();
}

// ------------------------------------------------------------------------

var horsSecteurDiscount = 1;
function calculTotalPanier() {
    var total = 0.00;
    $("table.Panier tr").not(":first-child").each(function() {
        var currRow = $(this);
        var rowTotal = parseFloat($("input.PrixItem", currRow).val()) * parseFloat($("input:text", currRow).val());
        $("span.TotalItem", currRow).text(formatNumberByCurrentCulture(rowTotal.toFixed(2)) + " $");
        total = parseFloat(total) + parseFloat(rowTotal);
    });
    
    var horsSecteurTotal = parseFloat(total) * parseFloat(horsSecteurDiscount);
    $("table.Sommaire span.SousTotalPanier").text(formatNumberByCurrentCulture(total.toFixed(2)) + " $");

	if ($("table.Sommaire span.HorsSecteurPanier").text() != "N/A") {
	    var formattedHorsSecteurTotal = formatNumberByCurrentCulture(horsSecteurTotal.toFixed(2));
	    $("table.Sommaire span.HorsSecteurPanier").text(formattedHorsSecteurTotal + " $");
	    $("table.Sommaire span.TotalPanier").text(formattedHorsSecteurTotal + " $");
	} else {
	    $("table.Sommaire span.TotalPanier").text($("table.Sommaire span.SousTotalPanier").text() + " $");
	}
}

// ------------------------------------------------------------------------
function formatNumberByCurrentCulture(invariantNumber) {
    var numberVar = Number.parseInvariant(invariantNumber);
    return numberVar.localeFormat("N");
}

// ------------------------------------------------------------------------
function equalHeight(group) {
    tallest = 0;
    $(group).each(function(){
        thisHeight = $(this).height();
        if(thisHeight > tallest)
			tallest = thisHeight;
    });
    $(group).css("min-height", tallest);
	if ($.browser.msie && $.browser.version < 7)
    	$(group).css("height", tallest);
}

// ------------------------------------------------------------------------
function BeginAjaxLoading(sender, args) {
    //window.status = "Attendez svp...";
    document.body.style.cursor = "wait";
}

function EndAjaxLoading(sender, args) {
    //window.status = "Terminé";
    document.body.style.cursor = "default";
}

// ------------------------------------------------------------------------
function RenderClick(e, btnID, validationGroup) {
    if (window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if (e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }
    // Si Enter
    if (keynum == 13) {
        // Lancer un postback sur le bouton passé en paramètre
        if (Page_ClientValidate(validationGroup)) {
            //
            __doPostBack(btnID, '');

        }
        return false;
    }
    return true;
}

// -- Coveo

function redirectToSearchPage() {
    var query = jQuery('#searchQuery').val();
    if (query != null && query != '') {
        window.location = searchPageUrl + "?lang=FR-CA&q=" + query;
    }
}

function CheckSearch(e) {
    if (window.event) { // IE
        keynum = e.keyCode;
    }
    else if (e.which) { // Netscape/Firefox/Opera
        keynum = e.which;
    }
    // Si Enter
    if (keynum == 13) {
        // Lancer la recherche
        redirectToSearchPage();
        return false;
    }
    return true;
}
