var fondDiv = false;
var dataDiv = false;

// chargement de la page
jQuery(document).ready(function(){
    afficheSousMenu();
    textInputConnexion();
    setForm(myClass);
    initTipsCompte()
});

// Tool tip lien encart compte

function initTipsCompte(){
    jQuery('#bloc-compte a[tip]').each(function(){
        jQuery(this).qtip({
            content: jQuery(this).attr('tip'), // Use the tooltip attribute of the element for the content
            position: {
                corner: {
                    target: 'bottomMiddle',
                    tooltip: 'topMiddle'
                }
            },
            style: {
                background: "url('/styles/images/compte/tool-tip-compte.png')",
                width: 140,
                height: 52,
                border: 0,
                'padding-top': 20,
                'font-size': 12,
                color: '#e2e1d7'
            }
        });
    });
}


function createTips(param) {
	  jQuery('#'+param).qtip({
            content: jQuery('#'+param).attr('tip'), // Use the tooltip attribute of the element for the content
            position: {
                corner: {
                    target: 'bottomMiddle',
                    tooltip: 'topMiddle'
                }
            },
            style: {
                background: "url('/styles/images/compte/tool-tip-compte.png')",
                width: 140,
                height: 52,
                border: 0,
                'padding-top': 20,
                'font-size': 12,
                color: '#e2e1d7'
            }
        });
}

function createTipsNewsletter(param) {
	  jQuery('#'+param).qtip({
            content: jQuery('#'+param).attr('tip'), // Use the tooltip attribute of the element for the content
            position: {
                corner: {
                    target: 'bottom',
                    tooltip: ''
                }
            },
            style: {
                background: "url('/styles/images/compte/tool-tip-compte.png')",
                width: 140,
                height: 52,
                border: 0,
                'padding-top': 20,
                'font-size': 12,
                color: '#e2e1d7'
            }
        });
}

// copie presse papier
function copyToClipboardIE(sText){
    // Le contenu actuel du presse-papier sera écrasé par la valeur de sText.
    window.clipboardData.setData('Text', sText);
    // On ne veut pas suivre le lien après le clic.
    return false;
}

function copyToClipboardFF(sText){
    try {
        // On test si la configuration permet l'accès au presse-papier.
        netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
    } 
    catch (e) {
        alert("Impossible d'accéder au presse-papier.");
    }
    // Initialisation du composant fournit par Mozilla.
    var gClipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);
    // Copie du texte dans le presse papier.
    gClipboardHelper.copyString(sText);
    // On ne veut pas suivre le lien après le clic.
    return false;
}

function copyToClipboard(sText){
    // Cas où on a accès à l'objet clipboardData.
    if (window.clipboardData) {
        return copyToClipboardIE(sText);
    }
    // Cas où on peut tester la configuration de Firefox sur
    else 
        if (typeof(netscape) == 'object' && typeof(Components) == 'object') {
            return copyToClipboardFF(sText);
        }
        else {
            alert("Cette fonctionnalité n'est pas disponible pour votre navigateur.");
        }
    return false;
}

//-- copie presse papier

//-- Tool tip lien encart compte

// Remplacement select
function selectReplacement(obj){
    // append a class to the select
    obj.className += ' replaced';
    // create list for styling
    var ul = document.createElement('ul');
    ul.className = 'selectReplacement';
    var opts = obj.options;
    for (var i = 0; i < opts.length; i++) {
        var selectedOpt;
        if (opts[i].selected) {
            selectedOpt = i;
            break;
        }
        else {
            selectedOpt = 0;
        }
    }
    for (var i = 0; i < opts.length; i++) {
        var li = document.createElement('li');
        var txt = document.createTextNode(opts[i].text);
        li.appendChild(txt);
        li.selIndex = opts[i].index;
        li.selectID = obj.id;
        li.onclick = function(){
            selectMe(this);
        }
        if (i == selectedOpt) {
            li.className = 'selected';
            li.onclick = function(){
                this.parentNode.className += ' selectOpen';
                this.onclick = function(){
                    selectMe(this);
                }
            }
        }
        if (window.attachEvent) {
            li.onmouseover = function(){
                this.className += ' hover';
            }
            li.onmouseout = function(){
                this.className = this.className.replace(new RegExp(" hover\\b"), '');
            }
        }
        ul.appendChild(li);
    }
    // add the input and the ul
    obj.parentNode.appendChild(ul);
}

function selectMe(obj){
    var lis = obj.parentNode.getElementsByTagName('li');
    for (var i = 0; i < lis.length; i++) {
        if (lis[i] != obj) { // not the selected list item
            lis[i].className = '';
            lis[i].onclick = function(){
                selectMe(this);
            }
        }
        else {
            setVal(obj.selectID, obj.selIndex);
            obj.className = 'selected';
            obj.parentNode.className = obj.parentNode.className.replace(new RegExp(" selectOpen\\b"), '');
            obj.onclick = function(){
                obj.parentNode.className += ' selectOpen';
                this.onclick = function(){
                    selectMe(this);
                }
            }
        }
    }
}

