window.onload = function (){
	
	//document.getElementById('cartBoxSwitched').style.height = 0;
	toggleMethod = "down";
	
	//BOF:menu JS
	$$('#dropDownMenu ul li.rootNode').each(function(element) {
		Tree.initV2(element);
	});
	
	//custom SelectBoxes
	nb_select_box = 0;
	$$('.selectBox').each(function(element) {
		SelectBox.init(element);
	});
	
	//hides ajaxCart delete checkboxes when ajaxCar is enabled
	$$('input.tohide').each(function(element){
		element.style.display = "none";
	});
	
	//create hover style for submit buttons
	$$('.submitBt').each(function(element){
		element.onmouseover = function(){
			this.style.backgroundPosition = "0 -22px";
		};
		element.onmouseout = function(){
			this.style.backgroundPosition = "0px 0px";
		};
	});
	
	//on désactive l'edition à la main des champs quantité (modifiable uniquement avec les fleche + et -)
	$$('input.qty_field').each(function(element){
		element.setAttribute("readonly","readonly");
	});
	
}

//LOG FONCTION by bixi; log on Firefox, alert on IE :
function log(obj){
	(document.all)
		? alert(obj)
		: console.log(obj);
}


function addEvent(obj,event,fct)
{
        if( obj.attachEvent)
                obj.attachEvent('on' + event,fct);
        else
                obj.addEventListener(event,fct,true);
}


function submitHover(obj){
	obj.className += " hover";
	/*backgroundImage = 'url(/img/bg_submit_search_field.png)';
	obj.style.backgroundRepeat = 'no-repeat';
	obj.style.backgroundPosition = '0 -18px';*/
}

function submitNormal(obj,classe){
	obj.className = classe;
	/*obj.style.backgroundImage = 'url(/img/bg_submit_search_field.png)';
	obj.style.backgroundRepeat = 'no-repeat';
	obj.style.backgroundPosition = '0 0px';*/
}


function CCollection() {
/* --CCollection object-- */
     var lsize = 0;

     this.add = _add;
     this.remove = _remove;
     this.isEmpty = _isEmpty;
     this.size = _size;
     this.clear = _clear;
     this.clone = _clone;

     function _add(newItem) {
     /* --adds a new item to the collection-- */
          if (newItem == null) return;

          lsize++;
          this[(lsize - 1)] = newItem;
     }

     function _remove(index) {
     /* --removes the item at the specified index-- */
          if (index < 0 || index > this.length - 1) return;
          this[index] = null;

          /* --reindex collection-- */
          for (var i = index; i <= lsize; i++)
               this[i] = this[i + 1];

          lsize--;
     }

     function _isEmpty() { return lsize == 0 }     /* --returns boolean if collection is/isn't empty-- */

     function _size() { return lsize }     /* --returns the size of the collection-- */

     function _clear() {
     /* --clears the collection-- */
          for (var i = 0; i < lsize; i++)
               this[i] = null;

          lsize = 0;
     }

     function _clone() {
     /* --returns a copy of the collection-- */
          var c = new CCollection();

          for (var i = 0; i < lsize; i++)
               c.add(this[i]);

          return c;
     }
}

