﻿// Ouverture de fenetre
function OpenW(Url, NomWin, Width, Height, Param, Top, Left)
{
	if (eval('window.'+ NomWin)!= null){eval('window.' + NomWin + '.close();');}
	if (Width == 0 || Width == null){Width = window.screen.availWidth-100;}
	if (Height == 0 || Height == null){Height = window.screen.availHeight-50;}
	if (Top == null && Top != 0){Top=(window.screen.availHeight/2)-(Height/2)-50;}
	if (Left == null && Left != 0){Left=(window.screen.availWidth/2)-(Width/2);}
	if (Param == '' || Param == null)
	{
		Param = 'scrollbars=1,resizable=yes';
	}
	if (Left <= 0){Left = 1}
	if (Top <= 0){Top = 1}
	eval(NomWin+'=window.open("'+Url+'","'+NomWin+'","top='+Top+',left='+Left+',width='+Width+',height='+Height+','+Param+'");');
}

// Appels Ajax
var ajaxReturnValue;
function ajax(url, querystring, method, fct) {
    var xhr_object = null;
    if(window.XMLHttpRequest)
      xhr_object = new XMLHttpRequest();
    else if(window.ActiveXObject)
      xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
    else {
      alert("Votre navigateur ne supporte pas les appels AJAX.");
      return;
    }
    xhr_object.onreadystatechange = function anonymous() {
        if (xhr_object.readyState == 4) {
            if (xhr_object.status  == 200) {
                ajaxReturnValue = xhr_object.responseText;
                if (fct != null) eval(fct + "(ajaxReturnValue);");
                else eval(ajaxReturnValue);
            }
            else alert(xhr_object.responseText);
        }
    };
    if (method == null) method = "POST";
    if (method == "POST") xhr_object.open(method, url, true);
    else xhr_object.open(method, url + "?" + querystring, true);
    
    if (method == "POST") {
        xhr_object.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        var data = querystring;
        xhr_object.send(data);
    } else xhr_object.send("");
}

// Affichage d'objets Flash
function showFlash(animation, width, height) {
AC_FL_RunContent(
    'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0',
    'width', width,
    'height', height,
    'src', animation,
    'quality', 'high',
    'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
    'align', 'middle',
    'play', 'true',
    'loop', 'true',
    'scale', 'showall',
    'wmode', 'transparent',
    'devicefont', 'false',
    'id', 'texte_anim',
    'bgcolor', '#ffffff',
    'name', 'texte_anime',
    'menu', 'true',
    'allowFullScreen', 'false',
    'allowScriptAccess','sameDomain',
    'movie', animation,
    'salign', ''
);
}

function getRacine() {
    if (typeof(Racine) == 'undefined')
        return '/';
    else
        return Racine;
}

// Recherche d'article
function recherche(champ) {
    var texte = champ.value;
    if ((texte.length > 0) && (texte != "Recherche"))
        self.location = getRacine() + "Recherche.aspx?q=" + escape(texte);
}

// Recherche de point de vente
function recherchePV(champ, url) {
    var commune = champ.value;
    if (commune.length > 2)
        self.location = getRacine() + "PointsVente.aspx?c=" + escape(commune) + "&url=" + url;
    else
        alert("Veuillez saisir le code postal ou le nom de votre commune");
}

function redirectPV(url) {
    if (confirm("La vente en ligne est accessible pour votre commune.\nVous allez être redirigé(e) sur son site, sur lequel vous pourrez effectuer vos achats."))
        self.location = url;
}

function showPV(ev) {
    setTimeout("$find('PVBehavior').show();", 100);
}

function hidePV(ev) {
    ev.preventDefault();        
    var modalPopupBehavior = $find('PVBehavior');
    modalPopupBehavior.hide();
}

function showZoom(photo, titre) {
    setPopupContenu("<img src='" + getRacine() + "Images/wait.gif' />");
    $get("modalTitre").innerHTML = titre;
    setPopupContenu("<a href='#' onclick='hideModalPopup();return false;'><img src='/data/photos/300/" + photo + ".jpg' alt='" + titre + "' style='width:300px;height:300px;' /></a>");
    showModalPopup(310, 334);
}

function showConseil(id, titre) {
    setPopupContenu("&nbsp;");
    $get("modalTitre").innerHTML = titre;
    setPopupContenu("<iframe src='/data/conseils/" + id + ".htm' frameborder=0 width='100%' height='100%'></iframe>");
    //ajax(Racine + "conseil.aspx", "id=" + id, "GET", "setPopupContenu");
    showModalPopup(600, 400);
}