function setVal(objID, selIndex){
    var obj = document.getElementById(objID);
    obj.selectedIndex = selIndex;
    
    // Cas select pour la recherche
    if (obj.className == 'select-recherche replaced') {
        var data = buildDataAJAX(obj.className);
        jQuery.ajax({
            type: "POST",
            url: "/js/ajax/recherche.php",
            data: data,
            success: function(html){
                jQuery("#list-select").html(html);
                setForm('select-recherche');
            }
        });
    }
    //-- Cas select pour la recherche
    
    // Cas select pour le previsionnel
    if (obj.className == 'select-previsionnel replaced') {
        document.forms['compte_previsionnel'].submit();
    }
    //-- Cas select pour le previsionnel
    
    // Cas pour la gestion des visite
    if (obj.className == 'select-niveau-acces replaced') {
        document.forms['form_niveau_acces'].submit();
    }
    //-- Cas pour la gestion des visite
    
    // Cas pour les adresses livraison
    if (obj.className == 'select-adresse-livraison replaced') {
        location.href = '/mon-compte/livraison-adresse.html?adresse_id=' + obj.value;
    }
    //-- Cas pour les adresses livraison
    
    // Cas pour les adresses compte
    if (obj.className == 'select-adresse-compte replaced') {
        location.href = '/mon-compte/mes-adresses.html?adresse_id=' + obj.value;
    }
    //-- Cas pour les adresses compte

}

function setForm(className){
    var s = new Array();
    if (className != null && className.length > 0) {
        if (document.getElementsByClassName) {
            s = document.getElementsByClassName(className);
        }
        else { //cas special IE car n'implemente pas la fonction getElementsByClassName
            elm = document.getElementsByTagName('select');
            for (var i = 0; i < elm.length; i++) {
                if (elm[i].className == className) {
                    s.push(elm[i]);
                }
            }
        }
    }
    else {
        s = document.getElementsByTagName('select');
    }
    
    for (var i = 0; i < s.length; i++) {
        selectReplacement(s[i]);
    }
}

function closeSel(obj){
    // close the ul
}

function buildDataAJAX(className){
    var s = new Array();
    var data = '';
    
    if (document.getElementsByClassName) {
        s = document.getElementsByClassName(className); //récupération des select
    }
    else { //cas spe IE
        elm = document.getElementsByTagName('select');
        for (var i = 0; i < elm.length; i++) {
            if (elm[i].className == className) {
                //alert('cas IE');
                s.push(elm[i]);
            }
        }
    }
    for (var i = 0; i < s.length; i++) { //on boucle dessus
        data += s[i].id + "="; //recup chaque identifiant de select
        var opts = s[i].options; //on recup les options du select
        for (var j = 0; j < opts.length; j++) { //on boucle dessus pr savoir laquelle est selectionner
            var selectedOpt;
            if (opts[j].selected) {
                data += opts[j].value + "&"; //on la concatene dans la chaine pr la requete AJAX
                break;
            }
        }
    }
    return data;
}

//-- remplacement select

function initCave(){
    jQuery("#fleche-gauche").click(function(){
        jQuery(this).unbind('click');
        slideCave('+');
    });
    jQuery("#fleche-droite").click(function(){
        jQuery(this).unbind('click');
        slideCave('-');
    });
}

function slideCave(direction){

    var decContenu = 200;
    var decHeader = 100;
    var duree = 1000;
    var zoneCave = 693;
    var mlTemp = jQuery("#contenu-cave").css('margin-left');
    var ml = mlTemp.substring(0, mlTemp.indexOf('px'));
    
    var nextMl = Math.abs(eval(ml + direction + decContenu)); //calcul de la valeur du prochain margin left
    var widthTemp = jQuery("#contenu-cave").css('width');
    var width = widthTemp.substring(0, widthTemp.indexOf('px'));
    
    if ((ml == 0 && direction == '+') || ((nextMl + zoneCave) >= width && direction == '-')) {
        decContenu = 0;
        decHeader = 0;
    }
    
    jQuery("#contenu-cave").animate({
        marginLeft: direction + '=' + decContenu + 'px'
    }, duree, function(){
        initCave();
    })
    
    jQuery("#entete-cave").animate({
        marginLeft: direction + '=' + decHeader + 'px'
    }, duree)
    
}

function genereToolTip(id, x, y, sortie){
	jQuery.ajax({
        type: "GET",
        url: "/js/ajax/tool_tip_bouteille.php",
        data: "commande_produit_id=" + id + "&sortie=" + sortie,
        success: function(msg){
            //alert(msg);
            dataDiv = document.createElement('div');
            dataDiv.style.position = 'absolute';
            dataDiv.style.left = x + "px";
            dataDiv.style.top = y + "px";
            dataDiv.innerHTML = msg;
            dataDiv.id = 'produit_bouteille_' + id;
            dataDiv.className = 'tool-tip-bottle';
            dataDiv.style.display = 'none';
            document.body.appendChild(dataDiv);
            jQuery(dataDiv).fadeIn('fast');
        }
    });
}

function initToolTip(sortie){
    jQuery("#contenu-cave .bouteille[rel]").each(function(){
        if (jQuery(this).attr('rel') != '') {
            var dataDiv = '';
            var id = jQuery(this).attr('rel');
            jQuery(this).hover(function(event){
                // on cache toutes les autres tool tip
                jQuery(".tool-tip-bottle").each(function(){
                    jQuery(this).css('display', 'none');
                });
                
                jQuery(this).css('cursor', 'pointer');
                
                var x = event.pageX + 10;
                var y = event.pageY + 10;
                
                //si la tooltip pr le produit nexiste pas, on la crée
                if (!jQuery("#produit_bouteille_" + id).attr('id')) {
                    idTimeout = setTimeout(function(){
                        genereToolTip(id, x, y, sortie)
                    }, 300);
                }
                else {
                    jQuery("#produit_bouteille_" + id).css("left", x);
                    jQuery("#produit_bouteille_" + id).css("top", y);
                    idTimeout = setTimeout(function(){
                        jQuery("#produit_bouteille_" + id).fadeIn('fast');
                    }, 500);
                }
            }, function(){
                clearTimeout(idTimeout);
                jQuery("#produit_bouteille_" + id).fadeOut('fast');
                
                idTime = setTimeout(function(){
                    jQuery(".tool-tip-bottle").each(function(){
                        jQuery(this).css('display', 'none');
                    });
                }, 500);
                clearTimeout(idTime);
            });
        }
    });
}

