/****************************************
 * Bibliothèque de fonctions JavaScript *
 ****************************************/

//#######################################################################################################
function setCookie(nom,valeur,domain)
{
	var expiration = new Date(2999,1,31);
	document.cookie = nom + "=" + escape(valeur) + ";expires=" + expiration.toGMTString() + ";domain=" + domain + ";path=/" ;
}


//#######################################################################################################
function GetCookie(domain, name)
{
	var str = GetDomainCookie(domain);
	return str;
	
}


//#######################################################################################################
function GetDomainCookie(name) 
{
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	} 
	else {
		begin += 2;
	}
	
	var end = document.cookie.indexOf(";", begin);
	
	if (end == -1) {
		end = dc.length;
	}
	
	return unescape(dc.substring(begin + prefix.length, end));
}


//#######################################################################################################
function GetCookieVal( strCookie, valName )
{
	if (strCookie != null)
	{
		var cookieArr=strCookie.split("&");
		valName = valName + '=';
		var alen=valName.length;

		for (i=0; i < cookieArr.length; i++)
		{
			var clen= cookieArr[i].length;
			
			if (cookieArr[i].substring(0,alen) == valName)
			{
				return (cookieArr[i].substring(alen,clen));
			}
		}			
	}	
}


//#######################################################################################################
function cookieExist(Name) 
{
	var search = Name + "=";
	
    if (document.cookie.length > 0)  // si il existe au moins un cookie
    {
		offset = document.cookie.indexOf(search);
		
        if (offset != -1)  // si le cookie recherché existe
        {
			return offset;
        }
        else  //le cookie n'existe pas
        {
			return -1;
        }
	}
} 

//#######################################################################################################
function UpdateUsersInfos()
{
	var s1 = document.getElementById("welcome");
	var s2 = document.getElementById("cartInfo");
	var s3 = document.getElementById("deconnection");

	var nbItemInCart = GetCookie("mollatInfos","nbCartItem");
	var nameUser	 = GetCookie("mollatInfos","nomclient");
	var sessionId    = GetCookie("mollatInfos","s_ID");
	var nameByXHR = new last_httpRequest("/_application/_functions/getNameUser.aspx", "sessionId=" + sessionId , "get");
	
	nameByXHR.createRequestObject();
	nameByXHR.sendGetReq();

	nameByXHR.xmlhttp.onreadystatechange = function()
	{
		if (nameByXHR.xmlhttp.readyState == 4) /* 4 : état "complete" */
		{
			s1.innerHTML = nameByXHR.xmlhttp.responseText
		}
	}
	
	// gestion du nom de l'utilisateur et du lien de deconnection
	
	if (nameUser != 'undefined' && nameUser != '')
	{
		s3.innerHTML = "<a href='/comptes/Deconnection.aspx'> se d&eacute;connecter"
	}
	else
	{
		s3.innerHTML = ""
	}
	
	
	// gestion du nombre de livres dans le CART.
	if (nbItemInCart > 0)
	{
		strNew = "<a href='/cart/cartContent.aspx'>Votre panier comporte (" + nbItemInCart +  ") article(s)</a>";
	}
	else
	{
		strNew = "Aucun article dans votre panier";
	}		
	s2.innerHTML = strNew;
}


//#######################################################################################################
/**
 * Fonction qui permet de gérer une taille max de caractères dans un text area. 
 * params : - form est le nom du formulaire 
 *          - champ est le nom du champ du formulaire 
 *          - max est le nombre max de caractères 
 */
function checkTextArea(champ, max) 
{
	var txt_size = document.getElementById(champ).value.length;
	
	if ( txt_size > max ) 
	{
		var msg = "Vous avez d\351pass\351 le nombre maximum de " + max + " caract\350res !\n";
		msg += "(Vous en avez tap\351 " + txt_size + " ! )";
		alert(msg);
	}
}


