﻿// 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 showConseil(id, titre) {
    OpenRadWindow("conseil", titre, 600, 400, false, null, "/data/conseils/" + id + ".htm");
}

function showAideDispo() {
    OpenRadWindow("dispo", "Disponibilité", 400, 200, false, null, Racine + "commun/htmltemplates/dispo.html");
}

function confirmOk()
{
    __doPostBack($get('ConfimEventTarget').value, $get('ConfimEventArgument').value);
}

// Google Maps

var fOrderOfCreation = 1;
var markers = [];

function initGoogleMap(container, zoom) {
    var mapOptions = {
        zoom: (zoom == null) ? 5 : zoom,
        center: new google.maps.LatLng(46.76305, 2.5),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(container, mapOptions);
    return map;
}

function clearOverlays() {
    if (markers) {
        for (i in markers) {
            markers[i].setMap(null);
        }
        markers.length = 0;
    }
}

function afficheMarker(map, latitude, longitude, icone, nom, centrer, zoom, draggable, orderOfCreation, fct) {
    var marker = null;
    if (map) {
        if (icone) {
            var icon = new google.maps.MarkerImage(icone,
                new google.maps.Size(20, 34),
                new google.maps.Point(0, 0),
                new google.maps.Point(10, 34));
        }
        var point = new google.maps.LatLng(latitude, longitude);
        if (orderOfCreation) {
            marker = new google.maps.Marker({
                position: point,
                map: map,
                icon: icon,
                title: nom,
                draggable: draggable,
                zIndex: fOrderOfCreation++
            });
        } else {
            marker = new google.maps.Marker({
                position: point,
                map: map,
                icon: icon,
                title: nom,
                draggable: draggable
            });
        }
        markers.push(marker);
        if (centrer)
        {
            map.setCenter(point);
            map.setZoom((zoom == null) ? 13 : zoom);
        }
        if (fct) eval(fct + "(marker);");
    }
    return marker;
}

function afficheAdresse(map, adresse, codePostal, ville, icone, dernierEssai, draggable, fct) {
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'address': adresse + ',' + codePostal + ',' + ville }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            afficheMarker(map, results[0].geometry.location.lat(), results[0].geometry.location.lng(), icone, "", true, null, draggable, false, fct);
        } else if (dernierEssai == false) {
            afficheAdresse(map, '', codePostal, ville, icone, true, draggable, fct);
        }
    });
}