function initToolTipSortie(sortie){
	
	jQuery("#contenu-cave .bouteille[rel]").each(function(){
        if (jQuery(this).attr('rel') != '') {
            var dataDiv = '';
            var id = jQuery(this).attr('rel');
            
            jQuery(this).hover(function(event){
                jQuery(this).css('cursor', 'pointer');
            });
            
            jQuery(this).click(function(event){
                jQuery("body").click(function(event){
				    // on cache toutes les autres tool tip
				    jQuery(".tool-tip-bottle").each(function(){
				        jQuery(this).css('display', 'none');
				    });
				});
                
                var x = event.pageX + 5;
                var y = event.pageY + 5;
				
				genereToolTip(id, x, y, sortie);
            });
        }
    });
	
}

//-- Ma Cave

// recherche

/*
 function search(){
 jQuery("#recherche select").change(function(){
 var data = '';
 jQuery("#recherche select").each(function(){
 //alert(jQuery(this).attr('id'));
 data += jQuery(this).attr('id') + '=' + jQuery(this).attr('value') + '&';
 });
 
 jQuery.ajax({
 type: "POST",
 url: "/js/ajax/recherche.php",
 data: data,
 success: function(html){
 jQuery("#list-select").html(html);
 search();
 }
 });
 
 });
 }
 */
//-- recherche

// menu et sous menu
function afficheSousMenu(){
    jQuery("#menu-principal a").each(function(i){
    
        jQuery(this).hover(function(event){
            jQuery("#menu-principal a").each(function(i){
                jQuery(this).removeClass('hover');
            });
            jQuery(this).addClass('hover');
            
            jQuery("#sous-menu .sous-menu-categorie").each(function(i){
                jQuery(this).css('display', 'none');
            });
            var id = jQuery(this).attr("id");
            jQuery("#sous-" + id).css('display', 'block');
        });
    });
}

function alterneText(id, text){
    jQuery(id).focus(function(){
        if (jQuery(this).attr('value') == text) {
            jQuery(this).attr('value', '');
        }
    });
    jQuery(id).blur(function(){
        if (jQuery(this).attr('value') == '') {
            jQuery(this).attr('value', text);
        }
    });
}

function textInputConnexion(){
    alterneText("#client_email", 'Votre email ici');
    alterneText("#client_password", 'Mot de passe');
    
    alterneText("#client_email_login", 'Votre email ici');
    alterneText("#client_password_login", 'Mot de passe');
}

// edition adresse panier paiement
function editAdresse(){
    jQuery("#lien-modif-adresse").click(function(){
        jQuery("#info-adresse").addClass("hidden");
        jQuery("#form-adresse").removeClass("hidden");
    });
}

var fondDiv = false;
var dataDiv = false;

function addFriend(idForm){
    if (!fondDiv) {
        fondDiv = document.createElement('div');
        fondDiv.style.position = 'absolute';
        document.body.appendChild(fondDiv);
    }
    fondDiv.innerHTML = '';
    
    $(fondDiv).setStyles({
        backgroundColor: '#000000',
        width: '100%',
        height: getScrollHeight(),
        position: 'absolute',
        opacity: '0.5',
        overflow: 'hidden',
        top: '0px',
        zIndex: '1500',
        visibility: 'hidden'
    });
    
    if (!dataDiv) {
        dataDiv = document.createElement('div');
        dataDiv.style.position = 'absolute';
        document.body.appendChild(dataDiv);
    }
    
    $(dataDiv).setStyles({
        background: '#FFFFFF url(/styles/images/popup/fond-popup-moyen.png) no-repeat top left',
        width: '503px',
        height: '550px',
        position: 'absolute',
        // border: '1px solid #7f7f7f',
        top: '50%',
        left: '50%',
        marginLeft: '-249px',
        marginTop: (getScrollTop() - 279) + 'px',
        zIndex: '1600',
        visibility: 'hidden'
    });
    
    $(fondDiv).onclick = function(){
        removeDiv();
    }
    
    new Ajax('/js/ajax/addFriendCave.php', {
        method: 'post',
        update: dataDiv,
        data: $(idForm).toQueryString(),
        onSuccess: function(req){
        
            $$(fondDiv).setStyles({
                visibility: 'visible'
            });
            $$('select').setStyles({
                visibility: 'hidden'
            });
            $$(dataDiv).setStyles({
                visibility: 'visible'
            });
        },
        evalScripts: true
    }).request();
    
}

