function verifLogin(formulaire){
    var login = "";
    var newPassword = "";
    if(formulaire.login.value==''){
        alert('Veuillez écrire votre identifiant.');
        formulaire.login.focus();
        return false;
    } else {
        login = formulaire.login.value;
    }
    if(formulaire.password.value==''){
        alert('Veuillez écrire votre mot de passe.');
        formulaire.password.focus();
        return false;
    } else {
        newPassword = MD5(formulaire.password.value);
    }
    window.location.href="login.do?login="+login+"&pass="+newPassword;
}

function verifInscription(){
    if(document.clientForm.titre[0].checked==false && document.clientForm.titre[1].checked==false && document.clientForm.titre[2].checked==false){
        alert('Veuillez indiquer votre civilité');
        document.clientForm.titre[0].focus();
        return false;
    }
    if(document.clientForm.nom.value==""){
        alert('Veuillez indiquer votre nom');
        document.clientForm.nom.focus();
        return false;
    }
    if(document.clientForm.prenom.value==""){
        alert('Veuillez indiquer votre prénom');
        document.clientForm.prenom.focus();
        return false;
    }
    if(document.clientForm.adresse.value==""){
        alert('Veuillez indiquer votre adresse');
        document.clientForm.adresse.focus();
        return false;
    }
    if(document.clientForm.cp.value==""){
        alert('Veuillez indiquer votre code postal');
        document.clientForm.cp.focus();
        return false;
    }
    if(document.clientForm.ville.value==""){
        alert('Veuillez indiquer votre ville');
        document.clientForm.ville.focus();
        return false;
    }
    if(document.clientForm.email.value==""){
        alert('Veuillez indiquer votre email');
        document.clientForm.email.focus();
        return false;
    } else {
            var email=document.clientForm.email.value;
            var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            if (!filter.test(email)){
                alert('Veuillez indiquer un email valide');
                document.clientForm.email.focus();
                return false;
            }
    }

    if(document.clientForm.login.value.length<6){
        alert('Veuillez indiquer un identifiant contenant au moins 6 caractères');
        document.clientForm.login.focus();
        return false;
    }
    if(document.clientForm.password.value.length<6){
        alert('Veuillez indiquer un mot de passe contenant au moins 6 caractères');
        document.clientForm.password.focus();
        return false;
    } else {
        if(document.clientForm.password.value!=document.clientForm.confirmpassword.value){
            alert('La confirmation du mot de passe est incorrecte.');
            document.clientForm.confirmpassword.focus();
            return false;
        }
    }
    return true;
}

function changeImage(monImage,source) {
  monImage.src=source;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
   var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
   if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}


function popup(page,nom,largeur,hauteur,options) {
	var top=(screen.height-hauteur)/2;
	var left=(screen.width-largeur)/2;
	window.open(page,nom,"top="+top+",left="+left+",width="+largeur+",height="+hauteur+","+options);
}

function popupFenetre(lien) {
	popup(lien,"popup","800","600","scrollbars=1,resizable=1");
}

String.prototype.trim = function() {
	return this.replace(/(^\s*)|(\s*$)/g, "");
}

function valideRechercheForm(formulaire) {
	formulaire.mots.value = formulaire.mots.value.trim();
	if(formulaire.mots.value=='') {
		alert('Veuillez indiquer un mot pour votre recherche !');
		return false;	
	} else {
		if(formulaire.mots.value.length<=2) {
			alert('Veuillez indiquer un mot de plus de 2 lettres !');
			return false;	
		}		
	}
	return true;	
}

var ie = (document.all)? true:false;
var ns4 = (document.layers)? true:false;
var ns6 = (document.getElementById)? true:false;

function creerObjet() {
    var obj = null;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer"){
        try {
            obj = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (E){
            try {
                obj = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e){
                obj = new XMLHttpRequest();
            }
        }
    }else{
        obj = new XMLHttpRequest();
    }
    if(obj==null){
        alert('Votre navigateur ne supporte pas les objets XMLHTTPRequest...'); 
    }
    return obj;
}

var http = creerObjet();

