/** bibliothèque javascript pour LVA.
 * CORE
 *
 *
 *
 */    
 
//  shorthand for document.getElementById()
function gE(i) {
	return (i) ? document.getElementById(i) : null;
}

/**
* AddEvent Manager (c) 2005-2006 Angus Turnbull http://www.twinhelix.com
* Free usage permitted as long as this credit notice remains intact.

USAGE EXAMPLES
 Here, we create a new function inline to run when the document loads.
addEvent(window, 'load', new Function('document.title = "AddEvent Manager: Activated!"'));

// Here we attach a predefined function to handle document clicks.
// It's automatically passed the correct "event" object!
function showClickCoords(evt)
{
 // 'this' refers to the object to which we're attached.
 // In this case, it's the 'document' object.
 this.title = 'Last click position: X=' + evt.clientX + ', Y=' + evt.clientY;
 // To stop all clicks on the document performing an action, just do this:
 //cancelEvent(e, false);
};

addEvent(document, 'click', showClickCoords);

// And if you want to stop handling the event, just do this:
//removeEvent(document, 'click', showClickCoords);
*/

if (typeof addEvent != 'function'){
 var addEvent = function(o, t, f, l) {
  var d = 'addEventListener', n = 'on' + t, rO = o, rT = t, rF = f, rL = l;
  if (o[d] && !l) return o[d](t, f, false);
  if (!o._evts) o._evts = {};
  if (!o._evts[t])  {
   o._evts[t] = o[n] ? { b: o[n] } : {};
   o[n] = new Function('e',
    'var r = true, o = this, a = o._evts["' + t + '"], i; for (i in a) {' +
     'o._f = a[i]; r = o._f(e||window.event) != false && r; o._f = null;' +
     '} return r');
   if (t != 'unload') addEvent(window, 'unload', function() {
    removeEvent(rO, rT, rF, rL);
   });
  }
  if (!f._i) f._i = addEvent._i++;
  o._evts[t][f._i] = f;
 };
 addEvent._i = 1;
 var removeEvent = function(o, t, f, l) {
  var d = 'removeEventListener';
  if (o[d] && !l) return o[d](t, f, false);
  if (o._evts && o._evts[t] && f._i) delete o._evts[t][f._i];
 };
}


// Optional cancelEvent() function you can call within your event handlers to
// stop them performing the normal browser action or kill the event entirely.
// Pass an event object, and the second "c" parameter cancels event bubbling.
function cancelEvent(e, c){
 e.returnValue = false;
 if (e.preventDefault) e.preventDefault();
 if (c) {
  e.cancelBubble = true;
  if (e.stopPropagation) e.stopPropagation();
 }
};
// end event section
 
// general popup
var newWin = null;
function popUp(strURL, strHeight, strWidth, other) {
 if (newWin != null && !newWin.closed) newWin.close();
 var strOptions="";
 strOptions="height="+strHeight+",width="+strWidth+','+other;
 newWin = window.open(strURL, 'newWin', strOptions);
 newWin.focus();
}

/**
 *  Inspired by Sean Kane (http://celtickane.com/programming/code/ajax.php)
 *  Feather Ajax v1.0.0
 *  customised by La Mire (www.lammire.com)
 *
 *
 * usage : 
 * 
 * 
 * <script type="text/javascript" >
 * function doit(str){
 *   alert (str);
 * }
 * 
 * // ajax call helper
 * function ajaxUpdate (){
 *  var ao = new AjaxObject();
 *   ao.setCallback (doit, 'text');
 *   ao.sndReq('POST','ajax_func.php', {action:'gettext',b1:'testing'});
 * }
 * </script>
 * <input type="button" value="Click Me" onClick="ajaxUpdate();" />   
 */ 