// avis
function displayAvis(){
	$$("#img_note li").each(function(element){	  
		element.addEvents({
			'mouseenter': function(){
				var chaine=element.id;
				var pos=chaine.length-1;
				var num=chaine.substr(pos,1);
				for(i=1;i<=num;i++){
					$('img_note_'+i).addClass('active');
				}
				/*$('notation_defaut').setStyle('display', 'none');
				$('notation_nom').setStyle('display', 'block');
				$('notation_nom').innerHTML=$('txt_note_'+num).value;*/
			},
			'click': function(){
				for(i=1;i<=5;i++){
					$('img_note_'+i).removeClass('active_click');
				}
				
				var chaine=element.id;
				var pos=chaine.length-1;
				var num=chaine.substr(pos,1);
				for(i=1;i<=num;i++){
					$('img_note_'+i).addClass('active_click');
				}
				$('notation_id').value=num;
				// $('notation_nom_nom').value=$('notation_nom').innerHTML;
			},
			'mouseleave': function(){
				for(i=1;i<=5;i++){
					$('img_note_'+i).removeClass('active');
				}
				/*if($('notation_id').value==0){
					$('notation_nom').setStyle('display', 'none');
					$('notation_defaut').setStyle('display', 'block');
				}else{
					$('notation_nom').innerHTML=$('notation_nom_nom').value;
				}*/
			}
		});
	}); 
}

function initAvis(id){
	for(i=1;i<=id;i++){
		$('img_note_'+i).addClass('active');
	}
	/*$('notation_defaut').setStyle('display', 'none');
	$('notation_nom').setStyle('display', 'block');
	$('notation_nom').innerHTML=$('txt_note_'+id).value;*/
}
//-- avis
//--------------------------------------------
var fondDiv = false;
var dataDiv = false;
// Ajout au panier
function addPanier(idForm){
    if (!fondDiv) {
        fondDiv = document.createElement('div');
        fondDiv.style.position = 'absolute';
        document.body.appendChild(fondDiv);
    }
    fondDiv.innerHTML = '';
    
    $(fondDiv).setStyles({
        backgroundColor: '#000000',
        width: '100%',
        height: getScrollHeight(),
        position: 'absolute',
        opacity: '0.5',
        overflow: 'hidden',
        top: '0px',
        zIndex: '1500',
        visibility: 'hidden'
    });
    
    if (!dataDiv) {
        dataDiv = document.createElement('div');
        dataDiv.style.position = 'absolute';
        document.body.appendChild(dataDiv);
    }
    
    $(dataDiv).setStyles({
        background: '#FFFFFF url(/styles/images/popup/fond-popup.png) no-repeat top left',
        width: '503px',
        height: '309px',
        position: 'absolute',
        // border: '1px solid #7f7f7f',
        top: '50%',
        left: '50%',
        marginLeft: '-249px',
        marginTop: (getScrollTop() - 199) + 'px',
        zIndex: '1600',
        visibility: 'hidden'
    });
    
    $(fondDiv).onclick = function(){
        removeDiv();
    }
    
    new Ajax('/js/ajax/panier-change.php', {
        method: 'post',
        update: dataDiv,
        data: $(idForm).toQueryString(),
        onSuccess: function(req){
        
            $$(fondDiv).setStyles({
                visibility: 'visible'
            });
            $$('select').setStyles({
                visibility: 'hidden'
            });
            $$(dataDiv).setStyles({
                visibility: 'visible'
            });
            
            new Ajax('/js/ajax/updatePanier.php', {
                update: $('panier')
            }).request();
        },
        evalScripts: true
    }).request();
    
}

function delPanier(idForm){
    new Ajax('/js/ajax/updatePanier.php', {
        update: $('panier'),
        method: 'post',
        data: $(idForm).toQueryString()
    }).request();
}

// Ajout WishList
function addWishlist(produit_id, client_id){
    if (!fondDiv) {
        fondDiv = document.createElement('div');
        fondDiv.style.position = 'absolute';
        document.body.appendChild(fondDiv);
    }
    fondDiv.innerHTML = '';
    //alert(getHeight());
    
    $(fondDiv).setStyles({
        backgroundColor: '#000000',
        width: '100%',
        height: getScrollHeight(),
        position: 'absolute',
        opacity: '0.5',
        overflow: 'hidden',
        top: '0px',
        zIndex: '1500',
        visibility: 'hidden'
    });
    
    if (!dataDiv) {
        dataDiv = document.createElement('div');
        dataDiv.style.position = 'absolute';
        document.body.appendChild(dataDiv);
    }
    
    $(dataDiv).setStyles({
        background: '#FFFFFF url(/styles/images/popup/fond-popup.png) no-repeat top left',
        width: '503px',
        height: '309px',
        position: 'absolute',
        // border: '1px solid #7f7f7f',
        top: '50%',
        left: '50%',
        marginLeft: '-249px',
        marginTop: (getScrollTop() - 199) + 'px',
        zIndex: '1600',
        visibility: 'hidden'
    });
    
    $(fondDiv).onclick = function(){
        removeDiv();
    }
    
    new Ajax('/js/ajax/addwishlist.php', {
        method: 'post',
        update: dataDiv,
        data: "produit_id=" + produit_id + "&client_id=" + client_id,
        onSuccess: function(req){
            $$(fondDiv).setStyles({
                visibility: 'visible'
            });
            $$('select').setStyles({
                visibility: 'hidden'
            });
            $$(dataDiv).setStyles({
                visibility: 'visible'
            });
        },
        evalScripts: true
    }).request();
}

//-- Ajout WishList