//class ajaxCart
var AjaxCart = function(){
	
	return{
		//fonction de mise a jour du panier (en mémoire)
		getNewCart : function(obj,_id,_name,_image,Xsell){
			
			//attributs
			products_id = _id;
			products_name = _name;
			products_image = _image;
			products_quantity = $('products_quantity').value; 
			
			//displays loader
			$('submitCart').style.background = 'url(/img/ajax-loader.gif) no-repeat bottom center"';
			
			
			//l'ajout du produit fait référence à un produit associé.
			if(Xsell != ''){
				new Ajax.Request('?action=buy_now&products_id='+ _id,{
					method: 'post',
					asynchronous: true,
					contentType:  'application/x-www-form-urlencoded',
					encoding:     'ISO-8891-1',
					//parameters: Form.serialize(obj), //sends all $_post vars
					//everything's OK, updating the cartBox display :
					onSuccess: function(){
						AjaxCart.display_cartNewProductBox();
					}, 
					onFailure: function(){
						alert("Erreur lors de l'ajout du produit au panier. Le produit n'a pu être ajouté.");
						return false;
					}
				});
			}
			//on ajoute un produit via sa page de details (formulaire complet)
			else{
				new Ajax.Request('ajax_cart.php?action=add_product',{
					method: 'post',
					asynchronous: true,
					contentType:  'application/x-www-form-urlencoded',
					encoding:     'ISO-8891-1',
					parameters: Form.serialize(obj), //sends all $_post vars
					//everything's OK, updating the cartBox display :
					onSuccess: function(){
						AjaxCart.display_cartNewProductBox();
					}, 
					onFailure: function(){
						alert("Erreur lors de l'ajout du produit au panier. Le produit n'a pu être ajouté.");
						return false;
					}
				});
			}
			return false;
		},
	
		//mise à jour de l'affichage du panier sur le site
		updateDisplayCart : function (){
			response = new Ajax.Request("/ajaxGetShoppingCart.php",{
				method: 'get',
				asynchronous: true,
				contentType:  'text/html',
				encoding:     'ISO-8891-1',
				parameters: { },
				onSuccess: function(transport){
					$('cartBox').innerHTML = transport.responseText;
				}, 
				onFailure: function(){
					//la mise a jour de l'affichage du panier à échouer.. cependant un produit a bien été commander! on raffraichi donc la page pour afficher le bon panier.
					document.location = "/index.php";
				}
			});
		},
		
		display_cartNewProductBox : function (){

			//alimentation de la div
			$('cartNewProductBox').innerHTML = "<p>"+products_name+'<br /><img src="/images/'+products_image+'" title="'+products_name+'" alt="'+products_name+'" /><br /></p>';
			
			//récupération de la hauteur de la div tout juste alimentée
			dest_height= $('cartNewProductBox').scrollHeight;
			if(dest_height <= 229) dest_height = 229;
			
			//affichage de la div
			new Effect.Morph('cartNewProductBox',{
						style:"height:"+dest_height+"px;",
						duration: 1,
						transition:Effect.Transitions.EaseFromTo,
						beforeStart:function (){
							$('submitCart').style.background = 'transparent url(/img/spr_add_to_cart.gif) no-repeat';
							$('cartNewProductBox').style.display = "block";
						},
						afterFinish: function(){
							speed_anim = (document.all) ? 500 : 0 ;
							 setTimeout('AjaxCart.hide_cartNewProductBox()',speed_anim); //
						}
					});
		},
		
		hide_cartNewProductBox : function (){
			
			//affichage de la div
			new Effect.Morph('cartNewProductBox',{
						style:"height:0px;",
						duration: 1,
						transition:Effect.Transitions.EaseFromTo,
						afterFinish: function (){
							$('cartNewProductBox').style.display = "none";
							AjaxCart.updateDisplayCart(); //mise à jour de l'affichage du panier.
						}
					});
		},
		
		deleteProduct : function (cart_id,txt_confirm) {
		    if (confirm (txt_confirm)){
		        cartidcorrection = cart_id;
		        for ( i=0; i<this.cartidcorrectif; i++ ) {
		            if ( this.cartidhystory[i+1] < cart_id ) {
		                 cartidcorrection--;
		            }
		        }   
					
				response = new Ajax.Request("ajax_cart.php",{
					method: 'get',
					asynchronous: true,
					contentType:  'text/html',
					encoding:     'ISO-8891-1',
					parameters: {cart_id : escape(cartidcorrection)},
					onSuccess: function(transport,json){
						//delete the product node (+separator node) and regenerating sub-total value :
						divProduct = $('ajaxcartProduct'+cart_id);
						divProduct.parentNode.removeChild(divProduct);
						productsCartSeparator = $('productsCartSeparator'+cart_id);
						productsCartSeparator.parentNode.removeChild(productsCartSeparator);
						
						//subtotal new value
						$('ajaxcartSubTotalValue').innerHTML = json.subtotal;
						  
						//if there's no more product in the cart.. we can display a warning message
						var myProducts = document.getElementsByClassName("cartProduct");
						
						if (myProducts.length <= 0){
							var html = '<div class="infoText">Votre panier est vide </div><div class=""><a id="back_button" style="background-position: 0px; margin-right:10px;" class="submitBt keepon_shopping" href="/index.php">Continuer</a></div>';
							(document.all)
								?	$('cart_quantity').innerText = html
								:   $('cart_quantity').innerHTML = html;
								
								//réactivation of the back link
								$('back_button').style.backgroundPosition = "0 -22px";
								$('back_button').onmouseover = function(){
									this.style.backgroundPosition = "0 -22px";
								};
								$('back_button').onmouseout = function(){
									this.style.backgroundPosition = "0px 0px";
								};
						}
		
						AjaxCart.updateDisplayCart();
					}, 
					onFailure: function(){
						//la mise a jour de l'affichage du panier à échouer.. cependant un produit a bien été commander! on raffraichi donc la page pour afficher le bon panier.
						document.location = "/shopping_cart.php";
					}
				});
					  
				return true;
		    } else {
		        var cartCheckId = 'cart_delete'+cart_id;
		        eval("document.getElementById('cart_quantity')[\""+cartCheckId+"\"].checked = false;");
				return false;
		    }
		},
		
		file : function (fichier){
		   if(window.XMLHttpRequest) // FIREFOX
		      xhr_object = new XMLHttpRequest();
		   else if(window.ActiveXObject) // IE
		      xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
		   else
		      return(false);
		   xhr_object.open("GET", fichier, false);
		   xhr_object.send(null);
		   if(xhr_object.readyState == 4)
		      return(xhr_object.responseText);
		   else return(false);
		},
		
		/*QtyNumber : function(obj,i,orig_number){
			if(obj.value != orig_number)
				$("validateQtyProd"+i).style.display = "block";
			else
				$("validateQtyProd"+i).style.display = "none";
		},*/
		
		QtyUp : function (i/*,orig_number*/){
			if(i != "products_quantity"){
				var inputCart = $("cartQty"+i);
				inputCart.value++;
				
				/*if(orig_number != inputCart.value)
					$("validateQtyProd"+i).style.display = "block";
				else
					$("validateQtyProd"+i).style.display = "none";*/
			}
			else{
				$(i).value++;
			}
		},
		
		QtyDown : function (i, minimum/*,orig_number*/){
			if(i != "products_quantity"){
				var inputCart = $("cartQty"+i);
				if((inputCart.value - 1) <= minimum){
					inputCart.value = minimum;
					if($("cart_delete"+i).onclick() == false)
						inputCart.value++;
				}
				else{
					inputCart.value--;
					/*if(orig_number != inputCart.value)
						$("validateQtyProd"+i).style.display = "block";
					else
						$("validateQtyProd"+i).style.display = "none";*/
				}
			}
			else{
				if(($(i).value - 1) <= minimum){
					$(i).value = minimum;
				}
				else{
					$(i).value--;
				}
			}
		},
		
		updateQty : function (cart_id, callback) {

			//ajaxLoader
			$("ajaxLoaderQtyProd"+cart_id).className = "ajaxLoaderQtyProdLoading";
			
			//callback
			AjaxCart[callback](cart_id,0);
			//callback
			
			
		    var cartQtyId = 'cartQty'+cart_id;
			
		    eval("var cartQty = document.getElementById('cart_quantity')[\""+cartQtyId+"\"].value;");
		    if ( cartQty > 0) {
		        cartidcorrection = cart_id;
		        for ( i=0; i<this.cartidcorrectif; i++ ) {
		            if ( this.cartidhystory[i+1] < cart_id ) {
		                 cartidcorrection--;
		            }
		        }

	            //response = new Ajax.Request(ajax_file_url,{
				response = 	new Ajax.Request('ajax_cart.php',{
					method: 'get',
					asynchronous: true,
					contentType:  'text/html',
					encoding:     'ISO-8891-1',
					parameters: {
						cart_id : escape(cartidcorrection),
						product_qty : eval(cartQty)
					},
					onSuccess: function(transport,json){
						//log("success ");

						
						 //subtotal new value
						$('ajaxcartSubTotalValue').innerHTML = json.subtotal;
						
						//quantity newvalue
						$('cartQty'+cart_id).value = json.quantity;
						
						//price newvalue
						$('ajaxcartPrice'+cart_id).innerHTML = json.price;
						
						//product name + options + stock check
						$('stockCheck'+cart_id).innerHTML = json.stock_check;
						
						//legend message out of stock
						$('out_of_stock_msg').innerHTML = json.stock_check2;
						
						AjaxCart.updateDisplayCart();
						$$('input.tohide').each(function(element){
							element.style.display = "none";
						});
						
						$("ajaxLoaderQtyProd"+cart_id).className = "ajaxLoaderQtyProd";
					}, 
					onFailure: function(){
						//la mise a jour de l'affichage du panier à échouer.. cependant un produit a bien été commandé! on raffraichi donc la page pour afficher le bon panier.
						document.location = "/shopping_cart.php";
						log("failure ");
					},
					afterFinish: function(){
						//ajaxLoader
						
						
					}
				});
		    }
		}
		
	};
}();