function showAideDispo() {
    setPopupContenu("<a href='#' class='Dispo' style='display:inline;'>&nbsp;</a> Article disponible. Livrable sous quelques jours.<br/><br/><a href='#' class='PasDispo' style='display:inline;'>&nbsp;</a> Article en commande. Livrable sous une dizaine de jours.");
    $get("modalTitre").innerHTML = "Disponibilité";
    showModalPopup(400, 150);
}

function setPopupContenu(html) {
    $get("modalContenu").innerHTML = html;
}

function showModalPopup(width, height) {
    window.onscroll = function () { $get("modalPage").style.top = document.body.scrollTop; };
    $get("modalPage").style.top = document.body.scrollTop;
    $get("modalPopup").style.width = width + "px";
    $get("modalPopup").style.height = height + "px";
    $get("modalPopup").style.left = "-" + width / 2 + "px";
    $get("modalPopup").style.top = "-" + height / 2 + "px";
    $get("modalContenu").style.height = (height - 34) + "px";
    $get("modalPage").style.display = "block";
}

function hideModalPopup() {
    $get("modalPage").style.display = "none";
}

function showModalConfirm(eventTarget, eventArgument, titre)
{
    $find("ConfirmBehavior").show();
    $get("ConfirmTitre").innerHTML = titre;
    $get("ConfimEventTarget").value = eventTarget;
    $get("ConfimEventArgument").value = eventArgument;
}

function confirmOk()
{
    __doPostBack($get('ConfimEventTarget').value, $get('ConfimEventArgument').value);
}

var geocoder = null;
var mapRechPV = null;
var mapDetailPV = null;

function initRechPVMap() {
    if (GBrowserIsCompatible()) {
        mapRechPV = new GMap2($get("mapRechPV"));
        mapRechPV.addControl(new GSmallMapControl()); 
        mapRechPV.addControl(new GMapTypeControl()); 
        mapRechPV.enableScrollWheelZoom();
        mapRechPV.enableContinuousZoom();
        mapRechPV.checkResize();
        mapRechPV.setCenter(new GLatLng(46.76305555555555, 2.5), 5); // centre de la France
    }
}

function fOrderOfCreation(marker, b) {
    return 1;
}

function afficheMarker(map, latitude, longitude, icone, nom, centrer, zoom, draggable, orderOfCreation) {
    var marker = null;
    if (map) {
        if (icone) {
            var icon = new GIcon();
            icon.image = icone;
            icon.iconSize = new GSize(20, 34);
            icon.iconAnchor = new GPoint(10, 34);
            icon.infoWindowAnchor = new GPoint(0, 0);
        }
        var point = new GLatLng(latitude, longitude);
        if (orderOfCreation) marker = new GMarker(point, {icon:icon, title:nom, draggable:draggable, zIndexProcess:fOrderOfCreation});
        else marker = new GMarker(point, {icon:icon, title:nom, draggable:draggable});
        map.addOverlay(marker);
        if (centrer)
        {
            //if (!zoom) zoom = 13;
            //point = map.fromLatLngToContainerPixel(point);
            map.checkResize();
            map.setCenter(point, 13);
        }
    }
    return marker;
}

function initDetailPVMap() {
    if (GBrowserIsCompatible()) {
        mapDetailPV = new GMap2($get("mapDetailPV"));
        mapDetailPV.setUIToDefault();
        //mapDetailPV.addControl(new GSmallZoomControl()); 
        //mapDetailPV.addControl(new GMapTypeControl()); 
        mapDetailPV.enableScrollWheelZoom();
        mapDetailPV.enableContinuousZoom();
        mapDetailPV.checkResize();
        mapDetailPV.setCenter(new GLatLng(46.76305555555555, 2.5), 5); // centre de la France
        geocoder = new GClientGeocoder(); 
    }
}

function afficheAdresse(adresse, codePostal, ville, icone, dernierEssai, draggable, fct) { 
  var marker = null;
  if (geocoder) {
    geocoder.getLatLng(
      adresse + ',' + codePostal + ','+ ville,
      function(point) {
        if (!point) {
          if (dernierEssai == true) { /*alert("Adresse introuvable");*/ }
          else afficheAdresse('', codePostal, ville, icone, true, draggable, fct);
        } else {
          if (icone) {
            var icon = new GIcon();
            icon.image = icone;
            icon.iconSize = new GSize(20, 34);
            icon.iconAnchor = new GPoint(10, 34);
            icon.infoWindowAnchor = new GPoint(0, 0);
          }
          marker = new GMarker(point, {icon:icon, draggable:draggable});
          mapDetailPV.addOverlay(marker);
          mapDetailPV.checkResize();
          mapDetailPV.setCenter(point, 13);
          if (fct) eval(fct + "(mapDetailPV, marker);");
        }
      } 
    ); 
  }
  return marker;
} 

