/*----------------------------------------------------------------------------//
// Javascript pour le site client  -------------------------------------------//
//----------------------------------------------------------------------------//
// Client : -
// Note   : -
// Date   : -
//----------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------*/
// 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/js/base.js");
//importJavascript("/includes/js/plugins/jquery.timer.js");

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

var rotatorAction = 0;
var selectedPromo = "";
var selectedSurvey6_1;

jQuery(document).ready(function() {

    IsCookieEnabled();
    jQuery("table.Tableau tr:last td").css("border-bottom-color", "#FFF");
    jQuery("#Contenu .ActivitePanier:last").css("margin-bottom", "40px");
	
	// -----------------------------------------------------------------------------------------------------------------
    // Onglets à l'accueil -------------------------------------------------------------------------------------------------
    // -----------------------------------------------------------------------------------------------------------------
	jQuery("p.Promo").css("display", "none");
	jQuery("p.Promo:first").css("display", "block" );
	jQuery("a.Onglet:first").addClass("On");
	selectedPromo = "#" + jQuery("p.Promo:first").attr("id");
	
	jQuery("a.Onglet").click(function(){
		jQuery("a.Onglet").removeClass("On");
		jQuery(this).addClass("On");
		var promo = jQuery(this).attr("href");
		if(promo != selectedPromo) {
			jQuery(selectedPromo).stop("true", "true").fadeOut(150, function(){
				jQuery(promo).stop("true", "true").fadeIn(300);
				selectedPromo = promo;
			});
		}
		else{
			selectedPromo = promo;
		}
		return false;
	});

    // -----------------------------------------------------------------------------------------------------------------
    // Taille du texte -------------------------------------------------------------------------------------------------
    // -----------------------------------------------------------------------------------------------------------------
    jQuery("a.TailleTexte.Petit").addClass("On");
    jQuery("a.TailleTexte.Petit").click(function() { jQuery("body").css("font-size", "62.6%"); SetSelectedSize(jQuery(this)); return false; });
    jQuery("a.TailleTexte.Moyen").click(function() { jQuery("body").css("font-size", "68.9%"); SetSelectedSize(jQuery(this)); return false; });
    jQuery("a.TailleTexte.Grand").click(function() { jQuery("body").css("font-size", "75.1%"); SetSelectedSize(jQuery(this)); return false; });

    // -----------------------------------------------------------------------------------------------------------------
    // Input label focus -----------------------------------------------------------------------------------------------
    // -----------------------------------------------------------------------------------------------------------------
    if (jQuery(".LabelFocus").length > 0) {
        jQuery(".LabelFocus").each(function() {
            jQuery(this).focus(function() {
                if (jQuery(this).val().length == 0 || jQuery(this).val() == jQuery(this).attr("title")) {
                    jQuery(this).val("");
                }
            });
            jQuery(this).blur(function() {
                if (jQuery(this).val().length == 0 || jQuery(this).val() == jQuery(this).attr("title")) {
                    jQuery(this).val(jQuery(this).attr("title"));
                }
            });
        });
    }

    // -----------------------------------------------------------------------------------------------------------------
    // Menu déroulant pour filtrer la recherche ------------------------------------------------------------------------
    // -----------------------------------------------------------------------------------------------------------------
    jQuery(".FiltreRecherche a.Trigger").click(function() {
        jQuery(".FiltreRecherche ul").toggleClass("Ouvert");
        jQuery(document).bind("click", function() {
            jQuery(".FiltreRecherche ul").removeClass("Ouvert");
            jQuery(this).unbind("click");
        });
        return false;
    });

    jQuery(".FiltreRecherche ul li a").click(function() {
        jQuery(".FiltreRecherche .TriRecherche").val(jQuery(this).attr("rel"));
        jQuery(".FiltreRecherche a.Trigger").text(jQuery(this).text());
        jQuery(this).parents("ul").removeClass("Ouvert");
        return false;
    });


    // -----------------------------------------------------------------------------------------------------------------
    // Rotator à l'accueil ---------------------------------------------------------------------------------------------
    // -----------------------------------------------------------------------------------------------------------------
    if (jQuery("#Rotator").length == 1) {
        //jQuery("#Rotator .RotatorItem").css({ opacity: 0.0 });
        jQuery("#Rotator .RotatorItem:first").css("display", "block");
        jQuery("ul#Temoins li:first").addClass("On");
        var totalRotatorItems = 0;
        var cpt = 1;

        jQuery("#Rotator .RotatorItem").each(function() {
            totalRotatorItems++;
        });

        // Compteur pour faire défiler les images
        jQuery.timer({ name: "Compteur", interval: 5 }, function() {
            cpt++;
            resetTemoin();
            jQuery("#Rotator .RotatorItem[@id=Item" + cpt + "]").stop().fadeIn(300);
            jQuery("ul#Temoins li[@id=Temoin" + cpt + "]").addClass("On");

            if (cpt > totalRotatorItems) {
                cpt = 1;
                jQuery("#Rotator .RotatorItem").stop().fadeOut(300);
                jQuery("#Rotator .RotatorItem:first").stop().fadeIn(300);
                jQuery("ul#Temoins li:first").addClass("On");
            }

        })

        // Contrôle des images avec clic sur les flèches
        jQuery(".BtRotatorSuivant").click(function() {
            if (rotatorAction == 0) {
                jQuery(jQuery.stopTimer("Compteur"));
                rotatorAction = 1;
                if (cpt + 1 > totalRotatorItems) {
                    resetRotatorItems();
                    resetTemoin();
                    cpt = 0;
                }
                jQuery("#Rotator .RotatorItem[@id=Item" + (cpt) + "]").stop().fadeOut(300);
                resetTemoin();

                jQuery("#Rotator .RotatorItem[@id=Item" + (cpt + 1) + "]").stop().fadeIn(300, function() {
                    cpt++;
                    rotatorAction = 0;
                });
                jQuery("ul#Temoins li[@id=Temoin" + (cpt + 1) + "]").addClass("On");
            }
        });

        jQuery(".BtRotatorPrecedent").click(function() {
            jQuery(jQuery.stopTimer("Compteur"));
            if (rotatorAction == 0) {
                rotatorAction = 1;
                if (cpt - 1 < 1) {
                    resetRotatorItems();
                    resetTemoin();
                    cpt = totalRotatorItems + 1;
                }
                jQuery("#Rotator .RotatorItem[@id=Item" + (cpt) + "]").stop().fadeOut(300);
                resetTemoin();

                jQuery("#Rotator .RotatorItem[@id=Item" + (cpt - 1) + "]").stop().fadeIn(300, function() {
                    cpt--;
                    rotatorAction = 0;
                });
                jQuery("ul#Temoins li[@id=Temoin" + (cpt - 1) + "]").addClass("On");
            }
        });
    }

    jQuery(".FormationOui").click(function() {
        selectedSurvey6_1 = "yes";
        jQuery(".ChoixSupplementaires").css("display", "inline-block");
        jQuery(".QuestionsFacultatives").slideDown(200, function() {
            jQuery(".DerniereQuestion").css("display", "none");
        });
    });
    jQuery(".FormationNon").click(function() {
        selectedSurvey6_1 = "no";
        jQuery(".ChoixSupplementaires").css("display", "none");
        jQuery(".QuestionsFacultatives").slideUp(200, function() {
            jQuery(".DerniereQuestion").slideDown(200);
        });
    });

    /*jQuery(".HiddenTextBox").click(function(){
    jQuery(this).next(".Toggle").css("display","block");										
    });*/

});