/* gestion du menu categories -------------------------------------------------------*/
var Tree = function() {
	return {
		/*version 1 : all sub-caegories hidden */
		initV1 : function(element, version) {
			
			if($(element).childNodes[2]){
				//IAmHere class corespond au fil d'ariane.. on ne cache pas les sous-menu faisant parti de l'arborescence de la page dans laquelle on se trouve.
				if(element.firstChild.firstChild.className != "IAmHere") {
					$(element).childNodes[2].className = 'parent_closed'; //hiding all sub-categories
				}
				else{
					$(element).childNodes[2].className = 'parent_opened';
				}
				$(element).childNodes[0].href ="#1";
				$(element).childNodes[0].onclick = function() {  //add onclick event
					if(element.className == "rootNode" && element.firstChild.className == "headerCat"){
						//contract All Sub Menus
						$$('ul.parent_opened').each(function(element) {
							element.className = "parent_closed";
						});
					}
					var el = this.parentNode;
					if(el.tagName=='LI' && (el.hasClassName('rootNode'))) {
						el.childNodes[2].className = (el.childNodes[2].className=='parent_opened')
						?	el.childNodes[2].className= 'parent_closed'
						:   el.childNodes[2].className= 'parent_opened';
						return false;
					}
				};
			}
		},
		
		/* version 2 : top categories non-clickable + default display the first sub-categories level */
		initV2 : function(element, version) {
			if($(element).childNodes[2]){
				
				//IAmHere class correspond au fil d'ariane.. on ne cache pas les sous-menu faisant parti de l'arborescence de la page dans laquelle on se trouve.
				if(element.className == "rootNode" && element.firstChild.className == "headerCat"){
					//alert(element.childNodes[2].tagName);
					element.childNodes[2].className = "parent_opened";
					element.firstChild.style.cursor = "default";
					element.firstChild.href ="#1";
					element.firstChild.onclick = function(){ return false} ;
				}
				else{
					if(element.firstChild.firstChild.className != "IAmHere") {
						$(element).childNodes[2].className = 'parent_closed'; //hiding all sub-categories
					}
					else{
						$(element).childNodes[2].className = 'parent_opened';
					}
							
					$(element).childNodes[0].href ="#1";
					$(element).childNodes[0].onclick = function() {  //add onclick event
						var el = this.parentNode;
						//contract All Sub Menus
						$$('#dropDownMenu ul li ul li ul.parent_opened').each(function(element) {
							if(element != el.childNodes[2])
								element.className = "parent_closed";
						});
						
						if(el.tagName=='LI' && (el.hasClassName('rootNode'))) {
							el.childNodes[2].className = (el.childNodes[2].className=='parent_opened')
							?	el.childNodes[2].className= 'parent_closed'
							:   el.childNodes[2].className= 'parent_opened';
							return false;
						}
					};
				}
			}
		}
		
	};
}();
/* FIN gestion du menu categories -------------------------------------------------------*/