function addPanier(id, quantite){
        var url = "addPanier.do?idProduit=" + escape(id) +"&quantite=" + escape(quantite)+"&random="+Math.random();
        http.open("GET", url, true);
        http.onreadystatechange = reponse;
        http.send(null);
}
function loadPanier(){
        var url = "loadPanier.do?random="+Math.random();
        http.open("GET", url, true);
        if(LireCookie('closePanier')==null || LireCookie('closePanier')=='0'){
            http.onreadystatechange = reponse;
        } else {
            http.onreadystatechange = reponseFerme;
        }
        http.send(null);
}
function loginAction(){
    var identifiant = document.loginForm.login.value;
    var motdepasse = document.loginForm.password.value;
    var newPassword = MD5(motdepasse);
    var url = "identification.do";
        http.open('GET', url + '?login=' + escape(identifiant)+ '&pass=' + escape(newPassword)+"&nid="+Math.random(), true);
        http.onreadystatechange = function retour(){
           if(http.readyState == 4){
                var xmlDoc = clean(http.responseXML.documentElement);
                var client = xmlDoc.getElementsByTagName("id");
                if(client.length > 0){
                    id = xmlDoc.getElementsByTagName("id")[0].firstChild.nodeValue;
                    titre = xmlDoc.getElementsByTagName("titre")[0].firstChild.nodeValue;
                    nom = xmlDoc.getElementsByTagName("nom")[0].firstChild.nodeValue;
                    prenom = xmlDoc.getElementsByTagName("prenom")[0].firstChild.nodeValue;
                    contenu = "<table><tr><td>"+titre+" "+nom+" "+prenom+"</td></tr>";
                    contenu += "<tr><td><a href=\"\">Votre espace</a> - <a href=\"javascript:void(0);\" onClick=\"deconnexion();\">Deconnexion</a></td></tr>";
                    contenu += "</table>";
                    document.getElementById("logged").innerHTML = contenu;
                    document.getElementById("logged").style.visibility ="visible";
                    document.getElementById("login").style.visibility ="hidden";
                }
            }
        };
        http.send(null);
}

function deconnexion(){
    var url = "deconnexion.do"+"?nid="+Math.random();
        http.open('GET', url , true);
        http.onreadystatechange = function deco(){
           if(http.readyState == 4){
                    document.getElementById("logged").style.visibility ="hidden";
                    contenu = "<form action=\"\" name=\"loginForm\" method=\"POST\">";
                    contenu += "<table>";
                    contenu += "<tr><td>Identifiant :</td><td><input type=\"text\" name=\"login\" value=\"\" size=\"10\"/></td></tr>";
                    contenu += "<tr><td>Mot de passe :</td><td><input type=\"password\" name=\"password\" value=\"\" size=\"10\"/></td><td><a href=\"javascript:void(0);\" onClick=\"loginAction();\"><img src=\"images/ok.gif\" border=\"0\" alt=\"Valider\"/></a></td></tr>";
                    contenu += "</table>";
                    contenu += "</form>";
                    document.getElementById("login").innerHTML=contenu;
                    document.getElementById("login").style.visibility ="visible";
            }
        };
        http.send(null);
}

