// Usage : addEvent(window, 'load', doSomeStuff);
function addEvent(obj, evType, fn, useCapture){
	if (obj.addEventListener){
		obj.addEventListener(evType, fn, useCapture);
		return true;
	} else if (obj.attachEvent){
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	} else { /* unsuported browser, e.g. NS4 or IE5Mac */ }
}
// Usage : removeEvent(window, 'load', doSomeStuff);
function removeEvent(obj, evType, fn, useCapture){
	if (obj.removeEventListener){
		obj.removeEventListener(evType, fn, useCapture);
		return true;
	} else if (obj.detachEvent){
		var r = obj.detachEvent("on"+evType, fn);
		return r;
	} else { /* unsuported browser, e.g. NS4 or IE5Mac */ }
}

/*	IsNumeric - true for all numeric, false if not*/
function isNumeric(PossibleNumber){	
   var PNum = new String(PossibleNumber);
   var regex = /[^0-9]/;
   return !regex.test(PNum);
}

// Pour limiter la longeur entree dans les textarea...
// (marche egalement pour les input, mais maxlength est deja defini dans ce cas)
// utilisation : ajouter onblur="maxlength(this, 250);" au textarea
function maxlength(element, maxvalue) {
	var q = element.value.length;
	var r = q - maxvalue;
	/*
	var msg = "Sorry, you have input "+q+" characters into the "+
		"text area box you just completed. It can return no more than "+
		maxvalue+" characters to be processed. Please abbreviate "+
		"your text by at least "+r+" characters.";
	*/
	var msg = "Taille de texte trop importante ! Supression des " + r + " derniers caracteres."
	if (q > maxvalue) {
		alert(msg);
		element.value = element.value.substring(0, maxvalue);
	}
}


// Recherche le formulaire contenant l'?l?ment d'id donn?
function findForm(formSubElementId) {
	var formSubElement = document.getElementById(formSubElementId);
	while (formSubElement != null && formSubElement.nodeName != "FORM") {
		formSubElement = formSubElement.parentNode;
	}
	return formSubElement;
}



// Ajoute un handler ? tous les liens a du document.
// Pour g?rer une liste d'exception, enlever le handler pass? apr?s avoir appel? cette fonction :
//   obj.removeEventListener(type, listener, useCapture)
// Utilisation : addTagHandler(window, 'a', 'click', doSomeStuff)
// TODO
function addTagHandler(obj, tagName, eventType, handler) {
	alert("addTagHandler() is not implemented!");
	var allTags = document.getElementsByTagName(tagName);
	for (i = 0; i < allTags.length; i++) {
		var tag = allTags[i];
		alert(tag.nodeName + ' ' + tag.nodeValue);
		addEvent(tag, eventType, handler);
	}
}




/*
 * Gestion des listes produit.
 * Utilisation :
 * avant d'afficher la liste des produits, ins?rer un
<script type="text/javascript"><!--
	addEvent(window, 'beforeunload', onExitProductList('${pageContext.request.contextPath}'));
//-->
 */
var modifiedProductsCode = new Array();
var modifiedProductsQuantity = new Array();
var currentContextPath;
var needConfirmation = true;