// Ajout a la newsletter
function addNewsletter(idForm){

    if (!fondDiv) {
        fondDiv = document.createElement('div');
        fondDiv.style.position = 'absolute';
        document.body.appendChild(fondDiv);
    }
    fondDiv.innerHTML = '';
    //alert(getHeight());
    
    $(fondDiv).setStyles({
        backgroundColor: '#000000',
        width: '100%',
        height: getScrollHeight(),
        position: 'absolute',
        opacity: '0.5',
        overflow: 'hidden',
        top: '0px',
        zIndex: '1500',
        visibility: 'hidden'
    });
    
    if (!dataDiv) {
        dataDiv = document.createElement('div');
        dataDiv.style.position = 'absolute';
        document.body.appendChild(dataDiv);
    }
    
    $(dataDiv).setStyles({
        background: '#FFFFFF url(/styles/images/popup/fond-popup.png) no-repeat top left',
        width: '503px',
        height: '309px',
        position: 'absolute',
        // border: '1px solid #7f7f7f',
        top: '50%',
        left: '50%',
        marginLeft: '-249px',
        marginTop: (getScrollTop() - 199) + 'px',
        zIndex: '1600',
        visibility: 'hidden'
    });
    
    $(fondDiv).onclick = function(){
        removeDiv();
    }
    
    new Ajax('/js/ajax/addNewsletter.php', {
        update: dataDiv,
        data: $(idForm).toQueryString(),
        onSuccess: function(req){
        
            $$(fondDiv).setStyles({
                visibility: 'visible'
            });
            $$('select').setStyles({
                visibility: 'hidden'
            });
            $$(dataDiv).setStyles({
                visibility: 'visible'
            });
        },
        evalScripts: true
    }).request();
}

function popupCms(cms_id){
    if (!fondDiv) {
        fondDiv = document.createElement('div');
        fondDiv.style.position = 'absolute';
        document.body.appendChild(fondDiv);
    }
    fondDiv.innerHTML = '';
    
    $(fondDiv).setStyles({
        backgroundColor: '#000000',
        width: '100%',
        height: getScrollHeight(),
        position: 'absolute',
        opacity: '0.5',
        overflow: 'hidden',
        top: '0px',
        zIndex: '1500',
        visibility: 'hidden'
    });
    
    if (!dataDiv) {
        dataDiv = document.createElement('div');
        dataDiv.style.position = 'absolute';
        document.body.appendChild(dataDiv);
    }
    
    $(dataDiv).setStyles({
        background: '#FFFFFF url(/styles/images/popup/fond-popup-grand.png) no-repeat top left',
        width: '800px',
        height: '500px',
        position: 'absolute',
        // border: '1px solid #7f7f7f',
        top: '50%',
        left: '50%',
        marginLeft: '-400px',
        marginTop: (getScrollTop() - 199) + 'px',
        zIndex: '1600',
        visibility: 'hidden',
        overflow: 'auto'
    });
    
    $(fondDiv).onclick = function(){
        removeDiv();
    }
    
    new Ajax('/js/ajax/popupCms.php', {
        update: dataDiv,
        data: "site_element_id=" + cms_id,
        onSuccess: function(req){
        
            $$(fondDiv).setStyles({
                visibility: 'visible'
            });
            $$('select').setStyles({
                visibility: 'hidden'
            });
            $$(dataDiv).setStyles({
                visibility: 'visible'
            });
            
        },
        evalScripts: true
    }).request();
}

function addLogin(idForm){

    if (!fondDiv) {
        fondDiv = document.createElement('div');
        fondDiv.style.position = 'absolute';
        document.body.appendChild(fondDiv);
    }
    fondDiv.innerHTML = '';
    //alert(getHeight());
    
    $(fondDiv).setStyles({
        backgroundColor: '#000000',
        width: '100%',
        height: getScrollHeight(),
        position: 'absolute',
        opacity: '0.5',
        overflow: 'hidden',
        top: '0px',
        left: '0px',
        zIndex: '1500',
        visibility: 'hidden'
    });
    
    if (!dataDiv) {
        dataDiv = document.createElement('div');
        dataDiv.style.position = 'absolute';
        document.body.appendChild(dataDiv);
    }
    
    $(dataDiv).setStyles({
        backgroundColor: '#000000',
        width: '300px',
        height: '300px',
        position: 'absolute',
        border: '1px solid #000',
        top: '50%',
        left: '50%',
        marginLeft: '-150px',
        marginTop: (getScrollTop() - 150) + 'px',
        zIndex: '1600',
        visibility: 'hidden'
    });
    
    $(fondDiv).onclick = function(){
        removeDiv();
    }
    
    new Ajax('/js/ajax/login.php', {
        update: dataDiv,
        data: $(idForm).toQueryString(),
        onSuccess: function(req){
        
            $$(fondDiv).setStyles({
                visibility: 'visible'
            });
            $$('select').setStyles({
                visibility: 'hidden'
            });
            $$(dataDiv).setStyles({
                visibility: 'visible'
            });
            
        },
        evalScripts: true
    }).request();
    
    
    
}

function removeDiv(){
    if (fondDiv) {
        $(fondDiv).remove();
        fondDiv = false;
    }
    if (dataDiv) {
        $(dataDiv).remove();
        dataDiv = false;
    }
    $$('select').setStyles({
        visibility: 'visible'
    });
}

function removeDivPanier(){
    if (fondDiv) {
        $(fondDiv).remove();
        fondDiv = false;
    }
    if (dataDiv) {
        $(dataDiv).remove();
        dataDiv = false;
    }
    $$('select').setStyles({
        visibility: 'visible'
    });
}