//#######################################################################################################
/**
 * Fonction booléénne qui vérifie qu'un nom de fichier a une bonne extension
 * 
 * Paramètres : 
 *  - tabExt() : un tableau contenant les extensions choisies (sans le point '.') 
 *               ex : tabExt = {"gif"; "jpeg"; "jpg"; "png"}
 *  - filename : le nom du fichier à vérifier
 * 
 * Retour : 
 *  - checkExtension renvoie vrai ssi l'extension de filename est contenue dans tabExt 
 *  - faux sinon
 */
function checkExtension(tabExt, filename) 
{
	if ( filename != "" )
	{
		var T = filename.split(".");
		var i_max = T.length - 1;
		
		if (T.length > 1) // filename contient au moins un point '.'
		{
			var ext = T[i_max].toLowerCase();
			
			// Recherche de ext dans tabExt() : 
			var i = 0;
			//while ( i < tabExt.length && !(ext.equals(tabExt[i])) ) 
			while ( i < tabExt.length && ext != tabExt[i].toLowerCase() ) 
			{
				i = i + 1;
			}
			
			return (i < tabExt.length);
		}
		else // filename ne contient pas de point '.'
		{
			return false;
		}
	}
	else {
		return false;
	}
}


//#######################################################################################################
/**
 * Fonction qui ouvre une msgBox de type confirm (bouton Ok et cancel)
 * params : 
 *			msg			, type String	, Message qui s'affichera dans la msgBox
 *			urlValidate	, type String	, Si l'utilisateur click sur oui, on redirige l'utilisateur vers cette url
 *
 **/
function msgConfirme(msg, urlValidate)
{
	if (confirm(msg))
	{
		document.location.href = urlValidate;
	}
}

//#######################################################################################################
/**
 * Fonction qui ouvre une fenetre popUp avec la taille spécifié
 * params : 
 *			url		, type String	, url de la page affiché dans la fenetre pop up
 *			name	, type String	, nom de la fenetre
 *			width	, type integer	, largeur de la fenetre pop up
 *			height	, type integer	, hauteur de la fenetre pop up
 * 
 **/
var WindowObjectReference = null;

function openWindow(strUrl, strWindowName,  width, height)
{
	if(WindowObjectReference == null || WindowObjectReference.closed)
	{
		WindowObjectReference = window.open(strUrl, strWindowName,
			'height=' + height + ',width=' + width + ',toolbar=no,status=no,directories=no,menubar=yes,location=no,scrollbars=yes,resizable=no');
	}
	else
	{
		WindowObjectReference.focus();
	}
}


//#######################################################################################################
/**
 * Fonction qui ouvre une fenetre popUp avec exactement la hauteur et la largeur de l'image !
 * params : 
 *			url		, type String	, url de la page affiché dans la fenetre pop up
 *			name	, type String	, nom de la fenetre
 * 
 **/
var WindowImgObjectReference = null;

function openImgWindow(bigImg, strWindowName)
{		
	if(WindowImgObjectReference == null || WindowImgObjectReference.closed)
	{			
		WindowImgObjectReference = window.open(bigImg.src, strWindowName,
			'height=' + (20 + bigImg.height ) + ',width=' + (bigImg.width + 20) + ',toolbar=no,status=no,directories=no,menubar=no,location=no,scrollbars=no,resizable=no');
	}
	else
	{
		WindowImgObjectReference.focus();
	}
}


//#######################################################################################################
/**
 * Fonction qui ouvre une fenetre popUp centrée sur l'écran 
 * params : 
 *			url		, type String	, url de la page affichée dans la fenetre pop up 
 *			nom		, type String	, nom de la fenetre 
 *			largeur	, type Integer	, largeur de la fenetre pop up 
 *			hauteur	, type Integer	, hauteur de la fenetre pop up 
 *			options	, type String	, options de la méthode window.open() MAIS SANS les attributs width et height ! 
 * 
 **/