function reponse() {
  if(http.readyState == 4){
        if(http.responseXML.documentElement != null){
        var xmlDoc = clean(http.responseXML.documentElement);
        var produit = xmlDoc.getElementsByTagName("produit");
        if(produit.length > 0){
        contenu = "<table cellpadding=\"0\" cellspacing=\"0\">";
            contenu += "<tr><td height=\"100%\">";
            contenu += "<table width=\"7\" height=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">";
                contenu += "<tr><td width=\"7\" height=\"8\" class=\"cadreHoGo\"></td></tr>";
                contenu += "<tr><td width=\"7\" height=\"100%\" class=\"cadreGo\"></td></tr>";
                contenu += "<tr><td width=\"7\" height=\"8\" class=\"cadreBaGo\"></td></tr>";
            contenu += "</table></td><td>";
            contenu += "<table border=\"0\" height=\"100%\" cellpadding=\"0\" cellspacing=\"0\">";
                contenu += "<tr height=\"4\"><td class=\"cadreHo\"></td></tr>";
                contenu += "<tr><td>";

        contenu += "<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\"><tr height=\"100%\"><td class=\"panierCadre\" width=\"90%\">";
        contenu += "<table><tr><td><img src=\"images/panier.gif\"/></td><td><b><a class=\"panierTitreLien\" href=\"javascript:openClose("+produit.length+");\">Panier : ";
        if(produit.length <= 1){
            contenu += produit.length+" article";
        } else {
            contenu += produit.length+" articles";
        }
        contenu +="</b></td></tr></table></td></tr>";
        contenu += "<tr><td><table width=\"100%\" cellpadding=\"1\" cellspacing=\"0\">";
        for(i=0 ; i<produit.length ; i++){
            idProduit = xmlDoc.getElementsByTagName("id")[i].firstChild.nodeValue;
            nomProduit = xmlDoc.getElementsByTagName("nom")[i].firstChild.nodeValue;
            quantiteProduit = xmlDoc.getElementsByTagName("quantite")[i].firstChild.nodeValue;
            contenu += "<tr><td class=\"panierInterieur\"><a href=\"javascript:deleteProduitPanier("+idProduit+")\"><img src=\"images/cancel.gif\" border=\"0\" alt=\"Supprimer article\"/></a>";
            contenu += " <a class=\"panierLien\" href=\"detailProduit.do?id="+idProduit+"\">";
            contenu += nomProduit+"</a></td><td class=\"panierInterieur\">";
            contenu += quantiteProduit+"</td><td class=\"panierInterieur\">";
            contenu += "<img src=\"images/ico_plus.gif\" onClick=\"addPanier("+idProduit+", 1);\"/><br/><img onClick=\"addPanier("+idProduit+", -1);\" src=\"images/ico_moins.gif\"/></td></tr>";
            contenu += "<tr bgcolor=\"#FFFFFF\"><td colspan=\"3\"></td></tr>";
        }
        contenu += "</table></td></tr>";
        contenu += "<tr><td class=\"panierCadre\"><a href=\"panier.do\" class=\"panierTitreLien\"/>Passer la commande</a></td></tr>";
        contenu +="</table>";

        contenu += "</td></tr>";
        contenu += "<tr><td height=\"8\" class=\"cadreBa\"></td></tr></table>";
        contenu += "</td><td width=\"7\" height=\"100%\">";

        contenu += "<table width=\"7\" height=\"100%\" cellpadding=\"0\" cellspacing=\"0\">";
                contenu += "<tr><td width=\"7\" height=\"8\" class=\"cadreHoDr\"></td></tr>";
                contenu += "<tr><td width=\"7\" height=\"100%\" class=\"cadreDr\"></td></tr>";
                contenu += "<tr><td width=\"7\" height=\"8\" class=\"cadreBaDr\"></td></tr>";
        contenu += "</table>";

        contenu += "</td></tr></table>";
                document.getElementById("panier").innerHTML = contenu;
                document.getElementById("panier").style.visibility ="visible";
                document.getElementById("panierFerme").style.visibility ="hidden";
        } else {
                openClose(0);
        }
      }
   }
}

function reponseFerme() {
  if(http.readyState == 4){
        if(http.responseXML.documentElement != null){
        var xmlDoc = clean(http.responseXML.documentElement);
        var produit = xmlDoc.getElementsByTagName("produit");
            contenu = "<table cellpadding=\"0\" cellspacing=\"0\"><tr><td><b><a class=\"blanc\" href=\"javascript:openClose();\">Panier : ";
            if(produit.length <= 1){
                contenu += produit.length+" article";
            } else {
                contenu += produit.length+" articles";
            }
            contenu +="</b></td></tr>";
            document.getElementById("panierFerme").innerHTML = contenu;
            document.getElementById("panierFerme").style.visibility="visible";
      }
   }
}
function go(c){
    if(!c.data.replace(/\s/g,''))
        c.parentNode.removeChild(c);
}

function clean(d){
        var bal=d.getElementsByTagName('*');
        for(i=0;i<bal.length;i++){
                a=bal[i].previousSibling;
                if(a && a.nodeType==3)
                        go(a);
                b=bal[i].nextSibling;
                if(b && b.nodeType==3)
                        go(b);
        }
        return d;
}