// -----------------------------------------------------------------------------------------------------------------
// Fonctions -------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------

function SetSelectedSize(size){
	jQuery("a.TailleTexte").removeClass("On");
	jQuery(size).addClass("On");
}
function resetRotatorItems(){
	jQuery("#Rotator .RotatorItem").each(function(){
		jQuery(this).stop().fadeOut(300);
	});
}
function resetTemoin(){
	jQuery("ul#Temoins li").each(function(){
		jQuery(this).removeClass("On")
	});
}

function ReplaceLeadership(s) {
    return s.replace(/(?!<em>)Leadership SST(?!<\/em>)/gi, "<em>Leadership SST</em>");
}

/* - Fonction : Validation des champs de formulaire - */
function ValidateForm(groupName, OnlyOneErrorByField, classError) {
    var msg = new Array();
    var ctl = new Array();

    if (classError != '') jQuery('.' + classError).removeClass(classError);

    //Ne pas oublier d'appliquer "Page_ClientValidate()" avant d'appeler cette procédure
    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 IsPhoneNumber(sText) {
    return sText.match(/^\d{10}$/i);
}

function IsNumeric(sText, bAcceptSpace) {

    var ValidChars = "0123456789";
    var IsNumber = true;
    var Char;

    if (!bAcceptSpace && sText.length == 0)
        return false;
    
    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }
    return IsNumber;
}
function IsPostalCode(sPostalCode) {
    return sPostalCode.match(/^\s*[a-ceghj-npr-tvxy]\d[a-z](\s)?\d[a-z]\d\s*$/i);
}


var firstInvalidElement = null;