function addModifiedProduct(code, quantity) {
  addModifiedProductExtended(code, quantity, true);
}
function removeModifiedProduct(code) {
	for (i = 0; i < modifiedProductsCode.length; i++) {
		if (modifiedProductsCode[i] == code) {
			var temp1 = modifiedProductsCode.slice(0,i);
			var temp2 = modifiedProductsCode.slice(i+1,modifiedProductsCode.length);
			
			if(i==0) {
				modifiedProductsCode = temp2;
			} else {
				modifiedProductsCode = temp1;
				modifiedProductsCode.concat(temp2);
			}
			
			temp1 = modifiedProductsQuantity.slice(0,i);
			temp2 = modifiedProductsQuantity.slice(i+1,modifiedProductsQuantity.length);
			if(i==0) {
				modifiedProductsQuantity = temp2;
			} else {
				modifiedProductsQuantity = temp1;
				modifiedProductsQuantity.concat(temp2);
			}
		}
	}
}
function addModifiedProductExtended(code, quantity, overwriteProduct) {    
	for (i = 0; i < modifiedProductsCode.length; i++) {
		if (modifiedProductsCode[i] == code) {
		    if (overwriteProduct) {
 			  modifiedProductsQuantity[i] = quantity;
 			}
			return;
		}
	}
	var currentModifiedProductIndex = modifiedProductsCode.length;
	modifiedProductsCode[currentModifiedProductIndex] = code;
	modifiedProductsQuantity[currentModifiedProductIndex] = quantity;
}
function onExitProductList(context, theNeedConfirmation) {
	if (theNeedConfirmation != undefined) {
		needConfirmation = theNeedConfirmation;
	}
	currentContextPath = context;
	return onExitProductList2;
}
function onExitProductList2() {
	// V?rifie si toutes les quantit?s sont ? quantiteMiniProduit
	// et alerte l'utilisateur si non
	if (modifiedProductsCode.length > 0){
		var modified = false;
		for (i = 0; i < modifiedProductsQuantity.length; i++) {
			if (modifiedProductsQuantity[i] > 0) {
				modified = true;
				break;
			}
		}
		if (modified) {
			var choice = !needConfirmation || window.confirm('Vous avez choisi ' + modifiedProductsCode.length + ' produit(s) sans cliquer sur Ajouter.'
				+ '\nCliquez sur OK pour les ajouter \340 votre panier, sinon cliquez sur Annuler.');
			if (choice) {
				var codesString = '';
				var quantitiesString = '';
				for (i = 0; i < modifiedProductsCode.length; i++) {
					codesString += (codesString=='')?'':'&';
					codesString += 'productCode=' + modifiedProductsCode[i];
					quantitiesString += (quantitiesString=='')?'':'&';
					quantitiesString += 'quantite=' + modifiedProductsQuantity[i];
				}
				var url = currentContextPath + "/AJAXAjoutPanier.shtml?" + codesString + "&" + quantitiesString;
				RPC_callToServer(url);
				for (i=0; i<300000; i++);
			}
			return choice;
		}
	}
}
function serialiserCodes() {
  var resultat = '';
  for (i = 0; i < modifiedProductsCode.length; i++) {
    if ( modifiedProductsCode[i] != undefined ) {
      resultat = resultat + modifiedProductsCode[i] + ';';
    }
  }
  resultat = resultat.substring(0, resultat.length-1);
  return resultat;
}

function serialiserQuantites() {
  var resultat = '';
  for (i = 0; i < modifiedProductsQuantity.length; i++) {
    if ( modifiedProductsQuantity[i] != undefined ) {
      resultat = resultat + modifiedProductsQuantity[i] + ';';
    }
  }
  resultat = resultat.substring(0, resultat.length-1);  
  return resultat;  
}

function flushCodes() {
  while (modifiedProductsCode.length > 0 ) {
    modifiedProductsCode.pop();
  }
}

function  flushQuantity() {
  while (modifiedProductsQuantity.length > 0 ) {
	modifiedProductsQuantity.pop();
  }
}
        


/* Appels RPC
 * Source : <http://developer.apple.com/internet/webcontent/iframe.html>
 * Principe : un appel serveur "en tache de fond" remplit un iframe avec une page contenant du code JavaScript
 * Autre possibilite a etudier : <http://developer.apple.com/internet/webcontent/xmlhttpreq.html>
 */