function centerPopup(url, nom, largeur, hauteur, options) 
{
	//alert(url);
	
	var x = (screen.width/2) - (largeur/2);
	var y = (screen.height/2) - (hauteur/2);
	
	if (options != '') {
		options += ',';
	}
	
	options += 'width=' + largeur + ',height=' + hauteur + ',top=' + y + ',left=' + x;
	//alert(options);
	//alert('centerPopup OK, now window.open...');
	window.open(url, nom, options);
	//alert('...window.open OK !');
}


//#######################################################################################################
/**
 * Fonction qui permet d'ajouter un article au panier
 * params : 
 *			idProd	, type String	, l'ean à ajouter
 * 
 **/
function AddToCart(idprod)
{
	document.addToCart.prodid.value=idprod
	document.addToCart.submit()
}

	
//#######################################################################################################
/**
 * Fonction qui renvoie True ssi la chaine passée en paramètre a bien le format d'un e-mail valide : 
 **/
function check_email(chaine)
{
	//var regexp = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9]+)+$/;
	var regexp = /^[_a-z0-9-]+([_a-z0-9-\.]+)*@[a-z0-9-]+([_a-z0-9-\.]+)*\.[a-z0-9]{2,}$/;
	
	return (regexp.test(chaine));
}
/*
function alert_email(chaine)
{
	if (!check_email(chaine))
	{
		alert('e-mail invalide !');
		return false;
	}
	else {
		alert('e-mail ok !');
		return true;
	}
}
*/

//#######################################################################################################
//Test un email a partir d'un formulaire. Effectue le Form action si l'email est valid, sinon renvoi un message d'erreur.
// Add by D.Guillard le 26/11/2006
function validFormEmail(txt_Email)
{

if (txt_Email == '')
{
	alert('Veuillez saisir un email.');
	return false;
}
else {

		if (check_email(txt_Email))
		{
			return true;
		}
		else {
			alert('D\351sol\351, l\'email : ' + txt_Email + ' est invalide.');
			return false;
		}
		
	}
}

//#######################################################################################################
//Test un email a partir d'un formulaire. Effectue le Form action si l'email est valid, sinon renvoi un message d'erreur.
// Add by D.Guillard le 28/02/2007
//Cette fonction est la meme que la precedente, avec le controle de champ vide en moins ^^
function validFormEmailWithoutEmptyTest(txt_Email)
{
	if (txt_Email == '')
	{
		return true;
		}else if (check_email(txt_Email))
		{
			return true;
		}
		else {
			alert('D\351sol\351, l\'email : ' + txt_Email + ' est invalide.');
			return false;
		}
		
}
//#######################################################################################################
/**
 * Fonction qui renvoie True ssi le numéro passé en paramètre a bien le format d'un EAN valide : 
 **/
function check_ean(num)
{
	var regexp = /^[0-9]{13,13}$/;
	return (regexp.test(num));
}


//#######################################################################################################
/**
 * Fonction qui teste la validité du numéro EAN ou ISBN passé en paramètre. 
 * Valeurs de retour : 
 *      1 : EAN valide 
 *     -1 : EAN invalide 
 *      2 : ISBN valide 
 *     -2 : ISBN invalide 
 *      0 : valeur incorrecte ne contenant pas de chiffres 
 **/
