/*----------------------------------------------------------------------------//
// Javascript pour le site client  -------------------------------------------//
//----------------------------------------------------------------------------//
// Client : OCAQ
//----------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------*/
// 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/jquery-ui.js");
importJavascript("/includes/js/plugins/jquery.colorbox-min.js");
importCss("/includes/js/plugins/colorbox.css", "screen");
importCss("/includes/js/datePicker.css", "screen");

/*----------------------------------------------------------------------------*/
// Declarations jQuery
/*----------------------------------------------------------------------------*/

var accordionEnabled = true;
var cloneBox = "";

var timerCloseMenu, timerOpenMenu = null;
var MenuClose = true;
var menuFlag = false;

$(document).ready(function() {
	
	InitOldBrowser();
	
    // ------------------------------------------------------------------------
    // AJUSTEMENTS DYNAMIQUES
    // ------------------------------------------------------------------------
    $("hr").replaceWith("<div class=\"hr\">&nbsp;</div>");
    $("br.Spacer").replaceWith("<span class=\"Spacer\">&nbsp;</span>");
    $("ul#LiensRapides").children("li:last").css("background", "none");
    $("tr:odd", ".Tableau1").children("td").addClass("CelluleAlternative");
    $("tr:odd", ".Tableau2B").children("td").addClass("CelluleAlternative");
    $("tr:odd", "..BlocSommaire table").children("td").addClass("CelluleAlternative");
    equalHeight($("#SectionsAccueil .Section"));

    // ------------------------------------------------------------------------
    // OUVERTURE D'UNE FENÊTRE AVEC COLORBOX
    // ------------------------------------------------------------------------
    $(".Popup").colorbox({ width: "390px;", inline: true, href: "#PopupContent" });
    $(".Popup2").colorbox({ width: "390px;", inline: true, href: "#PopupContent2" });

    $(".PasseClick").click(function() {
        var noPasse = $(this).attr("id");

        $("#PopupContent").find(".PasswordCode").val("");
        $("#PopupContent").find(".PasseId").val(noPasse);
    });

   
    
	// ------------------------------------------------------------------------
    // POSITIONNEMENT DES LOGOS DES PARTENAIRES
    // ------------------------------------------------------------------------
	var partnersBox = $("#Partenaires").width();
	var nbPartners = $("#Partenaires").children("li").length;
   	var pItemsWidth = Math.floor(partnersBox / nbPartners) - 20;
    $("#Partenaires").children("li").css("width", pItemsWidth + "px");

    // ------------------------------------------------------------------------
    // INPUT LABEL FOCUS
    // ------------------------------------------------------------------------
    InputLabelFocus();
	BgInputLabelFocus();

    // ------------------------------------------------------------------------
    // COLONNE LATÉRALE
    // ------------------------------------------------------------------------
    $("#ColonneLaterale").find("ul").each(function() {
        $(this).children("li:last").css("border-bottom", "none");
        $(this).children("li:last").css("padding-bottom", "0");
        $(this).children("li:last").css("margin-bottom", "0");
    });

    // ------------------------------------------------------------------------
    // CALENDRIER
    // ------------------------------------------------------------------------
    initDatePickers();

    // ------------------------------------------------------------------------
    // ACCORDÉONS
    // ------------------------------------------------------------------------
    $(".Accordeon").each(function() {
        $(this).find(".BlocDetails").css("display", "none");
    });

    $(".Accordeon a.Details").click(function() {
        if (accordionEnabled == true) {

            accordionEnabled = false;

            if ($(this).parents(".Accordeon").hasClass("On")) {

                $(this).parents(".Accordeon").toggleClass("On");
                $(this).parents(".Accordeon").find("a.Details").toggleClass("On");
                $(this).parents(".Accordeon").find(".BlocDetails").stop().slideToggle(250, function() {
                    accordionEnabled = true;
                });
            }
            else {
                $(".Accordeon").removeClass("On");
                $(".Accordeon").find("a.Details").removeClass("On");
                $(".Accordeon").find(".BlocDetails").stop().slideUp(250);

                $(this).parents(".Accordeon").addClass("On");
                $(this).addClass("On");
                $(this).parents(".Accordeon").find(".BlocDetails").stop().slideDown(250, function() {
                    accordionEnabled = true;
                });
            }
        }
        return false;
    });

    // ------------------------------------------------------------------------
    // RECHERCHE AVANCÉE/SIMPLIFIÉE
    // ------------------------------------------------------------------------
    $(".AffichageAvance").css("display", "none");
    $(".AffichageAvance").clone().appendTo("#Template");


    $(".BtRechercheAvancee").click(function() {
        cloneBox = $("#Template").clone();
        $(this).css("display", "none");
        $(this).parent().children(".BtRechercheSimplifiee").css("display", "block");
        $(".AffichageAvance").slideDown(200);
        return false;
    });

    $(".BtRechercheSimplifiee").click(function() {
        $(this).css("display", "none");
        $(this).parent().children(".BtRechercheAvancee").css("display", "block");
        $(".AffichageAvance").slideUp(200, function() {
            $(this).replaceWith(cloneBox.html());
        });
        return false;
    });

    // ------------------------------------------------------------------------
    // DESCRIPTION COMPLÈTE DES PUBLICATIONS
    // ------------------------------------------------------------------------
    $(".DescriptionComplete").css("display", "none");

    $(".BlocDescription a.Details").click(function() {
        $(this).toggleClass("On");
        $(".DescriptionComplete").slideToggle(250);
        return false;
    });

    // ------------------------------------------------------------------------
    // SURVOL SUR LE MENU DES SECTIONS
    // ------------------------------------------------------------------------
    $("#MenuSections > li").mouseenter(function() {
        $(this).children("a").addClass("Hover");
        $(this).children("ul").stop(true, true).fadeIn(250);
    });

    $("#MenuSections > li").mouseleave(function() {
        $(this).children("a").removeClass("Hover");
        $(this).children("ul").stop(true, true).fadeOut(250);
    });

    // ------------------------------------------------------------------------
    // SURVOL SUR LE MENU PRINCIPAL D'UNE SECTION
    // ------------------------------------------------------------------------
    var nbMenuItems = $("#MenuPrincipal").children("li").length;
    var menuWidth = $("#MenuPrincipal").width() + 20;
    var itemsWidth = Math.floor(menuWidth / nbMenuItems) - 20;

    $("#MenuPrincipal").children("li").css("width", itemsWidth + "px");

    jQuery("#MenuPrincipal li ul").hide();
    jQuery("#MenuPrincipal").mouseenter(function() {
        if (timerCloseMenu != null) { clearTimeout(timerCloseMenu); }
        timerOpenMenu = setTimeout(function() {
            jQuery("#MenuPrincipal li ul").slideDown("fast", function() {
                MenuClose = false;
            });
        }, 800);
    })
	   .mouseleave(function() {
	       if (timerOpenMenu != null) { clearTimeout(timerOpenMenu); }
	       timerCloseMenu = setTimeout(function() {
	           jQuery("#MenuPrincipal li ul").stop(true, true).slideUp("fast", function() {
	               MenuClose = true;
	           });
	       }, 150);
	   });

    var MenuTallestHeight = Math.max.apply(Math, $("#MenuPrincipal > li > a").map(function() {
        return $(this).height();
    }).get());

    var ListTallestHeight = Math.max.apply(Math, $("#MenuPrincipal > li > ul").map(function() {
        return $(this).height();
    }).get());

    $("#MenuPrincipal > li > a").css("height", MenuTallestHeight + "px");
    $("#MenuPrincipal > li > ul").css("height", ListTallestHeight + "px");
    $("#BlocMenuPrincipal").css("height", MenuTallestHeight + 13 + "px");

    // ------------------------------------------------------------------------
    // OUVERTURE DU MENU DE LA COLONNE GAUCHE
    // ------------------------------------------------------------------------
    $(".TriggerMenuDeroulant").click(function() {
        $(this).parent("li").children("ul").stop(true, true).slideToggle(250);
        $(this).toggleClass("On");
        return false;
    });

    $("a.RetirerDateReunion").click(function() {
        $(this).parents("p.DateReunion").remove();
        return false;
    });

    // ------------------------------------------------------------------------
    // BLOCS POUR FUTURS CA
    // ------------------------------------------------------------------------
    $("#BlocFutursCA").children(".BlocPromo").css("display", "none");
    $("#BlocFutursCA").children(".BlocPromo:first").css("display", "block");

    $("#BlocFutursCA .Navigation").find("a").click(function() {
        var selectedPromo = $(this).attr("href");
        $("#BlocFutursCA .Navigation").find("a").removeClass("On");
        $(this).addClass("On");
        $(".BlocPromo").fadeOut(150);
        $(selectedPromo).fadeIn(250);
        return false;
    });

    // ------------------------------------------------------------------------
    // TOOLTIPS
    // ------------------------------------------------------------------------
    $(".Tooltip").click(function() {
        var $this = $(this);
        var $span = $this.children("span");
        function closeAll() {
            $(".Tooltip").children("span").removeClass("On");
            $(document).unbind("click");
        }
        if ($span.hasClass("On")) {
            closeAll();
        } else {
            closeAll();
            $span.addClass("On");
            $(document).bind("click", closeAll);
        }
        return false;
    });

    $(".ContenuOnglets:first").css("display", "block");
    $(".SwitcherOnglets:first").parent("li").addClass("On");

    $(".SwitcherOnglets").click(function() {
        $(".SwitcherOnglets").parent("li").removeClass("On");
        $(this).parent().addClass("On");
        var selectedTab = $(this).attr("href");
        $(".ContenuOnglets").css("display", "none");
        $(selectedTab).css("display", "block");
        return false;
    });

    // init ajax header box
    InitHeaderBox();

    // assign login button
    $("#AjaxLoginButton").live("click", LoginFromHeaderBox);

    $("#AjaxPasswordBox").live("keypress", function(e) {
        return AjaxLoginInputKeypress(e);
    });


    //On ajoute la culture sur chaque lien sécurisé
    $('a[href*="/secure/"]').attr('href', function() {
        var currentCulture = "fr-CA";

        if (jQuery("body").attr("id") != "lang-FR") {
            currentCulture = "en-CA";
        }

        return $(this).attr('href') + '?c=' + currentCulture;
    });
});