function deleteProduitPanier(id){
    var url = "deleteProduitPanier.do";
    var idProduit = id;
        http.open('get', url + '?idProduit=' + escape(idProduit), true);
        http.onreadystatechange = reponse;
        http.send(null);
}
function openClose(nbProduit) {
        if(document.getElementById("panier").style.visibility=="visible"){
            document.getElementById("panier").style.visibility="hidden";
            contenu = "<table cellpadding=\"0\" cellspacing=\"0\"><tr><td><b><a class=\"blanc\" href=\"javascript:openClose();\">Panier : ";
            if(nbProduit <= 1){
                contenu += nbProduit+" article";
            } else {
                contenu += nbProduit+" articles";
            }
            contenu +="</b></td></tr>";
            document.getElementById("panierFerme").innerHTML = contenu;
            document.getElementById("panierFerme").style.visibility="visible";
            EcrireCookie('closePanier', '1');
        } else {
            EcrireCookie('closePanier', '0');
            loadPanier();
        }
}
function closePanier(){
        document.getElementById("panierFerme").style.visibility="hidden";
        document.getElementById("panier").style.visibility="hidden";
}

function deplacement(e) {
      if (ie) {
            //Récupération de la position de la souris
            window.lastX=event.clientX;
            window.lastY=event.clientY;
            // lance doDrag tant que l'on appuie sur le bouton de la souris en la bougeant
            document.onmousemove=doDrag;
            // lance endDrag quand on relache le bouton de la souris
            document.onmouseup=endDrag; 
      }else if (ns4) {
            //Récupération de la position de la souris
            window.lastX=e.pageX;
            window.lastY=e.pageY;
            // lance doDrag tant que l'on appuie sur le bouton de la souris en la bougeant
            document.captureEvents(Event.MOUSEMOVE)
            document.onmousemove=doDrag;
            // lance endDrag quand on relache le bouton de la souris
            document.captureEvents(Event.MOUSEUP)
            document.onmouseup=endDrag; 
      }else {
            //Récupération de la position de la souris
            window.lastX=e.clientX;
            window.lastY=e.clientY;
            // lance doDrag tant que l'on appuie sur le bouton de la souris en la bougeant
            window.onmousemove=doDrag;
            // lance endDrag quand on relache le bouton de la souris
            window.onmouseup=endDrag; 
      }

}
function doDrag(e) {
        unSelect();
      if (ie) {
            // Calcul de l'écart de position de la souris
            var difX=event.clientX-window.lastX;
            var difY=event.clientY-window.lastY;
            //Récupération de la position du div et ajout de l'écart de position de la souris
            var newX1 = parseInt(panier.style.left)+difX;
            var newY1 = parseInt(panier.style.top)+difY;
            // Assignation des nouvelles coordonnées au div
            panier.style.left=newX1+"px";
            panier.style.top=newY1+"px";
            //Assignation de l'anciènne position de la souris
            window.lastX=event.clientX;
            window.lastY=event.clientY; 
        } else if (ns4) {
            // Calcul de l'écart de position de la souris
            var difX=e.pageX-window.lastX;
            var difY=e.pageY-window.lastY;
            //Récupération de la position du div et ajout de l'écart de position de la souris
            var newX1 = parseInt(document.layers.panier.left)+difX;
            var newY1 = parseInt(document.layers.panier.top)+difY;
            // Assignation des nouvelles coordonnées au div
            document.layers.panier.left=newX1;
            document.layers.panier.top=newY1;
            //Assignation de l'anciènne position de la souris
            window.lastX=e.pageX;
            window.lastY=e.pageY; 
        } else {
            // Calcul de l'écart de position de la souris
            var difX=e.clientX-window.lastX;
            var difY=e.clientY-window.lastY;
            //Récupération de la position du div et ajout de l'écart de position de la souris
            var newX1 = parseInt(document.getElementById("panier").style.left)+difX;
            var newY1 = parseInt(document.getElementById("panier").style.top)+difY;
            // Assignation des nouvelles coordonnées au div
            document.getElementById("panier").style.left=newX1+"px";
            document.getElementById("panier").style.top=newY1+"px";
            //Assignation de l'anciènne position de la souris
            window.lastX=e.clientX;
            window.lastY=e.clientY; 
        } 

}
function start() {
            // lance deplacement quand on appuie sur le bouton de la souris
            loadPanier();
      if (ie) {
            panier.onmousedown= deplacement; 
      }else if (ns4) {
            document.captureEvents(Event.MOUSEDOWN);
            document.onmousedown=deplacement; 
      }else {
            document.getElementById("panier").addEventListener("mousedown",deplacement, false); 
            document.getElementById("panierFerme").addEventListener("mousedown",deplacement, false); 
      }
}
function endDrag(e) {
      select();
      if (ie || ns4) {
            //Réinitialisation du onmousemove
            document.onmousemove=null; 
      } else {
            //Réinitialisation du onmousemove
            window.onmousemove=null; 
      }
}
function EcrireCookie(nom, valeur){
    var argv=EcrireCookie.arguments;
    var argc=EcrireCookie.arguments.length;
    var expires=(argc > 2) ? argv[2] : null;
    var path=(argc > 3) ? argv[3] : null;
    var domain=(argc > 4) ? argv[4] : null;
    var secure=(argc > 5) ? argv[5] : false;
    document.cookie=nom+"="+escape(valeur)+
    ((expires==null) ? "" : ("; expires="+expires.toGMTString()))+
    ((path==null) ? "" : ("; path="+path))+
    ((domain==null) ? "" : ("; domain="+domain))+
    ((secure==true) ? "; secure" : "");
}