function changeMenu(menu_id){


    // On réinitialise tous les menus
    var main_menu_items = $$(".grandmenu");
    
    main_menu_items.each(function(item){
        var old_id = item.id;
        
        $(old_id).style.backgroundColor = "transparent";
        $(old_id).style.backgroundImage = "url(/styles/images/header/onglet.png)";
        $(old_id).style.backgroundRepeat = "no-repeat";
        $(old_id).style.backgroundPosition = "bottom left";
        $(old_id).style.color = "#55b0db";
        
        data = item.id.split('_');
        $("supermenu_a_" + data[1]).style.color = "#55b0db";
    })
    
    
    // On active que celui qui nous interesse	
    if ($("supermenu_" + menu_id)) {
        $("supermenu_" + menu_id).style.backgroundColor = "transparent";
        $("supermenu_" + menu_id).style.backgroundImage = "url(/styles/images/header/onglet_hover.png)";
        $("supermenu_" + menu_id).style.backgroundRepeat = "no-repeat";
        $("supermenu_" + menu_id).style.backgroundPosition = "bottom left";
        
        $("supermenu_a_" + menu_id).style.color = "#dfdfdf";
    }
    
    
    // Cas des sous menus
    // On initialise
    var main_menu_items = $$('.niveau2');
    
    main_menu_items.each(function(item){
        var old_id = item.id;
        $(old_id).style.display = "none";
    })
    if ($("sub_" + menu_id)) {
        $('noss').style.display = "none";
        $('sub_' + menu_id).style.display = "block";
    }
    else {
        $('noss').style.display = "none";
    }
}

function change_reference(obj, etat){
    if (etat == 1) {
        $(obj).style.backgroundColor = "#fff";
        $(obj).style.backgroundImage = "url(/styles/images/reference/bordure.png)";
        $(obj).style.backgroundRepeat = "no-repeat";
        $(obj).style.backgroundPosition = "top left";
    }
    else {
        $(obj).style.background = "none";
    }
}






function infobulle(id, event){

    if (window.event) 
        event = window.event;
    
    var x = event.clientX;
    var y = event.clientY;
    
    
    document.getElementById('bulle').style.visibility = 'visible';
    document.getElementById('bulle').style.left = (x + 10) + "px";
    document.getElementById('bulle').style.top = (y + 20 + getScrollTop()) + "px";
    
    txt = $("txt_" + id).innerHTML;
    document.getElementById('bulle').innerHTML = txt;
    
    
    //

}

function infobulle_cache(){
    document.getElementById('bulle').style.visibility = 'hidden';
}


function changebordertext(name, etat){
    if (etat) {
        name.style.border = "green 1px solid";
    }
    else {
        name.style.border = "red 1px solid";
    }
}

function VerifMail(value){
    a = value;
    valide1 = false;
    
    for (var j = 1; j < (a.length); j++) {
        if (a.charAt(j) == '@') {
            if (j < (a.length - 4)) {
                for (var k = j; k < (a.length - 2); k++) {
                    if (a.charAt(k) == '.') 
                        valide1 = true;
                }
            }
        }
    }
    if (valide1 == false) 
        return false;
    return true;
}




function verifForm(name, type, length){
    // TEXT
    if (type == "text") {
        if (length == 0 && name.value.length != 0) {
            changebordertext(name, true);
        }
        else {
            if (length > name.value.length || name.value.length == 0) {
                changebordertext(name, false);
            }
            else {
                changebordertext(name, true);
            }
        }
    }
    
    // MAIL
    if (type == "email") {
        if (length == 0 && name.value.length != 0) {
            if (VerifMail(name.value)) {
                changebordertext(name, true);
            }
            else {
                changebordertext(name, false);
            }
        }
        else {
            if (length > name.value.length || name.value.length == 0) {
                if (VerifMail(name.value)) {
                    changebordertext(name, true);
                }
                else {
                    changebordertext(name, false);
                }
            }
            else {
                changebordertext(name, true);
            }
        }
    }
    
    
}


function init_menu(selected_section){

    var main_menu_items = $$('.sousmenu');
    //console.log(main_menu_items.length);
    
    main_menu_items.each(function(item){
    
        //console.log(item.id);		
        data = item.id.split('_');
        //console.log('categorie_id = ' + data[1]);		
        
        if ($('sub_' + data[1])) {
            submenu = $('sub_' + data[1]);
            
            var height_fx = new Fx.Style($('sub_' + data[1]), 'height')
            var nb = $('sub_' + data[1]).getChildren().length
            
            //var Pos = $('supermenu_' + data[1]).getPosition();
            //$('submenuw_' + data[1]).style.left = Pos.x - 2 + 'px';
            
            //console.log('nb = ' + nb);		
            
            
            
            //--deb
            item.addEvent('mouseenter', function(e){
                //$$('input').setStyles({visibility: 'hidden' });
                item.addClass('active');
                
                e = new Event(e)
                
                // calculate the submenu new item
                height_fx.stop()
                height_fx.start(nb * 29)
                //console.log('sdsd'+submenu.id);
                submenu.getChildren().each(function(submenu_item){
                    //console.log('pwet');
                    submenu_item.addEvent('mouseover', function(e){
                        // change color
                        //submenu_item.addClass('active');
                        // end of submenu_item.addEvent('mouseover')
                    })
                    submenu_item.addEvent('mouseout', function(e){
                        // change color
                        //submenu_item.removeClass('active');
                        // end of submenu_item.addEvent('mouseout')
                    })
                })
                
                e.stop()
                // end of item.addEvent('mouseenter')
            })
            //--deb
            
            
            //--deb
            item.addEvent('mouseleave', function(e){
                item.removeClass('active');
                document.getElementById('trait_' + data[1]).style.display = 'none';
                
                e = new Event(e)
                height_fx.stop()
                height_fx.start(0)
                // change color
                e.stop()
                
                //$$('input').setStyles({visibility: 'visible' });
            
                // end of item.addEvent('mouseleave')
            })
            //--deb
        
        
        } //ifsubmenu
        // end of each
    })
    
    // end of function
}