// ------------------------------------------------------------------------
// INPUT LABEL FOCUS
// ------------------------------------------------------------------------
function InputLabelFocus() {
    if ($(".LabelFocus").length > 0) {
        $(".LabelFocus").each(function() {
        $(this).val(jQuery(this).attr("title"));
            
            $(this).focus(function() {
                if ($(this).val().length == 0 || $(this).val() == $(this).attr("title")) {
                    $(this).val("");
                }
            });
            $(this).blur(function() {
                if ($(this).val().length == 0 || $(this).val() == $(this).attr("title")) {
                    $(this).val(jQuery(this).attr("title"));
                }
            });
        });
    }
}

function BgInputLabelFocus() {
	if ($(".BgLabelFocus").length > 0) {
       
		$(".BgLabelFocus").each(function() {
           
		    $(this).focus(function() {
			   $(this).addClass("Focus");
            });
            $(this).blur(function() {
               if($(this).val().length == 0) $(this).removeClass("Focus");
            });
        });
    }
}

function ValidatePasseCodeSecure() {
    var objs = $(".PasswordCodeSecurite");

    // Should always be 2
    if (objs.length == 2) {
        if (($("#" + objs[0].id).val() == $("#" + objs[1].id).val()) && ($("#" + objs[0].id).val() != "")) {
            return true;
        }
    }

    alert($(".ErrorCodeSecurite").val());
    return false;
}