function Article(id, marque, categorie, prix, valeurs) {
    this.id = id;
    this.marque = marque;
    this.categorie = categorie;
    this.prix = prix;
    this.valeurs = valeurs;
}

function Champ(id, type, min, max, pas) {
    this.id = id;
    this.type = type;
    this.min = min;
    this.max = max;
    this.pas = pas;
}

var sliderMax = 300;

function rechercheAvancee() {
    var tabResult = new Array();
    for (idArticle in ra_articles) {
        var article = ra_articles[idArticle];
        var articleOk = true;
        var ctrl = null;
        // marque
        ctrl = $get("ra_marques");
        if (ctrl.selectedIndex != 0)
            articleOk &= (article.marque == ctrl[ctrl.selectedIndex].value);
        if (!articleOk) continue;
        // catégorie
        ctrl = $get("ra_categories");
        if (ctrl && (ctrl.selectedIndex != 0))
            articleOk &= (article.categorie == ctrl[ctrl.selectedIndex].value)
        if (!articleOk) continue;
        // autres critères
        for (idChamp in ra_champs) {
            ctrl = $get("ra_" + idChamp);
            if (idChamp == "Prix")
                valeur = article.prix;
            else
                valeur = article.valeurs[idChamp];
            switch (ra_champs[idChamp].type) {
                case "CHOIX":
                    if (ctrl && (ctrl.selectedIndex != 0))
                        articleOk &= (valeur && valeur.toLowerCase() == ctrl[ctrl.selectedIndex].text.toLowerCase())
                    break;
                case "BOOL":
                    if (ctrl && (ctrl.selectedIndex != 0))
                        articleOk &= (valeur && valeur == ctrl[ctrl.selectedIndex].value)
                    break;
                case "NUM":
                    var slider = ra_sliders[idChamp];
                    if (slider.minVal != 0)
                        articleOk &= (valeur && parseFloat(valeur) >= getSliderValeur(slider, 'min'));
                    if (slider.maxVal != sliderMax)
                        articleOk &= (valeur && parseFloat(valeur) <= getSliderValeur(slider, 'max'));
                    break;
                default:
                    if (ctrl && ctrl.value.length > 0)
                        articleOk &= (valeur == ctrl.value);
                    break;
            }
            if (!articleOk) break;
        }
        // tous les critères correspondent
        if (articleOk) tabResult.push(article.id);
    }
    $get("ra_results").value = tabResult.join(",");
    $get("ra_nbResult").innerHTML = tabResult.length;
}

function voirRechercheAvancee(idFamille) {
    if ($get("ra_nbResult").innerHTML > 0)
        self.location = "Liste.aspx?id=" + idFamille + "&lst=" + $get("ra_results").value;
    else
        alert("Aucun produit ne correspond à vos critères.");
}

function comparer() {
    var tabArticles = new Array();
    var chk = document.aspnetForm.chkCompare;
    if (chk.length == 1) {
        if (chk.checked) tabArticles.push(chk.value);
    } else {
        for (var i = 0; i < chk.length; i++)
            if (chk[i].checked) tabArticles.push(chk[i].value);
    }
    if ((tabArticles.length > 0) && (tabArticles.length <= 4))
        self.location = "Comparer.aspx?id=" + $get("idFamille").value + "&lst=" + tabArticles.join(",");
    else
        alert("Veuillez sélectionner entre 2 et 4 articles");
}

function getSliderValeur(slider, minmax) {
    var chp = ra_champs[slider.activeSlider.id.replace('slider', '')];
    if (chp) {
        if (minmax == 'min') {
            if (slider.minVal == 0) return chp.min;
            else return Math.round(slider.minVal * (chp.max - chp.min) / sliderMax + chp.min);
        } else {
            if (slider.maxVal == sliderMax) return chp.max;
            else return Math.round(slider.maxVal * (chp.max - chp.min) / sliderMax + chp.min);
        }
    } 
}

function removeSelectedItems(liste) {
    for (var i = 0; i < liste.length; i++) {
        if (liste.options[i].selected == true) {
            liste.options[i] = null; 
            i--;
        }
    }
}

function insertItem(liste, texte, valeur) {
    var item = new Option(texte, valeur);
    liste.options[liste.length] = item;
}