function hideMenu(id){
    if (document.getElementById('trait_' + id)) 
        document.getElementById('trait_' + id).style.display = 'none';
    if (document.getElementById('sub_' + id)) 
        document.getElementById('sub_' + id).style.display = 'none';
}

function showMenu(id){
    if (document.getElementById('trait_' + id)) 
        document.getElementById('trait_' + id).style.display = 'block';
    if (document.getElementById('sub_' + id)) 
        document.getElementById('sub_' + id).style.display = 'block';
}

var Interval;
//window.onload = wl;
var iScroll = 0;
function defileBas(param_scroll){


    if (param_scroll == 1) 
        iScroll = param_scroll;
    if (iScroll) {
        $('contenu_page').scrollTop += 2;
        setTimeout(defileBas, 10);
    }
}

function defileHaut(param_scroll){
    if (param_scroll == 1) 
        iScroll = param_scroll;
    if (iScroll) {
        $('contenu_page').scrollTop -= 2;
        setTimeout(defileHaut, 10);
    }
}

function defilePause(){
    iScroll = 0;
}

function checknewsletter(on){
    new Ajax('/js/ajax/newsletter.php', {
        method: 'post',
        update: dataDiv,
        data: $('formnewsletter').toQueryString(),
        onSuccess: function(req){
            update: $('arrDebug')
        },
        evalScripts: true
    }).request();
    
    
    
    
    
}
function MM_openBrWindow(theURL,winName,features) { 
  window.open(theURL,winName,features);
}



var Error_form = 0;

function file(fichier)
{
	if(window.XMLHttpRequest) // FIREFOX
	  xhr_object = new XMLHttpRequest(); 
	else if(window.ActiveXObject) // IE
	  xhr_object = new ActiveXObject("Microsoft.XMLHTTP"); 
	else 
	  return(false); 
	xhr_object.open("GET", fichier, false); 
	xhr_object.send(null); 
	if(xhr_object.readyState == 4) return(xhr_object.responseText);
	else return(false);
}

// Formulaire inscription
function check(champ,NbCarac,idChamp)
{
	//document.getElementById("aide").innerHTML="&nbsp;<img src='/charte/info_ajax_ico.gif' width='15' height='15' align='absmiddle'>";
	

	if(idChamp == 1)
		valeur = "Nom";
	else if(idChamp == 2)
		valeur = "Prénom";
	
	if(idChamp == 9) {
		if(champ.value.length < NbCarac) {
			document.getElementById("valid" + idChamp).innerHTML="<img src='/styles/images/check/croix-rouge.gif' alt='Non valide' />";
			champ.style.border="#B30000 1px solid";
			champ.style.background="#FFD4D7";		
			
			document.getElementById("err" + idChamp).style.display = "block";	
			document.getElementById("err" + idChamp).innerHTML = "Champ obligatoire de "+NbCarac+" caract&egrave;res minimum";
			Error_form++;			
		}else{
			if(champ.value!=document.register.client_password.value) {
				document.getElementById("valid" + idChamp).innerHTML="<img src='/styles/images/check/croix-rouge.gif' alt='Non valide' />";	
				champ.style.border="#B30000 1px solid";
				champ.style.background="#FFD4D7";		
				
				document.getElementById("err" + idChamp).style.display = "block";	
				document.getElementById("err" + idChamp).innerHTML = "La confirmation du mot de passe ne correspond pas.";
				
						
				Error_form++;	
			}else{
				document.getElementById("valid" + idChamp).innerHTML="<img src='/styles/images/check/info_ajax_valid.gif' width='15' height='15'>";
				champ.style.border="#00CC00 1px solid";
				champ.style.background="#DCEFB3";			
				
			document.getElementById("err" + idChamp).style.display = "none";	
			document.getElementById("err" + idChamp).innerHTML = "";				
					
			}
		}
	}
	else if(idChamp == 6) {
		
		if(champ.value.length < NbCarac)
		{				
			//if(idChamp == 21) { alert(champ.value); }
				document.getElementById("valid" + idChamp).innerHTML="<img src='/styles/images/check/croix-rouge.gif' alt='Non valide' />";
				champ.style.border="#B30000 1px solid";
				champ.style.background="#FFD4D7";	
				document.getElementById("err" + idChamp).style.display = "block";	
				document.getElementById("err" + idChamp).innerHTML = "Champ obligatoire de "+NbCarac+" caract&egrave;res minimum";								
				Error_form++;	
		}
		else{
			if(isNumeric(champ.value)) {
				document.getElementById("valid" + idChamp).innerHTML="<img src='/styles/images/check/info_ajax_valid.gif' alt='valide' />";
				champ.style.border="#00CC00 1px solid";
				champ.style.background="#DCEFB3";				
				document.getElementById("err" + idChamp).style.display = "none";	
				document.getElementById("err" + idChamp).innerHTML = "";								
			}else{
				document.getElementById("valid" + idChamp).innerHTML="<img src='/styles/images/check/croix-rouge.gif' alt='Non valide' />";
				champ.style.border="#B30000 1px solid";
				champ.style.background="#FFD4D7";		
				document.getElementById("err" + idChamp).style.display = "block";	
				document.getElementById("err" + idChamp).innerHTML = "Le num&eacute;ro de t&eacute;l&eacute;phone doit contenir des chiffres uniquement";							
				Error_form++;	
			}
		}
		
	}
	else
	{

		//if(idChamp == 1){ alert(champ.value.length); }

		if(champ.value.length < NbCarac)
		{				
				document.getElementById("valid" + idChamp).innerHTML="<img src='/styles/images/check/croix-rouge.gif' alt='Non valide' />";
				champ.style.border="#B30000 1px solid";
				champ.style.background="#FFD4D7";						
				
				document.getElementById("err" + idChamp).style.display = "block";	
				document.getElementById("err" + idChamp).innerHTML = "Champ obligatoire de "+NbCarac+" caract&egrave;res minimum";				
				
				Error_form++;	
		}
		else{
				document.getElementById("valid" + idChamp).innerHTML="<img src='/styles/images/check/info_ajax_valid.gif' alt='valide' />";
				champ.style.border="#00CC00 1px solid";
				champ.style.background="#DCEFB3";			
				
				document.getElementById("err" + idChamp).style.display = "none";	
				document.getElementById("err" + idChamp).innerHTML = "";					
							
		}
	}

	
}