function HideCartItem(obj) {
    $(obj).siblings().andSelf().not("label").fadeOut(250);
    $(obj).parents("tr").andSelf().fadeOut(250); // Tableaux
    $(obj).parents(".BlocRegulier.Special").andSelf().fadeOut(250); // Partenaires Panier
    return false;
}

function initDatePickers() {
    if (jQuery("body").attr("id") == "lang-FR") {
        var nomMois = ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'];
        var nomJournee = ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'];
        var nomJourneeMin = ['D', 'L', 'M', 'M', 'J', 'V', 'S'];
    }
    else {
        var nomMois = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
        var nomJournee = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
        var nomJourneeMin = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];
    }

    $(".ChampCalendrier").datepicker({
        monthNames: nomMois,
        dayNames: nomJournee,
        dayNamesMin: nomJourneeMin,
        showOtherMonths: true,
        dateFormat: 'yy-mm-dd',
        changeYear: true
    });

    $(".ChampCalendrierLimitedMaxDate").datepicker({
        monthNames: nomMois,
        dayNames: nomJournee,
        dayNamesMin: nomJourneeMin,
        showOtherMonths: true,
        dateFormat: 'yy-mm-dd',
        changeYear: true,
        maxDate: '+0d'
       

    });

    $(".ChampCalendrierLimitedMaxMinDate").datepicker({
        monthNames: nomMois,
        dayNames: nomJournee,
        dayNamesMin: nomJourneeMin,
        showOtherMonths: true,
        dateFormat: 'yy-mm-dd',
        changeYear: true,
        maxDate: '+0d',
        minDate: '-1y'

    });

    $(".Calendrier").click(function() {
        $(this).prev("span").find(".ChampCalendrier").trigger("focus");
    });

    $(".Calendrier").click(function() {
    $(this).prev("span").find(".ChampCalendrierLimitedMaxDate").trigger("focus");
});