function CheckValidators() {
    var isValid = true;
 
    firstInvalidElement = null;

    $(".RadioBtn").each(function() {
    if (!$(this).hasClass("Optional")) {
        isValid = ValidationRadioButton($(this)) && isValid;
        }
    });

    $(".CheckBoxValidator").each(function() {
    isValid = ValidationCheckbox($(this)) && isValid;
    });



    var isQ3_2Invalid;
    $(".Q3_2_1").each(function() {
        isQ3_2Invalid = !ValidationCheckbox($(this));
    });
    
    if (isQ3_2Invalid) {
        $(".Q3_2_2").each(function() {
            isQ3_2Invalid = !ValidationCheckbox($(this));
        });
    }

    if (isQ3_2Invalid) {
        $(".Q3_2_3").each(function() {
            isQ3_2Invalid = !ValidationCheckbox($(this));
        });
    }

    if (isQ3_2Invalid) {
        $(".Q3_2_4").each(function() {
            isQ3_2Invalid = !ValidationCheckbox($(this));
        });
    }

    if (isQ3_2Invalid) {
        $(".Q3_2_5").each(function() {
            isQ3_2Invalid = !ValidationCheckbox($(this));
        });
    }
    isValid = !isQ3_2Invalid && isValid;    

    isValid = ValidationOtherTextbox("DefisSST7") && isValid;
    isValid = ValidationOtherTextbox("BesoinsPrioritaires15") && isValid;
    isValid = ValidationOtherTextbox("FournisseursServices6") && isValid;
    isValid = ValidationOtherTextbox("LieuActivites4") && isValid;
    isValid = ValidationOtherTextbox("FormationPasUtilisee") && isValid;

    if (selectedSurvey6_1 == 'yes') {

        $(".CheckBoxValidator6_2").each(function() {
            isValid = ValidationCheckbox($(this)) && isValid;            
        });
    
        $(".RadioBtn").each(function() {
            if ($(this).hasClass("Optional")) {
                isValid = ValidationRadioButton($(this)) && isValid;
            }
        });
    }
    else {
        $(".CheckBoxValidator6_5").each(function() {
            isValid = ValidationCheckbox($(this)) && isValid;
        });
    }
   

    if (!isValid) {
        $(".MessageErreurs").css("display", "block");
    }
      
    if (firstInvalidElement != null)
        firstInvalidElement.focus();
    return isValid;
}


function ValidationRadioButton(currentControl) {
    var isValid = true;

    currentControl.parent(".QuestionReponse").removeClass("Error");
    if (currentControl.find("input:checked").length < 1) {
        currentControl.parent(".QuestionReponse").addClass("Error");
        isValid = false;
        if (firstInvalidElement == null)
            firstInvalidElement = currentControl;
    }

    return isValid;
}


function ValidationCheckbox(currentControl) {
    var isValid = true;
    
    currentControl.parent(".QuestionReponse").removeClass("Error");
    if (currentControl.find("input:checked").length < 1) {
        currentControl.parent(".QuestionReponse").addClass("Error");
        isValid = false;
        if (firstInvalidElement == null)
            firstInvalidElement = currentControl;
    }

    return isValid;
}

function ValidationOtherTextbox(controlNamePrefix) {
    var isValid = true;    
    var textBox = $("." + controlNamePrefix + "Txt");
    var checkBox = $("." + controlNamePrefix + "Cbx");

    textBox.removeClass("Erreur");

    if (checkBox.find("input:checked").length == 1 && textBox.val().length == 0) {
        isValid = false;
        textBox.addClass("Erreur");
        if (firstInvalidElement == null)
            firstInvalidElement = textBox;
    }

    return isValid;
}
function IsCookieEnabled() {
    Set_Cookie('test', 'none', '', '/', '', '');
    if (Get_Cookie('test')) {
        cookie_set = true;
        Delete_Cookie('test', '/', '');
    } else {
        cookie_set = false;
		showCookieWarning();
    }
}
function Get_Cookie(check_name) {
    var a_all_cookies = document.cookie.split(';');
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false;
    var i = '';

    for (i = 0; i < a_all_cookies.length; i++) {
        a_temp_cookie = a_all_cookies[i].split('=');
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
        if (cookie_name == check_name) {
            b_cookie_found = true;
            if (a_temp_cookie.length > 1) {
                cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
            }
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if (!b_cookie_found) {
        return null;
    }
}

function Set_Cookie(name, value, expires, path, domain, secure) {
    var today = new Date();
    today.setTime(today.getTime());
    if (expires) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date(today.getTime() + (expires));
    document.cookie = name + "=" + escape(value) +
		((expires) ? ";expires=" + expires_date.toGMTString() : "") + 
		((path) ? ";path=" + path : "") +
		((domain) ? ";domain=" + domain : "") +
		((secure) ? ";secure" : "");
}
function Delete_Cookie(name, path, domain) {
    if (Get_Cookie(name)) document.cookie = name + "=" +
			((path) ? ";path=" + path : "") +
			((domain) ? ";domain=" + domain : "") +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
function showCookieWarning(){
	//jQuery("p#AvertissementCookie").css("display", "block");
	jQuery("a.Disabled").attr("href", "javascript:void(0);");
	jQuery("a.Disabled").attr("title", "Inscription impossible. Veuillez d’abord activer l’option Cookies de votre navigateur.");
	jQuery("a.Disabled").css("cursor", "default");
	jQuery("a.Disabled").css("background", "#C9CECC");
	jQuery("a.Disabled").css("color", "#a9a9a9");
	jQuery("a.Disabled").children("span").css("background", "none");
}