var IFrameObj; // our IFrame object
function RPC_callToServer(theUrl) {
  if (!document.createElement) {return true};
  var IFrameDoc;
  if (!IFrameObj && document.createElement) {
    // create the IFrame and assign a reference to the
    // object to our global variable IFrameObj.
    // this will only happen the first time 
    // callToServer() is called
   try {
      var tempIFrame=document.createElement('iframe');
      tempIFrame.setAttribute('id','RSIFrame');
      tempIFrame.style.border='0px';
      tempIFrame.style.width='0px';
      tempIFrame.style.height='0px';
      // Don't use display:none, because NS6 ignores IFRAMEs when the display property is set to none.
      tempIFrame.style.visibility="hidden";//Cedrik add
      IFrameObj = document.body.appendChild(tempIFrame);
      
      if (document.frames) {
        // this is for IE5 Mac, because it will only
        // allow access to the document object
        // of the IFrame if we access it through
        // the document.frames array
        IFrameObj = document.frames['RSIFrame'];
      }
    } catch(exception) {
      // This is for IE5 PC, which does not allow dynamic creation
      // and manipulation of an iframe object. Instead, we'll fake
      // it up by creating our own objects.
      iframeHTML='<iframe id="RSIFrame" style="';
      iframeHTML+='border:0px;';
      iframeHTML+='width:0px;';
      iframeHTML+='height:0px;';
      // Don't use display:none, because NS6 ignores IFRAMEs when the display property is set to none.
      iframeHTML+='visibility:hidden;';//Cedrik add
      iframeHTML+='"><\/iframe>';
      document.body.innerHTML+=iframeHTML;
      IFrameObj = new Object();
      IFrameObj.document = new Object();
      IFrameObj.document.location = new Object();
      IFrameObj.document.location.iframe = document.getElementById('RSIFrame');
      IFrameObj.document.location.replace = function(location) {
        this.iframe.src = location;
      }
    }
  }
  
  if (navigator.userAgent.indexOf('Gecko') !=-1 && !IFrameObj.contentDocument) {
    // we have to give NS6 a fraction of a second
    // to recognize the new IFrame
    setTimeout('RPC_callToServer()',10);
    return false;
  }
  
  if (IFrameObj.contentDocument) {
    // For NS6
    IFrameDoc = IFrameObj.contentDocument; 
  } else if (IFrameObj.contentWindow) {
    // For IE5.5 and IE6
    IFrameDoc = IFrameObj.contentWindow.document;
  } else if (IFrameObj.document) {
    // For IE5
    IFrameDoc = IFrameObj.document;
  } else {
    return true;
  }
  
  //Cedrik add
  if (theUrl.toLowerCase().substr(0, 4) != "http") {
    var prefix = window.location.protocol + "//" + window.location.host;
    if (theUrl.charAt(0) != '/') {
      prefix = prefix + '/';
    }
    theUrl = prefix + theUrl;
  }
  IFrameDoc.location.replace(theUrl);
  return false;
}
function RPC_buildQueryStringForFormName(theFormName) {
  theForm = document.forms[theFormName];
  return RPC_buildQueryStringForForm(theForm);
}
function RPC_buildQueryStringForForm(theForm) {
  var qs = '';
  for (e=0;e<theForm.elements.length;e++) {
    if (theForm.elements[e].name!='') {
      qs+=(qs=='')?'':'&';//Cedrik change (remove '?')
      qs+=theForm.elements[e].name+'='+escape(theForm.elements[e].value);
      }
    }
  return qs
}




/* Appel RPC (take 2)
 * Source : http://homepage.mac.com/kevinmarks/staticjah.html
 * Principe : remplacement d'un element html nomme par un contenu dynamique (appel serveur en tache de fond)
 * See also: <http://developer.apple.com/internet/webcontent/xmlhttpreq.html>
 * Note :
It is essential that the data returned from the server be sent with a Content-Type set to text/xml.
Content that is sent as text/plain or text/html is accepted by the instance of the request object
however it will only be available for use via the responseText property.
 * Usage :
With all the AJAX excitement, it's worth pointing out a simple technique
I call JAH - which can be Just Async HTML, or Javascript Async HTML to taste.

This works on the microformat principle that XHTML is XML, but with the
added advantage that Javascript already knows how to handle XHTML DOM's
so no xml parsing is required.

You just include <script type="text/javascript" language="javascript1.3" src="jah.js"></script>
in the <head> and then link to dynamic pages with
<a href="javascript:jah('kevin.html','target');">kevin</a>
where target is the id of the HTML element you want to replace.
 */