$(".Calendrier").click(function() {
    $(this).prev("span").find(".ChampCalendrierLimitedMaxMinDate").trigger("focus");
});
}

function ShowFormError(strErrorCS) {
    var classError = "Erreur";
    var arrayError = strErrorCS.split(",");
    if (arrayError.length > 0) {
        jQuery('.' + classError).removeClass(classError); //Cleanup
        for (var i = 0; i < arrayError.length; i++) {
            jQuery('#' + arrayError[i]).addClass(classError);
        }
    }
}

function CheckForm(formName) {
    if (typeof (Page_ClientValidate) == 'function') {
        if (!Page_ClientValidate(formName)) {
            ValidateForm(formName, true, "Erreur");
            return false;
        }
    }
    return true;
}

function ValidateForm(groupName, OnlyOneErrorByField, classError) {
    var msg = new Array();
    var ctl = new Array();
    if (classError != '') jQuery('.' + classError).removeClass(classError);
    for (var i = 0; i < Page_Validators.length; i++) {
        if (Page_Validators[i].validationGroup == groupName && !Page_Validators[i].isvalid) {
            if (OnlyOneErrorByField) {
                var exist = false;
                for (var y = 0; y < ctl.length; y++) {
                    if (ctl[y] == Page_Validators[i].controltovalidate)
                        exist = true;
                }
                if (!exist) {
                    msg[msg.length] = Page_Validators[i].errormessage;
                    if (classError != '') jQuery('#' + Page_Validators[i].controltovalidate).addClass(classError);
                }
            }
            else {
                msg[msg.length] = Page_Validators[i].errormessage;
                if (classError != '') jQuery('#' + Page_Validators[i].controltovalidate).addClass(classError);
            }
            ctl[i] = Page_Validators[i].controltovalidate;
        }
    }
    return msg;
}