// Ajax Object definition
function AjaxObject() {
	this.callback = null; // callback function
	this.sendXML = false; // text or xml, default to text
	
	/** public : setCallback()
	 *  fixe la fonction callback et le mode de retour des données
	 *  fn doit être du type string !
	 */   	
	this.setCallback = function (fn, mode){
		this.callback = fn;
		this.sendXML=  (mode=='xml') ? true : false;
		
	};

	/** initialise un object XMLHttp
	 *  private function - appellé à l'instanciation
	 */   	
	this.createRequestObject = function() {	
	// This is called at the very bottom -- 
  // it sets this.http to the Ajax request object (ro)
		var ro;	
		
	 try {//IE ?
			ro = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			try { ro = new ActiveXObject("Microsoft.XMLHTTP");}
      catch (e2) { ro = null;	}
		}
    // standard
		if (!ro && typeof XMLHttpRequest!='undefined') {
				ro = new XMLHttpRequest();
			}

		return ro; //instance of AjaxObject
	};
	
	/**
	 *	This function will start the Ajax process, and is called manually by the user
	 *	action is either 'get' or 'post'	
	 *	url can contain GET variables -- like myajax.php?action=test
	 *	method : GET or POST	 
	 */	 	  
	this.sndReq = function(action, url, vars) { 
		// encode datas (parameters)
		tmp = new Array();
    for (var i in vars) {
    tmp.push (encodeURIComponent(i)+'='+encodeURIComponent(vars[i])); 
   }
   // ajoute un paramètre aléatoire pour palier les pb de cache
   tmp.push ('rand'+'='+new Date().getTime());
   datas = tmp.join('&');
    //alert (url + datas);
   /*this.http.abort();*/
   
    switch (action.toUpperCase()){
    case 'GET':
      this.http.onreadystatechange = this.handleResponse; 
      this.http.open('GET',url+'?'+datas,true);
		  this.http.send(null);	
      break;
      
    case 'POST' : // default to POST
      this.http.onreadystatechange = this.handleResponse; 
      this.http.open('POST',url,true);
      // on s'assure que la requête n'est jamais mise en cache
      this.http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      this.http.setRequestHeader('If-Modified-Since',	'Sat, 29 Oct 1994 00:00:00 GMT');
      this.http.send(datas);	
    }
	
	};
	/**
	 *	This function is called when this.http's state changes
	 *	 0=uninitialized,1=loading,2=loaded,3=interactive,4=complete	 
	 */	 	
	this.handleResponse = function() { 

	
      if(me.http.readyState != 4 ) return;
      if(me.http.status != 200) alert ('Server response : '+ me.http.status + "\n" +me.http.getAllResponseHeaders());
      //alert(me.http.getAllResponseHeaders())
      var data = (me.sendXML) ? me.http.responseXML : me.http.responseText;
    //  data = eval( '('+data+')');
    //  if (me.callback!=null ) me.callback (data);
    //  else alert ('Callback function no set');
//alert( me.callback+ '('+data+');');
    eval(me.callback+ '('+data+');');
    
    
    
	};

	
	
	// constructor
	// necessary because this.http won't work in the callback
  // function 'handleResponse' (we have to use me.http instead)
	var me = this;	
	this.http = this.createRequestObject(); 

}


/**
 serialize un objet Javascript en chaine de 
 type php serialized object
boolean (variable OUI/NON),
string (variable de chaîne de caractères),
number (variable numérique),
function (fonction),
object (objet),
undefined (type indéterminé).

*/
function php_serialize(obj) {
  var tok, tmp, count;
  var typo = typeof(obj);

	switch (typo){
		case 'string': tok = 's:'+obj.length+':"'+obj+'";';
      break;
		case 'boolean': tok = (obj) ? 'b:1;': 'b:0;';
			break;
		case 'number':
			tok =  (obj - Math.floor(obj) != 0) ? 'd:'+obj+';' : 'i:'+obj+';';
			break;
		case 'function':
			tok = obj;
			break;
		case 'object':
      tmp = '';
      count = 0;		
		  if (obj instanceof Array) { // tableau avec index numériques
          for (var key in obj) {
              tmp += 'i:'+key+';'+php_serialize(obj[key]);
              count++;
          }
          tok = 'a:'+count+':{'+tmp+'}';
        } else { // tableau associatif
          for (var key in obj) {
              tmp += php_serialize(key);
              tmp += (obj[key]) ? php_serialize(obj[key]) :php_serialize('');
              count++;
          }
          tok = 'a:'+count+':{'+tmp+'}';
        }
		break;
		default : 
			tok = 's:0:"";'; // empty string
			break;

	}

    return tok;
}


/** pendant de la fonction php_serialize:
 *  unserialize une string de type php serialized object
 *
 */  