// global request and XML document objects
var req;

//AKA loadXMLDoc(url, target)
function jah(url,target) {
    //Cedrik add
    if (url.toLowerCase().substr(0, 4) != "http") {
        var prefix = window.location.protocol + "//" + window.location.host;
        if (url.charAt(0) != '/') {
            prefix = prefix + '/';
        }
        url = prefix + theUrl;
    }
    // native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        // onreadystatechange: Event handler for an event that fires at every state change
        req.onreadystatechange = jahDone;
        req.target=target;
        //syntax: open("method", "URL"[, asyncFlag[, "userName"[, "password"]]])
        req.open("GET", url, true);
        req.send(null);
    // IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        try {
            req = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (error) {
            req = new ActiveXObject("Msxml2.XMLHTTP");
        }
        if (req) {
            req.onreadystatechange = jahDone;
            req.target=target;
            req.open("GET", url, true);
            req.send();
        }
    }
}    

//AKA processReqChange()
function jahDone() {
    // only if req is "loaded"
    /*	Object status integer:
		0 = uninitialized
		1 = loading
		2 = loaded
		3 = interactive
		4 = complete
     */
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
        	// ...processing statements go here...
            results = req.responseText;
            document.getElementById(req.target).innerHTML = results;
        } else {
			//alert("There was a problem retrieving the XML data:\n" +
            //    req.statusText);
            document.getElementById(req.target).innerHTML="jah error:\n" +
                req.statusText;
        }
    }
}

// fonction permettant la validation des champs dans les formulaires de saisi produit recap
function miseAJourProduit(field, quantiteInitial) {
	field.value = field.value-0+0;
	if (field.value == 'NaN') {
		field.value = quantiteInitial;
	}
	if(field.value!=quantiteInitial) field.form.submit();
}

// fonction d'ajout pour les push produit
function ajouterQuantiteEcensity(field, quantity, quantiteMin, quantiteMax) {
	ajouterQuantite(field, quantity, quantiteMin, quantiteMax, false, 0, false);
}

function ajouterQuantite(field, quantity, quantiteMin, quantiteMax, dejaDansPanier, iteration) {
	ajouterQuantiteGenerale(field, quantity, quantiteMin, quantiteMax, dejaDansPanier, iteration, false);
}

// fonction d'ajout pour les listes de produits
function ajouterQuantiteGenerale(field, quantity, quantiteMin, quantiteMax, dejaDansPanier, iteration, acceptZero) {
	var codeProduit = field.form.codeProduitPanier.value;
	
	field.value = field.value-0+quantity;
	if(acceptZero) {
		if (field.value < quantiteMin) {
			field.value = 0;
		}
	} else {
		if (field.value < quantiteMin) {
			field.value = quantiteMin;
		}
	}
	if (quantiteMax != 0 && field.value > quantiteMax) {
		field.value = quantiteMax;
	}
	if (field.value == 'NaN') {
		field.value = quantiteMin;
	}
	
	var theDiv = document.getElementById('ligneProduit-'+iteration);
	if(theDiv!=null) {
		if(dejaDansPanier) {
			theDiv.style.backgroundColor = '#ffeedb';
		} else {
			theDiv.style.backgroundColor = '#eeffdb';
		}
	}
	
	if(!dejaDansPanier) {
		var theText = document.getElementById('texteproduit-'+iteration);
		if(theText!=null) {
			theText.style.color = '#88c445';			
			if (field.value > 0) {
			  theText.innerHTML = 'cliquez pour en ajouter ' + field.value;
			} else {
			  theText.innerHTML = '';
			}
		}
	}
	
	addModifiedProduct(codeProduit, field.value);
}