function equalHeight() {
	var $o = $(arguments[0]);
	$o.height( Math.max.apply(Math, $o.map(function(){ return $(this).height(); }).get()) );
}

function SwitchSearchMode(mode){
	if(mode == "more"){
	
	}
}

function ShowAdvancedMode() {
    $(".AffichageAvance").css("display", "block");
    $(".AffichageAvance").slideDown(200);
}

function ShowErrorPopup() {
    $.colorbox({ returnFocus:true, width: "390px", inline: true, href: "#PopupError" });
}

function ShowErrorPopupMain() {
    $.colorbox({ returnFocus:true,width: "390px", inline: true, href: "#PopupErrorMain" });
}


function ExpandTitleToggle(object, openText, closeText) {

    var closingAlreadyOpened = $(object).hasClass("opened");

    $("#BlocAccordeon").find("#ShowDetails").each(function(index) {
        if ($(this).hasClass("opened")) {
            $(this).removeClass("opened");
            $(this).text(openText);
        }
    });

    if (!closingAlreadyOpened)
    {
        $(object).text(closeText);
        $(object).addClass("opened");
    }
}

function open_new_window(URL) {
    NewWindow = window.open(URL, "_blank", "toolbar=no,menubar=0,status=0,copyhistory=0,scrollbars=yes,resizable=1,location=0,width=600,height=400");
    NewWindow.location = URL;
}



function ShowRemainingTime(){
	if($(".BoiteTempsRestant").length > 0){
		var boxWidth = $("#BarreActions a.Panier").width() - 2;
		var boxPadding = parseInt($("#BarreActions a.Panier").css("padding-left")) + parseInt($("#BarreActions a.Panier").css("padding-right"));
		$(".BoiteTempsRestant").css("width", boxWidth + boxPadding + "px");
	}
}


function InitHeaderBox() {
    $.ajax({
        cache: false,
        type: "POST",
        url: "/Services/CartLoginHeaderBoxService.ashx",
        data: { c: $("#BarreActions").attr("class") },
        success: function(msg) {
            $("#BarreActions").html(msg);

            $(".Compte, .FermetureConnexion").click(function() {
                if ($("#BarreActions").hasClass("On")) {
                    $("#BarreActions").removeClass("On");
                    $("#BarreActions").css("height", "32px");
                }
                else {
                    $("#BarreActions").addClass("On");
                    $("#BarreActions").css("height", "65px");
                }
                return false;
            });
        }
    });
}

function CallAgainUpdateCart() {
    $.ajax({
        cache: false,
        type: "POST",
        
        url: "/Presentation/Templates/PanierInscriptionActivite.aspx/ButtonClickHandlerMethod",
        data: "{}", 
        success: function(msg) {
            }  });
        }
   



function LoginFromHeaderBox() {
    $.ajax({
        cache: false,
        type: "POST",
        url: "/Services/ValidateUserCredentials.ashx",
        dataType: "json",
        data: { l: $("#AjaxLoginBox").val(), p: $("#AjaxPasswordBox").val(), c: $("#AjaxCulture").val() },
        success: function(data) {
            if (data.IsValid) {
                window.location = data.RedirectUrl;
            }
            else {
                alert(data.ErrorMessage);
            }
        }
    });
}

function MaxLength(obj, mlength) {
    if (obj.getAttribute) {
        if (obj.value.length > mlength) {
            obj.value = obj.value.substring(0, mlength)
        }
    }
}

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 (validationGroup != null) {
            if (Page_ClientValidate(validationGroup)) {
                __doPostBack(btnID, '');
            }
        }
        else {
            __doPostBack(btnID, '');
        }
        return false;
    }
    return true;
}

function AjaxLoginInputKeypress(e) {

    if (e.which == 13) {
        return LoginFromHeaderBox();
    }

}

function removeFlash() {
	$("#VideoPlayerAccueil").remove();
}