function php_unserialize2(txt){
	var level=0,arrlen=new Array(),del=0,out=new Array(),key=new Array(),save=txt;
	while(1){
		switch(txt.substr(0,1)){
		case 'N':
			del = 2;
			ret = null;
		break;
		case 'b':
			del = txt.indexOf(';')+1;
			ret = (txt.substring(2,del-1) == '1')?true:false;
		break;
		case 'i':
			del = txt.indexOf(';')+1;
			ret = Number(txt.substring(2,del-1));
		break;
		case 'd':
			del = txt.indexOf(';')+1;
			ret = Number(txt.substring(2,del-1));
		break;
		case 's':
			del = txt.substr(2,txt.substr(2).indexOf(':'));
			ret = txt.substr( 1+txt.indexOf('"'),del);
			del = txt.indexOf('"')+ 1 + ret.length + 2;
		break;
		case 'a':
			del = txt.indexOf(':{')+2;
			ret = new Array();
			arrlen[level+1] = Number(txt.substring(txt.indexOf(':')+1, del-2))*2;
		break;
		case '}':
			txt = txt.substr(1);
			if(arrlen[level] != 0){alert('var missed : '+save); return undefined;};
			//alert(arrlen[level]);
			level--;
		continue;
		default:
			if(level==0) return out;
			alert('syntax invalid(1) : '+save+"\nat\n"+txt+"level is at "+level);
			return undefined;
		}
		if(arrlen[level]%2 == 0){
			if(typeof(ret) == 'object'){alert('array index object no accepted : '+save);return undefined;}
			if(ret == undefined){alert('syntax invalid(2) : '+save);return undefined;}
			key[level] = ret;
		} else {
			var ev = '';
			for(var i=1;i<=level;i++){
				if(typeof(key[i]) == 'number'){
					ev += '['+key[i]+']';
				}else{
					ev += '["'+key[i]+'"]';
				}
			}
			eval('out'+ev+'= ret;');
		}
		arrlen[level]--;//alert(arrlen[level]-1);
		if(typeof(ret) == 'object') level++;
		txt = txt.substr(del);
		continue;
	}
}

/**
 *	défini un objet form select.
 *	method reset() : vide le select box
 *	method disable() : désactive le select box  
 *  method getSelectedOption() : retourne l'option choisie (unique)
 *  method getAllSelectedOption() : retourne le tableau des options choisies
 *  method populate : remplit la select box avec les valeurs passées
 *   
*/
 
 
function form_select(e){
	var elt;
	var def_option = {'' : '-'};


	/** reset select to default value 
	*/	
	this.reset = function () {
		// nota: voir référence http://www.quirksmode.org/js/options.html
		this.elt.options.length = 0;
		this.populate(this.def_option);
		this.disable();
	};
	
	this.disable = function(flag){
		this.elt.disabled = flag;
	};
	
	/**  renvoie null ou la première options sélectionnée
		ne fonctionne pas pour les sélections multiples 
	*/
	this.getSelectedOption = function () {
	    var options = this.elt.options;
	    var selected = null;
	
	    for(var i = 0; i < options.length; i++) {
	        if(options[i].selected) {
				selected = options[i].value;
				break;
	        }
	     }
	    return selected;
	};
	
	/**  renvoie un tableau des options sélectionnées
		(sélections multiples)
	*/
	this.getAllSelectedOption = function () {
	    var options = this.elt.options;
	    var selected = new Array();
	
	    for(var i = 0; i < options.length; i++) {
	        if(options[i].selected) selected.push (options[i].value);
	     }
	    return selected;
	};
	
	/** ajoute des options aux options existantes
	* @param (object) o : tableau de valeurs {value : label}
	*/
	this.populate = function (o,sel) {
		var n = this.elt.options.length;
		for (var i in o){
		this.elt.options[n] = new Option( o[i],i,i==sel,i==sel);
		 n++;
		}
	};
	
	this.elt = e;
	}
// decode mail (fonctionne de pair avec la fonction PHP mail_encode dans lib/functionslib)
function mail_decode(st,lab,xk,html){
	if (!html) html='';
  var r="";for(i=0;i<st.length;i++)r+=String.fromCharCode(xk^st.charCodeAt(i));
	document.write ('<a href="mailto:'+r+'" '+html+'>'+lab+'</a>');
}
function showSogeBlock(s){
	   	var e = document.getElementById('sogeBlock');
	   	if (!s) e.style.display = "none";
		}
function check(){
		var frm = document.forms["box"];
	   	if  (frm.cdv.checked == 1){
			var e = document.getElementById('sogeBlock');
			e.style.display = "block";
		}
		else alert("Veuillez confirmer que vous avez bien pris connaissance de nos conditions générales de vente ");
	
		 }
function checkgratuit(){
		var frm = document.forms["box"];
	   	if  (frm.cdv.checked == 1){
			return true;
		}
		else { alert("Veuillez confirmer que vous avez bien pris connaissance de nos conditions générales de vente ");
			return false;
		 }
		 }
function ajouterchamp(i)	{dom.insert("ajoutnode","p","pemail"+i);dom.createInput("pemail"+i,"texte","email"+i,"email"+i);dom.insert("email"+i,"label","lemail"+i);$('lemail'+i).innerHTML="Adresse e-mail "+i; }