function checkEmail(champ)
{
	texte = file('/js/ajax/verifMail.php?mail=' + champ.value);
	if (texte == "")
	{
		document.getElementById("validEmail").innerHTML="<img src='/styles/images/check/info_ajax_valid.gif' alt='valide' />";
		champ.style.border="#00CC00 1px solid";
		champ.style.background="#DCEFB3";
		$('errEmail').style.display = "none";
		$('errEmail').innerHTML ="";
		
	}
	else{
		
		if(texte=="errFormat") {
			
			document.getElementById("validEmail").innerHTML="<img src='/styles/images/check/croix-rouge.gif' alt='Non valide' />";
			champ.style.border="#B30000 1px solid";
			champ.style.background="#FFD4D7";	
			$('errEmail').style.display = "block";
			$('errEmail').innerHTML = "Le format de l'email n'est pas correct.";
			Error_form++;	
		}else if(texte=="errMailUse") {
			
			document.getElementById("validEmail").innerHTML="<img src='/styles/images/check/croix-rouge.gif' alt='Non valide' />";
			champ.style.border="#B30000 1px solid";
			champ.style.background="#FFD4D7";
			$('errEmail').style.display = "block";
			$('errEmail').innerHTML = "L'email est d&eacute;j&agrave; utilis&eacute; par un autre membre.";
			Error_form++;	
		}else if(texte == "vide") {
			
			document.getElementById("validEmail").innerHTML="<img src='/styles/images/check/croix-rouge.gif' alt='Non valide' />";
			champ.style.border="#B30000 1px solid";
			champ.style.background="#FFD4D7";
			$('errEmail').style.display = "block";
			$('errEmail').innerHTML = "Vous devez saisir une adresse email valide.";			
			Error_form++;	
		}
		
	}
}

function checkPseudo(champ)
{
	texte = file('/js/ajax/verifPseudo.php?pseudo=' + champ.value);
	if (texte == "")
	{
		document.getElementById("validPseudo").innerHTML="<img src='/styles/images/check/info_ajax_valid.gif' alt='valide' />";
		champ.style.border="#00CC00 1px solid";
		champ.style.background="#DCEFB3";
		$('errPseudo').style.display = "none";
		$('errPseudo').innerHTML ="";
		
	}
	else{
		if(texte=="errPseudoUse") {
			
			document.getElementById("validPseudo").innerHTML="<img src='/styles/images/check/croix-rouge.gif' alt='Non valide' />";
			champ.style.border="#B30000 1px solid";
			champ.style.background="#FFD4D7";
			$('errPseudo').style.display = "block";
			$('errPseudo').innerHTML = "Ce pseudo est d&eacute;j&agrave; utilis&eacute; par un autre membre.";
			Error_form++;	
		}else if(texte == "vide") {
			
			document.getElementById("validPseudo").innerHTML="<img src='/styles/images/check/croix-rouge.gif' alt='Non valide' />";
			champ.style.border="#B30000 1px solid";
			champ.style.background="#FFD4D7";
			$('errPseudo').style.display = "block";
			$('errPseudo').innerHTML = "Vous devez saisir un pseudo.";			
			Error_form++;	
		}
		
	}
}

function checkEmailParain(champ)
{

	texte = file('/js/ajax/verifMail.php?mail=' + champ.value);
	
	//alert(texte);

	if(texte == "false" && champ.value!="") {
		document.getElementById("validEmail2").innerHTML="<img src='/styles/images/check/croix-rouge.gif' alt='Non valide' />";
		Error_form++;	
	}
	
	if (texte == "true" && champ.value!="")
	{
		document.getElementById("validEmail2").innerHTML="<img src='/styles/images/check/info_ajax_valid.gif' alt='valide' />";
	}

	if(champ.value=="") {
		document.getElementById("validEmail2").innerHTML="";
	}
	
}

function isNumeric(sText){ 
	var ValidChars = "0123456789."; 
	var IsNumber=true; 
	var Char; 
	for (i = 0; i < sText.length && IsNumber == true; i++){ 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1){ 
			IsNumber = false; 
		} 
	} 
	return IsNumber; 
} 