function removeQuantiteProduit(form) {
	var codeProduit = form.codeProduitPanier.value;
	
	removeModifiedProduct(codeProduit);
}

function isNavigatorPlus() {
	var agt=navigator.userAgent.toLowerCase();

    var is_opera = (agt.indexOf("opera") != -1);
    var is_konq = (agt.indexOf('konqueror') != -1);
    var is_khtml  = (is_safari || is_konq);
    var is_ie   = ((agt.indexOf('msie 6') != -1) && (!is_opera) && (!is_khtml));
    
    return is_ie || is_opera;
}

// fonction permettant le resize des fenetres
function getWindowHeight() {
	var windowHeight = 0;
	if (typeof(window.innerHeight) == 'number') {
		windowHeight = window.innerHeight;
	} else {
		if (document.documentElement && document.documentElement.clientHeight) {
			windowHeight = document.documentElement.clientHeight;
		} else {
			if (document.body && document.body.clientHeight) {
				windowHeight = document.body.clientHeight;
			}
		}
	}
	return windowHeight;
}

function getWindowWidth() {
	var windowWidth = 0;
	if (typeof(window.innerWidth) == 'number') {
		windowWidth = window.innerWidth;
	} else {
		if (document.documentElement && document.documentElement.clientWidth) {
			windowWidth = document.documentElement.clientWidth;
		} else {
			if (document.body && document.body.clientWidth) {
				windowWidth = document.body.clientWidth;
			}
		}
	}
	return windowWidth;
}

function resizeSet(data,hauteur,largeur,min) {
	var element = document.getElementById(data);
	if(data=="panier") hauteur = hauteur - (isNavigatorPlus()?10:0);
	if(element!=null) {
		if(largeur>0) {
			element.style.width=largeur+ "px";
		}
		if(hauteur>min) {
			element.style.height=hauteur+ "px";
		} else {
			element.style.height=min+ "px";
		}
	}
}

function TableauSize() {
	this.nb = 0;
	this.add = addSizeur;
}

function Sizeur(name,hauteur,largeur,hauteurMin) {
	this.name = name;
	this.hauteur = hauteur;
	this.largeur = largeur;
	this.hauteurMin = hauteurMin; 
}

function addSizeur(name,hauteur,largeur,hauteurMin) {
	this[this.nb] = new Sizeur(name,hauteur,largeur,hauteurMin);
	this.nb++;
}



function setResize(tableau) {
	if (document.getElementById) {
		var windowHeight=getWindowHeight();
		var windowWidth=getWindowWidth();
		for(i=0;i<tableau.nb;i++) {
			try {
				var hauteur = windowHeight - tableau[i].hauteur;
				if(tableau[i].hauteur==0) hauteur = 0;
				var largeur = windowWidth - tableau[i].largeur;
				if(tableau[i].largeur==0) largeur = 0;
				resizeSet(tableau[i].name,hauteur,largeur,tableau[i].hauteurMin);
			} catch(e) {
			}
		}
		var element = document.getElementById("page");
		if(element!=null) {
			if(windowWidth<900) element.style.width = 900+"px";
			else element.style.width = windowWidth+"px";
		}
	}
}

function submitOnEnter(event,form) {
	if (event.keyCode==13) {
		form.submit();
		return false;
	} else {
		return true;
	}
}

function rollOverAttente(oldTag, newTag) {
	var test1 = document.getElementById("avantChargement");
    var test2 = document.getElementById("attenteChargement");
	if(test1!=null&&test2!=null) {
		test1.style.display = "none";
		test2.style.display = "block";
	}
}

function rollOverWithName(nameTag) {
	try {
		var test = document.getElementById(nameTag);
		if(test!=null) {
			if(test.style.display=='none') test.style.display = 'block';
			else test.style.display='none';
		}
	} catch (erreur) {}
}

function changeListe(theForm) {
	if (theForm.numero[theForm.numero.selectedIndex].value == -1) {
		theForm.name.style.display='block';
	} else {
		theForm.name.style.display='none';
	}
}