// Recherche avancée

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":
                    if ($('#slider' + idChamp).slider("values", 0) != 0)
                        articleOk &= (valeur && parseFloat(valeur) >= getSliderValeur('slider' + idChamp, 'min'));
                    if ($('#slider' + idChamp).slider("values", 1) != sliderMax)
                        articleOk &= (valeur && parseFloat(valeur) <= getSliderValeur('slider' + idChamp, '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;
}

var _idFamille;

function voirRechercheAvancee(idFamille) {
    if ($get("ra_nbResult").innerHTML > 0) {
        _idFamille = idFamille;
        // mémorisation des critères
        // - Marque
        var crit = new Array();
        var ctrl = $get("ra_marques");
        if (ctrl.selectedIndex != 0)
            crit.push(["Marque", ctrl[ctrl.selectedIndex].value]);
        // - Catégorie
        ctrl = $get("ra_categories");
        if (ctrl && (ctrl.selectedIndex != 0))
            crit.push(["Categorie", ctrl[ctrl.selectedIndex].value]);
        // - Autres critères
        for (idChamp in ra_champs) {
            ctrl = $get("ra_" + idChamp);
            switch (ra_champs[idChamp].type) {
                case "CHOIX":
                case "BOOL":
                    if (ctrl && (ctrl.selectedIndex != 0))
                        crit.push([idChamp, ctrl.selectedIndex]);
                    break;
                case "NUM":
                    if (($('#slider' + idChamp).slider("values", 0) != 0) || ($('#slider' + idChamp).slider("values", 1) != sliderMax))
                        crit.push([idChamp, $('#slider' + idChamp).slider("values", 0) + "," + $('#slider' + idChamp).slider("values", 1)]);
                    break;
                default:
                    if (ctrl && (ctrl.value.length > 0))
                        crit.push([idChamp, ctrl.value]);
                    break;
            }
        }
        // mémorisation des critères sur le serveur et redirection sur le callback
        Findis.Web.Services.Contexte.SetRechercheAvancee(idFamille, crit, voirRACallBack);
    } else {
        alert("Aucun produit ne correspond à vos critères.");
    }
}

function voirRACallBack(result) {
    // redirection
    if (result > 0)
        self.location = "Liste.aspx?id=" + _idFamille + "&lst=" + $get("ra_results").value;
    else
        self.location = "Liste.aspx?id=" + _idFamille;
}

function razRechercheAvancee() {
    // marque
    $get("ra_marques").selectedIndex = 0;
    // catégorie
    var ctrl = $get("ra_categories");
    if (ctrl) ctrl.selectedIndex = 0;
    // autres critères
    for (idChamp in ra_champs) {
        ctrl = $get("ra_" + idChamp);
        switch (ra_champs[idChamp].type) {
            case "BOOL":
            case "CHOIX":
                if (ctrl) ctrl.selectedIndex = 0;
                break;
            case "NUM":
                $('#slider' + idChamp).slider("values", 0, 0);
                $('#slider' + idChamp).slider("values", 1, sliderMax);
                break;
            default:
                if (ctrl) ctrl.value = "";
                break;
        }
    }
    rechercheAvancee();
}

function updateSliderLabel(idSlider) {
    $get(idSlider + '_value').innerHTML = getSliderValeur(idSlider, 'min') + ' et ' + getSliderValeur(idSlider, 'max');
}

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(idSlider, minmaxval) {
    var chp = ra_champs[idSlider.replace('slider', '')];
    if (chp) {
        if (minmaxval == 'min') {
            if ($("#" + idSlider).slider("values", 0) == 0) return chp.min;
            else {
                val = $("#" + idSlider).slider("values", 0) * (chp.max - chp.min) / sliderMax + chp.min;
                if (chp.max > 1) return Math.round(val);
                else return Math.round(val * 10) / 10;
            }
        } else if (minmaxval == 'max') {
            if ($("#" + idSlider).slider("values", 1) == sliderMax) return chp.max;
            else {
                val = $("#" + idSlider).slider("values", 1) * (chp.max - chp.min) / sliderMax + chp.min;
                if (chp.max > 1) return Math.round(val);
                else return Math.round(val * 10) / 10;
            }
        } else {
            val = minmaxval * (chp.max - chp.min) / sliderMax + chp.min;
            if (chp.max > 1) return Math.round(val);
            else return Math.round(val * 10) / 10;
        }
    } 
}

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;
}

// 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 = 0;

function initInfos() {
    if (bAffInfos == 0) {
        $("div.infosPro").css("display", "none");
        $("div.infosPro2").css("display", "none");
        $("span.infosPro2").css("display", "none");
        $("div.infosPub").css("display", "block");
    } else {
        $("div.infosPro").css("display", "block");
        $("div.infosPro2").css("display", "block");
        $("span.infosPro2").css("display", "inline");
        $("div.infosPub").css("display", "none");
    }
}

function masquerInfos() {
    bAffInfos = 1 - parseInt(bAffInfos);
    initInfos();
	// 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)) {
        var msg = "Nous pouvons vous livrer " + stock + " pièce(s).";
        if (Activite == "ADC") msg = "Nous ne pouvons vous livrer la quantité désirée.";
        if (!confirm(msg + " Souhaitez-vous ajouter " + qte + " pièce(s) à votre panier ?")) 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";
    }
}

function GetRadWindow() {
    var oWindow = null;
    if (window.radWindow) oWindow = window.radWindow;
    else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;
    return oWindow;
}

function getRadWindow(id) {
    var mgr = GetRadWindowManager();
    var wnd = mgr.getWindowByName(id);
    return wnd;
}

function OpenRadWindow(id, title, width, height, modal, behaviors, url) {
    var wnd = radopen(url, id);
    wnd.setSize(width, height);
    wnd.set_modal(modal);
    wnd.set_visibleStatusbar(false);
    wnd.set_showContentDuringLoad(false);
    if (!behaviors)
        wnd.set_behaviors(Telerik.Web.UI.WindowBehaviors.Move + Telerik.Web.UI.WindowBehaviors.Close);
    else
        wnd.set_behaviors(behaviors);
    wnd.set_title(title);
    //wnd.IconUrl = "/data/trs.gif";

    return wnd;
}

function ChoisirClient() {
    var wnd = OpenRadWindow('ChoixClient', '', 500, 360, true, null, getRacine() + 'FdV/ChoixClient.aspx');
    wnd.show();
}