/* HASHMAP Class :  used instead of string-indexed Arrays */
var targInfo = {
	Set : function(foo,bar) {this[foo] = bar;},
	Get : function(foo) {return this[foo];}
}

/* CUSTOM SelectBox */
/* trouve toutes les selectBox par leur classe , et les remplace par de fausses selectBox en JS - unobstrusive  */
var SelectBox = function() {
	
	var arrow_image = "/img/arrow.png";
	
	/* IE needs this to emulate css :hover on li items  */
	var IEHoverColor = "#D1C79D";
	var IENormalColor = "";
	
	var selectBoxes = new Array();
	
	/*
	 * TODO: key listener
	 var indexTab = new Array();
	indexTab["A"] = 1;*/
	
	return {
		init : function(element) {
			
			var displayed = false;
			selectBoxes[element.id] = new Array();		

			var defaultOption = false;
			
			function toggleDisplayOptionsList(){
					var myUl = container.getElementsByTagName("ul")[0];
					if(displayed){
						myUl.style.display = "none";
						displayed = false;
					}
					else{
						displayed = true;
						myUl.style.display = "block";
						
						/* TODO:key listener */
						/*document.onkeydown = function (evenement){
							var inputChar = (document.all)
								? String.fromCharCode(event.keyCode)
								: String.fromCharCode(evenement.which);
							console.log(inputChar);
							console.log(selectBoxes[element.id]["charIndex"]);
							ul.childNodes[selectBoxes[element.id]["previousChoice"].id].className = "";
							ul.childNodes[selectBoxes[element.id]["charIndex"][inputChar]].className = "selectedOption";
						};*/
					}
			}
			
			if(element.tagName == "SELECT"){
				//fake selectBox creation :
				
				//container
				var container =	document.createElement("div");
				container.className = 'containerSelectBox';
				//element.parentNode.appendChild(container);
				element.parentNode.insertBefore(container,element);
				
				//textfield
				var fakeTextField = document.createElement("div");
				fakeTextField.className = "fakeTextField";
				fakeTextField.onclick = function(){
					SelectBox.hideAllSelectBoxes();
					toggleDisplayOptionsList();
				}
				container.appendChild(fakeTextField);
				
				//true hidden inputfield  replacing the entire selectBox; (updated by onclick events on fake list)
				/*var formHiddenField = document.createElement("input");
				formHiddenField.setAttribute("type","hidden");
				formHiddenField.className = "hidden";
				formHiddenField.setAttribute("name",element.name);
				formHiddenField.setAttribute("value",element.options[element.options.selectedIndex].value);
				container.appendChild(formHiddenField);*/
				
				//arrow-image clickable
				/*var image = document.createElement("img");
				image.setAttribute('src',arrow_image);
				container.appendChild(image);*/
				
				//fake options-list
				if(element.options.length > 0){
					var ul = document.createElement("ul");
					ul.className = "options";
					container.appendChild(ul);
					/*ul.onfocus = function (){
						alert(this);
					};*/
					//creates a <li> for each options
					//for (var option in element.options){
					var len = element.options.length;
					for (var x=0; x < len; x++){
						var li = document.createElement("li");
						li.title = element.options[x].value;
						(document.all)
							? li.innerText = element.options[x].text
							: li.innerHTML = element.options[x].text;
						li.id = x;
						
						//index of each option's first character (keyboard navigation)
						/*selectBoxes[element.id]["charIndex"] = new Array();
						var firstChar =  (document.all) ? li.innerText : li.innerHTML;
						var firstCharCode = String.charCodeAt(firstChar.substring(0,1).toUpperCase());
						console.log(firstCharCode);
						selectBoxes[element.id]["charIndex"][firstCharCode] = x;*/
						//console.log(selectBoxes[element.id]["charIndex"].length);

						
						
						/* on click event*/
						li.onclick = function(){
							var txt = this.innerHTML.replace(/&nbsp;/g, " ");
							
							element.options.selectedIndex = this.id; //on associe l'option de la fausse selectBox à l'option de la vrai selectBox
							if (typeof element.onchange == "function") element.onchange(); //en gardant les actions onchange javascript de la vraie.
							
							if (typeof element.options[this.id].onclick == "function")	element.options[this.id].click() ; //et en gardant l'eventuel evenement onclick des option originaaux
							
							(document.all)
								? fakeTextField.innerText = txt  //innerHTML value
								: fakeTextField.innerHTML = this.innerHTML;  //innerHTML value
								
							var node_len = this.parentNode.childNodes.length;
							for (var y = 0; y < node_len; y++)
								this.parentNode.childNodes[y].className = "";
							this.className = "selectedOption";
							selectBoxes[element.id]["previousChoice"] = this;
							toggleDisplayOptionsList();

						};
						/* END on click event*/
						
						li.onmouseover = function(){
							IENormalColor = this.style.backgroundColor;
							this.style.backgroundColor = IEHoverColor;
						};
						
						li.onmouseout = function(){
							this.style.backgroundColor = IENormalColor;
						};
				
						
						// set position of the selected option (if existing)
						if(element.options.selectedIndex == x){
							(document.all)
								? fakeTextField.innerText = element.options[x].text
								:fakeTextField.innerHTML = element.options[x].text;
							defaultOption = true;
							li.className = "selectedOption";
							selectBoxes[element.id]["previousChoice"] = li;
						}
						

						ul.appendChild(li);
					}
					//console.log("len array => " + selectBoxes[element.id]["charIndex"].length);
					
				}
				
				//no selected option : first one is selected by default
				if(!defaultOption){
					fakeTextField.innerHTML = element.options[0].text;
				}
				//the end : we can delete the original-selectBox
				 element.style.display = "none";
				 nb_select_box++;
			}
		},
		
		hideAllSelectBoxes : function(){
			$$('ul.options').each(function(element){
				element.style.display = "none";
				displayed="false";
			});
		}
	};
}();