function check_isbn_ean(num)
{
	var correct;
	
	var nb_chiffrres = 10; // nb de chiffres pour un ISBN 
	var nb_tirets = 3;     // nb de tirets pour un ISBN 
	var isbn_length = nb_chiffrres + nb_tirets;
	
	//Modif le 01/02/2007 par D.Guillard
	var regexp_isbn_tiret	= /^[0-9]+(-)[0-9]+(-)[0-9]+(-)[X0-9]+$/;
	var regexp_isbn_long_tiret= /^[0-9]+(-)[0-9]+(-)[0-9]+(-)[0-9]+(-)[X0-9]+$/;
	var regex_isbn_noTiret	= /^[X0-9]{10,10}$/;
	var regex_ean			= /^[0-9]{13,13}$/;
	
	
	var pas_de_chiffres = /^[^0-9]+$/;
	
	if ( pas_de_chiffres.test(num) ) 
	{
		correct = 0;
	}
	else 
	{			
		// Si on teste un EAN (pas de tirets dans le numéro) : 
		if (num.indexOf("-") == -1) 
		{
			if (regex_ean.test(num)) 
			{
				correct = 1;
			}
			else if (regex_isbn_noTiret.test(num))
			{
				correct = 2;
			}
			else if (num.length > 10)
			{
				correct = -1;
			}
			else
			{
				correct = -2;
			}
		}
					
		// Si on teste un ISBNN : 
		// Modif le 01/02/2007 par D.Guillard -----
		else if (regexp_isbn_tiret.test(num)) 
		{			
			if (num.length == 13)
			{
				correct = 2;
			}
			else
			{
				correct = -2;
			}
		}
		else if (regexp_isbn_long_tiret.test(num))
		{
			if (num.length == 17)
			{
				correct = 2;
			}
			else
			{
				correct = -2;
			}		
		}
		//-----------------------------------------
		else 
		{
			correct = -2;
		}
	}
	
	return correct;
}


//#######################################################################################################
/**
 * Fonction qui limite le nombres de caractères saisis dans un champ text ou textarea 
 * identifié par son id. 
 * Lorsqu'on atteint le maximum, la fonction efface les caractères en trop. 
 * 
 * @params	txt_id  : l'id du champ à contrôler 
 *			max		: le nombre maximum de caractères autorisé 
 **/
function countCar(txt_id, max) 
{
	var txt = document.getElementById(txt_id);
	
	if (txt.value.length > max) 
	{
		txt.value = txt.value.substr(0, max); // substr(0, max) <=> substring(0, max-1)
	}
}


//#######################################################################################################
function txtOnFocus(thisTxtBox, txtDefault)
{
	if (thisTxtBox.value == txtDefault)
	{
		thisTxtBox.value='';
	}
}


//#######################################################################################################
function txtOnBlur(thisTxtBox, txtDefault)
{
	if (thisTxtBox.value == '')
	{
		thisTxtBox.value=txtDefault;
	}
}


//#######################################################################################################
/**
 * Fonction qui récupère les paramètres GET de l'url courante et les retourne dans un 
 * tableau à 2 dimensions : 
 * 
 * Ex : url = http://www.truc.com/index.aspx ? param1=x & param2=y 
 * 
 *		- tab[0][0] = "param1"  ,  tab[0][1] = "x" 
 *		- tab[1][0] = "param2"  ,  tab[1][1] = "y" 
 * 
 * S'il n'y a pas de paramètres GET dans l'url la fonction renvoie la valeur 'null'.
 **/
function getParams() 
{
	var params = location.search.substring(1, location.search.length);
	
	if ( params != "" ) 
	{
		var tab = new Array();
		params = params.split("&");
		
		for (i=0; i < params.length; i++) 
		{
			var variable = params[i].substring(0, params[i].indexOf("="));
			var valeur = params[i].substring(params[i].indexOf("=")+1, params[i].length);
			
			tab[i] = new Array(variable, valeur);
		}
		
		return tab;
	}
	else 
	{
		return null;
	}
}


//#######################################################################################################
function addAnListCart(idSpan, ean)
{
	var sessionId = GetCookie("mollatInfos","s_ID");
	var nbCartItem = GetCookie("mollatInfos","nbCartItem");
	var myXHR = new last_httpRequest("/librairie/addInCartAndList.aspx", "sessionId=" + sessionId + "&ean=" + ean + "&qte=1" , "get");
	myXHR.createRequestObject();
	myXHR.sendGetReq();

	if (isNaN(nbCartItem))
	{
		nbCartItem = 0
	}

	myXHR.xmlhttp.onreadystatechange = function()
	{
		if (myXHR.xmlhttp.readyState == 4) /* 4 : état "complete" */
		{
			document.getElementById(idSpan).innerHTML = myXHR.xmlhttp.responseText;
			UpdateUsersInfos();
		}
	}
}