function getCookieVal(offset){
    var endstr=document.cookie.indexOf (";", offset);
    if (endstr==-1) endstr=document.cookie.length;
    return unescape(document.cookie.substring(offset, endstr));
}
function LireCookie(nom){
    var arg=nom+"=";
    var alen=arg.length;
    var clen=document.cookie.length;
    var i=0;
    while (i<clen){
        var j=i+alen;
        if (document.cookie.substring(i, j)==arg) return getCookieVal(j);
        i=document.cookie.indexOf(" ",i)+1;
        if (i==0) break;
    }
    return null;
}
function dechargement(){
      if (ie || ns4) {
            posX = panier.style.left;
            posY = panier.style.top;
            posX = posX.substring(0, posX.indexOf('px'));
            posY = posY.substring(0, posY.indexOf('px'));
                    EcrireCookie('posX', posX);
                    EcrireCookie('posY', posY);
      } else {
            posX = document.getElementById("panier").style.left;
            posY = document.getElementById("panier").style.top;
            posX = posX.substring(0, posX.indexOf('px'));
            posY = posY.substring(0, posY.indexOf('px'));
                    EcrireCookie('posX', posX);
                    EcrireCookie('posY', posY);
      }
}
function unSelect(){
    if(ie){
        document.onselectstart = new Function("return false");
    } else {
        if(window.sidebar){
            document.onmousedown=faux;
            document.onclick=bien;
        }
    }
}
function select(){
    if(ie){
        document.onselectstart = new Function("return true");
    } else {
        if(window.sidebar){
            document.onmousedown=bien;
            document.onclick=bien;
        }
    }
}
function faux(e){
    return false;
}
function bien(e){
    return true;
	
}

/***email POUR NEWSLETTER ***/
function validerEmail() {
var email = document.getElementById('email').value;
	 if(email == ""){
        alert ('Vous devez remplir le champ e-mail !!!');
        return false;
    } else if (!checkEmail(email)) {
		alert ('L\'email saisit n\'est pas valide.');
		return false;
	} else { return true;
	}
}

function checkEmail(emailStr) {
       if (emailStr.length == 0) {
           return true;
       }
       var emailPat=/^(.+)@(.+)$/;
       var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
       var validChars="\[^\\s" + specialChars + "\]";
       var quotedUser="(\"[^\"]*\")";
       var ipDomainPat=/^(\d{1,3})[.](\d{1,3})[.](\d{1,3})[.](\d{1,3})$/;
       var atom=validChars + '+';
       var word="(" + atom + "|" + quotedUser + ")";
       var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
       var domainPat=new RegExp("^" + atom + "(\\." + atom + ")*$");
       var matchArray=emailStr.match(emailPat);
       if (matchArray == null) {
           return false;
       }
       var user=matchArray[1];
       var domain=matchArray[2];
       if (user.match(userPat) == null) {
           return false;
       }
       var IPArray = domain.match(ipDomainPat);
       if (IPArray != null) {
           for (var i = 1; i <= 4; i++) {
              if (IPArray[i] > 255) {
                 return false;
              }
           }
           return true;
       }
       var domainArray=domain.match(domainPat);
       if (domainArray == null) {
           return false;
       }
       var atomPat=new RegExp(atom,"g");
       var domArr=domain.match(atomPat);
       var len=domArr.length;
       if ((domArr[domArr.length-1].length < 2) ||
           (domArr[domArr.length-1].length > 3)) {
           return false;
       }
       if (len < 2) {
           return false;
       }
       return true;
    }
function getPageUrl() {
    return window.location.href.toString();
}