// Manipulation des balises HTML Par Julien Royer (www.alsacreations.com)
// Exemples d'utilisation : var els = cls.query("active"); // .active
//                          els = cls.query("active", "span"); // span.active
var cls = (function() {
	function re(cn) {
		return new RegExp("(^|\\s)" + cn + "(\\s|$)");
	}

	var that = {
		has: function(el, cn) {
			return re(cn).test(el.className);
		},

		add: function(el, cn) {
			if (!el.className) {
				el.className = cn;
			} else if (!that.has(el, cn)) {
				el.className += " " + cn;
			}
		},

		rem: function(el, cn) {
			el.className = el.className.replace(re(cn), function(m, c1, c2) { return c1 && c2; });
		},

		replace: function(el, cn, newCn) {
			el.className = el.className.replace(re(cn), "$1" + newCn + "$2");
		},

		query: function(cn, tn, root) {
			var els = (root || (root = document)).getElementsByTagName(tn || (tn = "*"));
			if (!els.length && root.all && tn === "*") {
				els = root.all;
			}

			var res = [], r = re(cn);
			for (var i = 0, el; (el = els[ i]); ++i) {
				if (r.test(el.className)) {
					res[res.length] = el;
				}
			}

			return res;
		}
	};
	return that;
})();

// Masquer les balises en fonction d'une classe
function Masquer(balise, classe) {
  var els = cls.query(classe, balise)
  for (i=0; i < els.length; i++)
    els[i].style.display = "none";
}

// Afficher les balises en fonction d'une classe
function Afficher(balise, classe) {
  var els = cls.query(classe, balise)
  for (i = 0; i < els.length; i++)
      els[i].style.display = "block";
}

function AfficherInline(balise, classe) {
    var els = cls.query(classe, balise)
    for (i = 0; i < els.length; i++)
        els[i].style.display = "inline";
}

// Gestion des cookies
function DateExpiration (DateExp) {
	var aujourdhui = new Date(0);
	var aujourdhuidate = aujourdhui.getTime();
	if (aujourdhuidate > 0)
		DateExp.setTime (DateExp.getTime() - aujourdhuidate);
}

function FixeCookie (nom,valeur,expire,path,domaine,securise) {
	document.cookie = nom + "=" + escape (valeur) + ((expire) ? "; expires=" + expire.toGMTString() : "") + ((path) ? "; path=" + path : "") + ((domaine) ? "; domain=" + domaine : "") + ((securise) ? "; secure" : "");
}

function SupprCookie (nom,path,domaine) {
	if (GetValeurCookie(nom)) {
		document.cookie = nom + "=" + ((path) ? "; path=" + path : "") + ((domaine) ? "; domain=" + domaine : "") + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}

function ValeurCookie (Pos) {
	var endstr = document.cookie.indexOf (";", Pos);
	if (endstr == -1)
		endstr = document.cookie.length;
	return unescape(document.cookie.substring (Pos, endstr));
}

function GetValeurCookie (nom) {
	var cookielength = document.cookie.length;
	var arg = nom + "=";
	var arglength = arg.length;
	var i = 0;
	
	while (i < cookielength) {
		var j = i + arglength;
		if (document.cookie.substring(i, j) == arg)
			return ValeurCookie (j);
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) break; 
	}
	return null;
}

// Affichage des infos pro
var bAffInfos
if (GetValeurCookie("infosPro"))
	bAffInfos = parseInt(GetValeurCookie("infosPro"));
else
	bAffInfos = 1;

function masquerInfos() {
	bAffInfos = 1 - parseInt(bAffInfos);
	if (bAffInfos == 0) {
	    Masquer('div', 'infosPro');
	    Masquer('div', 'infosPro2');
	    Masquer('span', 'infosPro2');
        Afficher('div', 'infosPub');
	} else {
	    Afficher('div', 'infosPro');
	    Afficher('div', 'infosPro2');
	    AfficherInline('span', 'infosPro2');
        Masquer('div', 'infosPub');
	}
	// Enregistrement du cookie (de session !)
	FixeCookie("infosPro", bAffInfos, null, "/");
}

// Ajout au panier pro
function CheckQte(btnId, qteId, stock) {
    stock = parseInt(stock);
    qte = $get(qteId).value;
    if (isNaN(qte) || (parseInt(qte) < 0)) {
        alert("Veuillez saisir une quantité supérieure ou égale à 0.");
        return false;
    }
    qte = parseInt(qte);

    bOk = true;
    if ((qte > stock)) {
        if (!confirm("Nous pouvons vous livrer " + stock + " pièce(s). Souhaitez-vous poursuivre votre réservation de " + qte + " pièce(s) ?")) bOk = false;
    }
    if (bOk) $get('__EVENTTARGET').value = btnId;
    return bOk;
}

function toggle(id, inline) {
    var elt = $get(id);
    if (elt) {
        if (elt.style.display == "none")
            elt.style.display = (inline) ? "inline" : "block";
        else
            elt.style.display = "none";
    }
}