//#######################################################################################################
function XHR_calculTotal(idSpan,zoneDescId)
{
	var sessionId = GetCookie("mollatInfos","s_ID");
	var myXHR = new last_httpRequest("/comptes/calculTotal.aspx", "session_Id=" + sessionId + "&zoneDescId=" + zoneDescId , "get");
	
	myXHR.createRequestObject();
	myXHR.sendGetReq();

	myXHR.xmlhttp.onreadystatechange = function()
	{
		if (myXHR.xmlhttp.readyState == 4) /* 4 : état "complete" */
		{
			document.getElementById(idSpan).innerHTML = myXHR.xmlhttp.responseText;
		}
	}		
}


//#######################################################################################################
function SelectAll(checked,formulaire)
{  
	
	if(checked)
	{
		for(i=0;i < document[formulaire].elements.length ;i++)
		{
			var e = document[formulaire].elements[i]; 
			if (e.type == 'checkbox')
			{
				e.checked = true;
			} 
		}
	}
	else
	{
		for(i=0;i < document[formulaire].elements.length ;i++)
		{
			var e = document[formulaire].elements[i]; 
			if (e.type == 'checkbox')
			{
				e.checked = false;
			} 
		}
	}
	
}


//#######################################################################################################
function verifMail(thisTxtBox)
{
	var succes = true;
	
	if ( (thisTxtBox.value != '') && (!check_email(thisTxtBox.value)) )
	{
		thisTxtBox.className = "error";
		alert('Adresse e-mail non valide');
		succes = false;
	}
	else
	{
		thisTxtBox.className = "";
	}
	
	return succes;
}


//#######################################################################################################
function verifFrmMollatLetter(txtBoxMail)
{
	if ( txtBoxMail.value != '' && verifMail(txtBoxMail) )
	{
		return true;
	}
	else
	{
		return false;
	}
}


//#######################################################################################################
function retourAchat()
{
	alert(document.cookie);
/*
	if (isLastPage && history.length > 0)
	{
		history.back();
	}
	else
	{
		document.location.href="/index.aspx";
	}
	
	isLastPage = true;	*/
}


//#######################################################################################################
/**
 * Pour le calcul des frais d'envois dans la pop-up des frais de ports (/help_modLiv.aspx) 
 * Fonction qui créée une listBox de modes de livraison en fonction d'un pays identifié par son id 
 * via un XmlHttpRequest 
 * 
 * @params	pays_id  : l'id du pays 
 **/
function fdp_loadZone(pays_id) 
{
	//alert('pays_id = ' + pays_id);
	
	if (pays_id != "") 
	{
		if (document.getElementById("fdp_cost_label")) {
			document.getElementById("fdp_cost_label").innerHTML="";
		}
		if (document.getElementById("fdp_cost_value")) {
			document.getElementById("fdp_cost_value").innerHTML="";
		}
		
		var MyXhr = new last_httpRequest("/_application/_functions/fdp_loadZone_xhr.aspx", "id=" + pays_id + "&load=mode", "get");
		MyXhr.createRequestObject();
		MyXhr.sendPostReq();

		MyXhr.xmlhttp.onreadystatechange = function()
		{
			if (MyXhr.xmlhttp.readyState == 4) 
			{
				//alert(MyXhr.xmlhttp.responseText);
				document.getElementById('fdp_div_mode').innerHTML = MyXhr.xmlhttp.responseText;
			}
		}
	}
	else 
	{
		//alert("pas de pays_id !");
		document.getElementById('fdp_div_mode').innerHTML = "";
		document.getElementById('fdp_div_cost').innerHTML = "";
	}
}


//#######################################################################################################
/**
 * Pour le calcul des frais d'envois dans la pop-up des frais de ports (/help_modLiv.aspx) 
 * Fonction qui affiche le coût d'une livraison pour un pays et un mode de livraison donné 
 * via un XmlHttpRequest 
 * 
 * @params	pays_id		:	l'id du pays 
 *			serv_id		:	l'id du mode de livraison (offre : colissimo, chronopost, ...) 
 **/
function fdp_calcFraisLivr(pays_id, serv_id, nbLivres) 
{
	if ( pays_id != "" && serv_id != "" && !isNaN(nbLivres) && nbLivres.indexOf('.') == -1 && nbLivres.indexOf(',') == -1 ) 
	{
		//alert('pays_id = ' + pays_id + '\nserv_id = ' + serv_id + '\nnbLivres = ' + nbLivres);
		
		var MyXhr = new last_httpRequest("/_application/_functions/fdp_loadZone_xhr.aspx", "id=" + pays_id + "&load=cost&servid=" + serv_id + "&nbL=" + nbLivres, "get");
		MyXhr.createRequestObject();
		MyXhr.sendPostReq();

		MyXhr.xmlhttp.onreadystatechange = function()
		{
			if (MyXhr.xmlhttp.readyState == 4) 
			{
				//alert(MyXhr.xmlhttp.responseText);
				document.getElementById('fdp_div_cost').innerHTML = MyXhr.xmlhttp.responseText;
			}
		}
		
		return true;
	}
	else 
	{
		var msg = "";
		
		if ( pays_id == "" ) {
			msg += "Vous devez s\351lectionner un pays.\n";
		}
		
		if ( serv_id == "" ) {
			msg += "Vous devez s\351lectionner un mode de livraison.\n";
		}
		
		if ( isNaN(nbLivres) || nbLivres.indexOf('.') != -1 || nbLivres.indexOf(',') != -1 ) {
			msg += "Vous devez taper un entier pour le nombre de livres.\n";
		}
		
		
		if (msg != "") {
			alert(msg);
		}
		
		return false;
	}
}


//#######################################################################################################
/**
 * A la fermeture du navigateur par l'utilisateur, lorsqu'il est sur la page /search/searchResult.aspx, 
 * cette fonction appelle un XmlHttpRequest qui permet de fermer la session Electre si elle existe : 
 */
function closeSessionElectre() 
{
	//alert('on entre bien ds la fonction closeSessionElectre()...');
	
	var MyXhr = new last_httpRequest("/_application/_functions/ElectreLogout.aspx", "", "get");
	MyXhr.createRequestObject();
	MyXhr.sendGetReq_onunload();
	
	//alert('Bye Bye Electre ! ;-)');
}


//#######################################################################################################
function verifBox()
{
	var isValid = true;
	var TitleL = document.getElementsByName('avisLibelle')[0].value.length;
	var TexteL = document.getElementsByName('txtLibelle')[0].value.length;
	var msgError = 'Attention : ';

	/* Check de la notation */
	if(document.getElementById('selectNote').value=='-1')
	{
		msgError += '\n - Veuillez attribuer une notation \340 votre avis.';
		isValid = false;
	}

	/* Check du texte */
	if(TexteL < 150)
	{
		msgError += '\n - Le texte de votre avis dois contenir au minimum 150 caract\350res.';
		isValid = false;
	}

	/* Affichage du message d'erreur */
	if(!isValid)
	{
	alert(msgError);
	}
	return isValid;
}



//#######################################################################################################
function getElementsByName_forIE(str_tag, str_name) {
     
	var elem = document.getElementsByTagName(str_tag);
	var arr = new Array();
	
	for(i = 0, iarr = 0; i < elem.length; i++) 
	{
		att = elem[i].getAttribute("name");
		if(att == str_name) {
			arr[iarr] = elem[i];
			iarr++;
		}
	}
	return arr;
}


//#######################################################################################################








