// Require prototype javascript framwork

// prevent firebug console debuggin from crashing IE
/*if (!window.console || !console.firebug)
{
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = function() {}
}*/

/*****************************************/
var initScroll = 0;

function openSmallWindow(url,title) {
	window.open(url,title,'height=650, width=590, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=yes');
	return false;
}

function showPic(div,img){
	if($(div)) Element.remove(div);
	new Insertion.After(img,'<div class="divPop" id="'+div+'" style="display:none;" ></div>');
	Element.update(div,'<img src="'+ img.src +'" border="0" />');	
	$(div).style.zIndex=500;
	Effect.Appear(div,'{duration: 0.3}');	
}
function showPic2(div,div2,img){
	if($(div)) Element.remove(div);
	new Insertion.After(div2,'<div class="divPop" id="'+div+'" style="display:none;" ></div>');
	Element.update(div,'<img src="'+ img +'" border="0" />');	
	$(div).style.zIndex=500;
	Effect.Appear(div,'{duration: 0.3}');	
}

function hidePic(div){ Effect.Fade(div,'{duration: 0.3}'); }

function removeElement(id){ // remove element with disapear 
  console.log('hello');
	Effect.Fade(id,'{duration: 0.3,afterFinish:function(){Element.remove(id);}}');	
}


function toggleDiv(divName){
	var div = $(divName);
	if(div.getStyle(display)=="none") div.show();
	else div.hide();
}

function errorMsg(msg){
	/*var button = '<input type="button" name="closeModal" onclick="Control.Modal.close();" class="popupButton" value=" Ok " />';
	msg += '<p style="text-align:center;">'+button+'</p>';*/
	Modalbox.show("<div id=\"infoModal\"><p>"+msg+"</p></div>",{title: '<h6 class="error"><span>Erreur</span></h6>', width: 250});
	//modalDialog("Erreur!",msg,'error',250,250);	
}

function successMsg(msg){
	/*var button = '<input type="button" name="closeModal" onclick="Control.Modal.close();" class="popupButton" value=" Ok " />';
	msg += '<p style="text-align:center;">'+button+'</p>';*/
	Modalbox.show(msg,{title: '<h6 class="success"><span>Ajout effectué avec succès</span></h6>', width: 250});
	
	
//	modalDialog('<h6>Ajout effectué avec succès</h6>',msg,'success',250,250);	
}
/********  modal dialog */
/*
function modalDialogOld(title,content,className,width,height){
	var theBody = document.body;
	theBody.style.overflow = "hidden";
	
	
	if(!$('popupMask')){
		var mask = '<div id="popupMask" style="display:none"></div>';
		new Insertion.Bottom(document.body,mask);	
	}
	Element.show('popupMask');
	if($('popupContainer')) Element.remove('popupContainer');
	
	var popup = '<div id="popupContainer" style="display:none"  class="'+className+'">';
			popup += '<div id="popupTitleBar">';
				popup += '<div id="popupTitle">'+title+'</div>';		
				popup += '<div id="popupControls" onclick="closeModal()"><span>X</span></div>';
			popup += '</div>';
			popup += '<div id="popupContent">'+content+'</div>';
		popup += '</div>';
	new Insertion.Bottom(document.body,popup);
	
	centerPopWin('popupContainer',width,height);
	Element.show('popupContainer');
}*/

function closeModal(){
	/*
	Element.remove('popupContainer');
	Element.remove('popupMask');
	var theBody = document.body;
	theBody.style.overflow = "";
	*/
	Modalbox.hide();
}
/*
function centerPopWin(id,width, height) {	
	if (width == null || isNaN(width)) { width = 250; }
	if (height == null) { height = 250;	}	
	$(id).style.width  = width+'px';
	$(id).style.height = height+'px';
	$(id).style.marginTop  = ((height / 2) * -1)+'px';	
	$(id).style.marginLeft = ((width / 2) * -1)+'px';
}

function getViewportHeight() {
	if (typeof window.innerWidth != 'undefined') return window.innerHeight;
 	else if (typeof document.documentElement != 'undefined'
     && typeof document.documentElement.clientWidth !=
     'undefined' && document.documentElement.clientWidth != 0) return document.documentElement.clientHeight;
 	else return document.getElementsByTagName('body')[0].clientHeight;   
}
function getViewportWidth() {
	if (typeof window.innerWidth != 'undefined') return window.innerWidth;
 	else if (typeof document.documentElement != 'undefined'
     && typeof document.documentElement.clientWidth !=
     'undefined' && document.documentElement.clientWidth != 0) return document.documentElement.clientWidth;
 	else return document.getElementsByTagName('body')[0].clientWidth; 
}*/

function modalDialog(title,content,className,ewidth,eheight)
{
	if(!ewidth)	 ewidth = 250;
	if(!eheight) eheight = 250;	
	
	var popup = '<div id="popupTitleBar">';
			popup += '<div id="popupControls" onclick="Modalbox.hide();"><img src="img/modal/close_modal.gif" alt="Fermer ce popup" /></div>';
			popup += '<div id="popupTitle">'+title;		
		popup += content+'</div>';
	
	
		
	//new Insertion.Bottom(document.body,popup);
	var m = new Control.Modal(false,{
			contents:popup,
            opacity: 0.5,
            position: 'absolute',
            width: ewidth,
            //height: eheight,
			//overlayClassName: 'overlay',
			containerClassName: className ,
			beforeOpen: function(){document.body.setStyle({height:'auto'});}, //called before the modal opens
    		afterClose: function(){document.body.setStyle({height:'100%'});}
        }); 
	m.open();
	
	return false;
}


function addQttToKartItem(qtt,price,productId){
	var qttBox = $('products['+productId+']');
	if(!isNaN(parseInt(qttBox.value)) && !isNaN(parseInt(qtt))){
		var oldQtt = parseInt(qttBox.value);
		var newqtt = oldQtt + qtt;
		if (newqtt < 0) newqtt = 0;	
		if(changeCartItemQtt(newqtt,productId,price,oldQtt));
	}
	else { alert('Quantity Error'); }
}

function updateQttKartItem(qtt,price,productId){
	
	var qttBox = $('products[' + productId + ']');
	qttBox.value = qtt;
	price = parseFloat(price);
	var totalDiv = $('total-'+productId);
	var newprice = (qttBox.value * price);
	////console.debug('np1',price);
	newprice = (Math.round(newprice * 100)) / 100;
	
	////console.debug('np2',newprice);
	totalDiv.innerHTML = newprice + ' &euro;';
	showUpdateTotalButton();
	/*	
	$('modifCart').style.display = 'inline';		
	$('initOrder').style.display = 'none';			
	*/
}
function showUpdateTotalButton()
{
	updateButton=$('btnUpdateTotal');
	if(updateButton && !updateButton.visible())
	{
		updateButton.show();
	}
}
function changeCartItemQtt(qtt,olId,price,oldQtt){
	if(!oldQtt) var oldQtt = 1;
	var action = 'changeLineQttAjax';
	var php = new PHP_Serializer();
	var arParam = new Array();
	
	if(qtt <= 0) {
		if(confirm('Supprimer ce produits?')){
			qtt = 0; removeFromCart(olId);
			return 0;
		}
		else qtt = 1;
	}
	
	arParam['qtt'] = qtt;
	arParam['olId'] = olId;
	
	var param = escape(php.serialize(arParam));	
	
	var url = '/ecommerce/handler.php'
	var paramstr = 'action='+action+'&param='+ param;
	var myAjax = new Ajax.Request(url, {
					method: 'get',
					onSuccess : function(resp) {
						if(resp.responseText && resp.responseText.search(/errorCHANGEqtt/) >-1){
							errorMsg("Ouups ! Une erreur est survenue lors de la suppression du produit.");							
						}
 						else { 							
							updateCartInfo();
						}
 					},
 					onFailure : function(resp) {
 						errorMsg("Ouups ! Une erreur est survenue lors de la suppression du produit.");
						updateQttKartItem(oldQtt,price,olId);
						return false;
 					},
 					parameters : paramstr
	});	
	updateQttKartItem(qtt,price,olId);
}

function removeFromCart(olId){
	
	var action = 'delCartLineAjax';
	var php = new PHP_Serializer();
	var arParam = new Array();
	arParam['olId'] = olId;
	var param = escape(php.serialize(arParam));	
	
	var url = '/ecommerce/handler.php'
	var paramstr = 'action='+action+'&param='+ param;
	//window.console.log('ok');
	
	var myAjax = new Ajax.Request(url, {
					method: 'get',
					onSuccess : function(resp) {
						if(resp.responseText && resp.responseText.search(/errorDELETEcart/) >-1)
 							errorMsg("Ouups ! Une erreur est survenue lors de la suppression du produit.");
 						else {
 						  document.location.reload();
 							//updateCartInfo();	
							//updateTopQttInfo();
							//removeElement('tr'+olId);
						}
 					},
 					onFailure : function(resp) {
 					 // window.console.log('error');
 						errorMsg("Ouups ! Une erreur est survenue lors de la suppression du produit.")
 					},
 					onException: function(e){ /*window.console.log(e);*/},
 					parameters : paramstr
	});
	
	
}

function addVoucher(code) {
	var url = '/ecommerce/handler.php';
	var params = {
			action: 'addVoucher',
			code: code
	};
	new Ajax.Request(url, {
		method: 'post',
		parameters: $H(params),
		onSuccess : function(r) {
			if(r.responseText == 'true') {
				document.location.reload();
			} else {
				errorMsg(r.responseText);
			}
		},
		onFailure: function(r) {
			errorMsg("Ouups ! Une erreur est survenue lors de l'ajout du coupon.");
		}
	});
}

function removeVoucher(id) {
	var url = '/ecommerce/handler.php';
	var params = {
			action: 'removeVoucher',
			id: id
	};
	new Ajax.Request(url, {
		method: 'post',
		parameters: $H(params),
		onSuccess : function(r) {
			document.location.reload();
		},
		onFailure: function(r) {
			errorMsg("Ouups ! Une erreur est survenue lors de la suppression du coupon.");
		}
	});
}

function checkUserInfoDevis(){
	
	var action = 'checkUserInfoDevisAjax';	
	var url = '/ecommerce/handler.php';
	var paramstr = 'action='+action;
	var myAjax = new Ajax.Request(url, {
					method: 'get',
					onSuccess : function(resp) {						
						if(resp.responseText && resp.responseText.search(/userINFOKO/) >-1){
 							errorMsg("Vos informations ne sont pas complètes. Merci de bien vouloir les compléter pour envoyer votre devis.");	
							return false;
						
						}
 						else {
 							checkUserInfoDevisOK();
						}
 					},
 					onFailure : function(resp) {
 						errorMsg("Ouups ! Une erreur est survenue lors de l'oprération.")
 					},
 					parameters : paramstr
	});
}

function saveCartChanges(){
	var form = $('cartForm');
	var action = 'updateCart';
	form.action = '/ecommerce/handler.php?action='+action
	
	form.submit();
}

function addToCart(pid){
	addProduct('cart',pid);
}


function addProduct(type,pid,qtt){ // type is cart or favourite
	if(type == 'cart'){
		var action = 'addToCartAjax';
		var errMsg = "Une erreur est survenue lors de l'ajout de ce produit au panier";
		var succMsg= '<div id="infoModal"><p>Ce produit à bien été ajouté à votre sélection.<br>Que souhaitez-vous faire?</p></div></div><div id="popupContent"><div id="goCatalogue"><a href="#" onclick="Modalbox.hide();return false;" class="popupButton MB_focusable"><img src="img/modal/goCatalogue.gif" alt="Revenir au catalogue de produits" border="0"></a><p>Cliquez sur le bouton ci-dessus pour fermer cette fenêtre et continuer vos achats.</p></div><div id="goMonQuatuor"><a href="/ecommerce-monpanier-0-0-0.html" class="popupButton MB_focusable"><img src="img/modal/goMonQuatuor.gif" alt="Accéder à votre Quatuor" border="0"></a><p>Cliquez sur le bouton ci-dessus pour accéder à votre panier d\'achat ou demande de devis.</p></div></div>';
	}
	else{
		var action = 'addToFavAjax';
		var errMsg = "Une erreur est survenue lors de l'ajout de ce produit aux favoris";
		var succMsg= '<div id="infoModal"><p>Ce produit &agrave; bien &eacute;t&eacute; ajout&eacute; &agrave; votre panier.<br />Que souhaitez-vous faire?</p></div></div><div id="popupContent"><div id="goCatalogue"><a href="#" onclick="Modalbox.hide();return false;" class="popupButton"/><img src="img/modal/goCatalogue.gif" alt="Revenir au catalogue de produits" border="0" /></a><p>Cliquez sur le bouton ci-dessus pour fermer cette fen&ecirc;tre et continuer vos achats.</p></div><div id="goMonQuatuor"><a href="/ecommerce-monquatuor-0-0-0.html" class="popupButton"/><img src="img/modal/goMonQuatuor.gif" alt="Accéder à votre Quatuor" border="0" /></a><p>Cliquez sur le bouton ci-dessus pour accéder à votre panier d\'achat et votre espace personnel.</p></div></div>';
	}
	
	var php = new PHP_Serializer();
	var arParam = new Array();
	
	if($('pQtt')){
		var qtt = $F('pQtt');
	}
	else{
		var qtt = 1;	
	}
	
	var size = null;
	if($('sizeForm')){
		var inputs = $A($('sizeForm').getElementsByTagName('input'));
		inputs.each(
			function(input)
			{
				if(input.checked == true){
					if(input.value == '') size = null;
					else size = input.value;
				}
			}
		);
	}
   	
	var color = null;
	if($('colorForm')){
		if($('pColorId').value != '')
			color = $('pColorId').value
	}
	
	arParam['pid'] 		= pid;
	arParam['qtt'] 		= qtt;
	arParam['pSizeId'] 	= size;		
	arParam['pColorId'] = color;	
	arParam['productUrl'] = document.location.href;
	
	var param = (php.serialize(arParam));
	var url = '/ecommerce/handler.php'
	var paramstr = 'action='+action+'&param='+ escape(param);
	var myAjax = new Ajax.Request(url, {
					method: 'get',
					onSuccess : function(resp) {
						if(resp.responseText && resp.responseText.search(/errorADDproduct/) >-1){ errorMsg(errMsg); }
						else{ updateTopQttInfo(); successMsg(succMsg); }
					},
					onFailure : function(resp) { errorMsg(errMsg); },
					parameters : paramstr
	});
}

function updateCartInfo(){
	var action = 'getCartInfo';	
	var url = '/ecommerce/handler.php'
	var paramstr = 'action='+action;
	var myAjax = new Ajax.Request(url, {
					method: 'get',
					onSuccess : function(resp) { updateCartInfoData(resp.responseText); },
 					onFailure : function(resp) { errorMsg("Ouups! Une erreur est survenue lors de la suppression du produit.")},
 					parameters : paramstr
	});
}

function updateTopQttInfo(){
	var action = 'getFavCartQttInfo';	
	var url = '/ecommerce/handler.php'
	var paramstr = 'action='+action;
	var myAjax = new Ajax.Request(url, {
					method: 'get',
					onSuccess : function(resp) { updateTopQttInfoData(resp.responseText); },
 					onFailure : function(resp) { errorMsg("Ouups! Une erreur est survenue lors de la suppression du produit.")},
 					parameters : paramstr
	});	
}


function updateTopQttInfoData(serialized){
	var php = new PHP_Serializer(); 
 	var data = php.unserialize(serialized);
	$('cartSelectCount').innerHTML =data.cartQtt;	
	$('favSelectCount').innerHTML =data.favQtt;	
	
	if($('favBlock') && data.favQtt == 0){
		Element.update('favBlock','<p>Aucun produit dans vos favoris</p>');	
	}
	if($('cartBlock') && data.cartQtt == 0){
		Element.update('cartBlock','<p>Aucun article dans votre panier.</p>');
	}
	
}

function updateCartInfoData(serialized){
	var php = new PHP_Serializer(); 
 	var data = php.unserialize(serialized);
	
	if(data.cartCount > 0){		
		$('cartSubTotal').innerHTML =data.subTotal;	
		$('cartTransportFee').innerHTML =data.transportFee;	
		$('cartTotalHTVA').innerHTML = data.totalHTVA;	
		$('cartTvaAmount').innerHTML = data.TVAAmount;			
		$('cartTotal').innerHTML = data.total;	
		$('cartTransportDetails').innerHTML = data.transportDetails;
	}
	
}
/****************************************/
/* gestion des favoris  */

function addToFav(pid){	addProduct('fav',pid); }

function addQttToFavItem(qtt,flId){	
	var qttBox = $("pQtt['"+flId+"']");
	var oldQtt = parseInt(qttBox.value);
	var newQtt = oldQtt + qtt;
	changeFavQtt(newQtt,flId,oldQtt);	
}

function changeFavQtt(qtt,flId,oldQtt){
	if(!oldQtt) oldQtt = 1;
	var action = 'changeFavQtt';
	var php = new PHP_Serializer();
	var arParam = new Array();
	
	if(qtt <= 0) {
		if(confirm('Supprimer ce produits?')){
			qtt = 0; deleteFav(flId);
		}
		else qtt = 1;
	}
	if(qtt > 0){	
		arParam['flId'] = flId;
		arParam['pQtt'] = qtt;		
		var param = (php.serialize(arParam));		
		var url = '/ecommerce/handler.php'
		var paramstr = 'action='+action+'&param='+ escape(param);
		var myAjax = new Ajax.Request(url, {
						method: 'get',
						onSuccess : function(resp) {
							if(resp.responseText && resp.responseText.search(/errorSETfavQTT/) >-1){
								//setQttValue($flId,$("pQtt['"+flId+"']"));
	 							errorMsg("Ouups ! Une erreur est survenue lors de la modification de quantité.")
							}
	 						else{  }
						},
	 					onFailure : function(resp) { errorMsg("Ouups ! Une erreur est survenue lors de la modification de quantité.")
						$("pQtt['"+flId+"']").value = oldQtt;
						},
	 					parameters : paramstr
		});
		$("pQtt['"+flId+"']").value = qtt;
	}
}

function setFavQttValue($flId,txtBox){
	var action = 'getFavQtt';
	var php = new PHP_Serializer();
	var arParam = new Array();		
	arParam['flId'] = flId;	
	var param = (php.serialize(arParam));	
	var url = '/ecommerce/handler.php'
	var paramstr = 'action='+action+'&param='+ escape(param);
	var myAjax = new Ajax.Request(url, {
					method: 'get',
					onSuccess : function(resp) {
						if(resp.responseText && resp.responseText.search(/errorSETfavQTT/) >-1){
							//setQttValue($flId,$("pQtt['"+flId+"']"));
 							errorMsg("Ouups ! Une erreur est survenue lors de la modification de quantité.");
						}
 						else{ txtBox.value = resp.responseText;	}
					},
 					onFailure : function(resp) { errorMsg("Ouups ! Une erreur est survenue lors de la modification de quantité.");},
 					parameters : paramstr
	});
}

function emptyFav(){
	var action = 'emptyFav';
	
	var url = '/ecommerce/handler.php'
	var paramstr = 'action='+action;
	var myAjax = new Ajax.Request(url, {
					method: 'get',
					onSuccess : function(resp) {
						if(resp.responseText && resp.responseText.search(/errorEMPTYfav/) >-1){							
 							errorMsg("Ouups ! Une erreur est survenue lors de la suppression de vos favoris.");
						}
 						else{
 						 document.location.reload();
 							//$('favForm').innerHTML = "<tr><td>Aucun article dans vos favoris.</td></tr>";
 							//Element.hide('actionsFav','askDevisBox');
 						}
					},
 					onFailure : function(resp) {
 						errorMsg("Ouups ! Une erreur est survenue lors de la suppression de vos favoris.");
 					},
 					parameters : paramstr
	});
}


function setFavDevisCheck(flId,checked){
	var action  = 'setProductCheckDevisAjax';
	var php = new PHP_Serializer();
	var arParam = new Array();
	arParam['flId'] = flId;
	arParam['checked'] = checked;
	var param = (php.serialize(arParam));
	
	var url = '/ecommerce/handler.php'
	var paramstr = 'action='+action+'&param='+ escape(param);
	var myAjax = new Ajax.Request(url, {
					method: 'get',
 					onFailure : function(resp) {
 						errorMsg("Ouups ! Une erreur est survenue lors du chagement du status du produit.")
 					},
 					parameters : paramstr
	});
	
}

function setAllFavChecked(){
	var action  = 'setAllProductCheckDevisAjax';	
	var url = '/ecommerce/handler.php'
	var paramstr = 'action='+action;
	var myAjax = new Ajax.Request(url, {
					method: 'get',
					onSuccess : function(resp) {
						if(resp.responseText && resp.responseText.search(/errorSETallFAVchecked/) >-1){

							errorMsg("Ouups ! Une erreur est survenue lors de la selection des favoris."); 
						}
 						else
 							setAllFavChecks(true);						
 					},
 					onFailure : function(resp) {

 						errorMsg("Ouups ! Une erreur est survenue lors du chagement du status du produit.")
 					},
 					parameters : paramstr
	});
}

function setAllFavUnChecked(){
	var action  = 'setAllProductUnCheckDevisAjax';	
	var url = '/ecommerce/handler.php'
	var paramstr = 'action='+action;
	var myAjax = new Ajax.Request(url, {
					method: 'get',
					onSuccess : function(resp) {
						
						if(resp.responseText && resp.responseText.search(/errorSETallFAVunchecked/) >-1){
							errorMsg("Ouups ! Une erreur est survenue lors de la selection des favoris.");
						}
 						else
 							setAllFavChecks(false); 						
 					},
 					onFailure : function(resp) { 						

 						errorMsg("Ouups ! Une erreur est survenue lors du chagement du status du produit.")
 					},
 					parameters : paramstr
	});
}

function setAllFavChecks(state){
	if($('favForm')){
		var inputs = $A($('favForm').getElementsByTagName('input'));
			 inputs.each(function(input)
			{
				if(input.name.search(/productsCheck/) >-1)
					input.checked = state;
			}
		);
	}
}

function deleteFav(flId){
	var action  = 'delFavProductAjax';
	var php = new PHP_Serializer();
	var arParam = new Array();
	arParam['flId'] = flId;
	
	var param = (php.serialize(arParam));
	
	var url = '/ecommerce/handler.php'
	var paramstr = 'action='+action+'&param='+ escape(param);

	var myAjax = new Ajax.Request(url, {
					method: 'get',
					onSuccess : function(resp) {
						if(resp.responseText && resp.responseText.search(/errorDELETEfav/) >-1)
 							errorMsg("Ouups ! Une erreur est survenue lors de la suppression du produit.");
 						else{
 						 document.location.reload();
 						 //updateTopQttInfo();
             //removeElement('trFav'+lflId);
						}
 					},
 					onFailure : function(resp) {
 						errorMsg("Ouups ! Une erreur est survenue lors de la suppression du produit.")
 					},
 					parameters : paramstr
	});
	
}

function devisDialog(logged){
	if(!logged){
		document.location.href = "ecommerce-login-0-logDevis-0.html"
		//errorMsg('vous devez être connecté pour faire une demande devis.<br /><a href="/ecommerce-login-0-devis-0.html">Se connecter / s\'inscrire</a>');
		//return false;
	}
	else checkUserInfoDevis();
	
}

function checkUserInfoDevisOK(){		
	
		var url = '/ecommerce/favoris/comment.php';
		var paramstr = '';
		var myAjax = 
			new Ajax.Request(
					url, {
					method: 'get',
					onSuccess : function(resp) {
					//modalDialogModalbox.show('Demande de devis',resp.responseText,'',400,350);
					Modalbox.show(resp.responseText+'<br/>',{title: 'Demande de devis', width: 400});
					},
					onFailure : function(resp) {
						errorMsg("Ouups ! Une erreur est survenue lors l'envois de la demande de devis.");
					},
					parameters : paramstr
			});
}

function askDevis(){
	
	
	var url = '/ecommerce/handler.php?action=askFavDevisAjax';
	
	var php = new PHP_Serializer();
	var arParam = new Array();
		
	var paramstr = 'comment='+$F('commentDevis');
	
	var myAjax = new Ajax.Request(url, {
					method: 'post',
					onSuccess : function(resp) { 							
 						if(resp.responseText && resp.responseText.search(/devisSENT/) >-1 && resp.responseText.search(/Fatal error/) == -1 || resp.responseText.search(/Parse error/) == -1  ){
 							successMsg("Votre demande de devis a été envoyée.\nNous vous répondrons dans les plus brefs délais.</br>");
						}
						else errorMsg("Ouups ! Une erreur est survenue lors l'envois de la demande de devis.");
 					},
 					onFailure : function(resp) {
 						errorMsg("Ouups ! Une erreur est survenue lors l'envois de la demande de devis.");
 					},
 					parameters : {comment : $F('commentDevis')}
	});
}

/***************************************/
/* gestion de la commande */

function orderSaveUserInfo(formName,action,redirectTo){
	
	if(!tmt_validateForm($(formName))) return false;	

	if(!$(formName)) errorMsg('pas de form '+formName);
	var param = Form.serialize(formName);
	var url = '/ecommerce/handler.php?action='+action;
	var paramstr = param;
	var myAjax = new Ajax.Request(url, {
					method: 'post',
					onSuccess : function(resp) {
						if(resp.responseText && resp.responseText.search(/errorSAVINGuserINFO/) >-1){
 							errorMsg("Ouups ! Une erreur est survenue lors de l'enregistrement de vos données.");
						}
 						else{  		
							//console.debug(resp);
 							goToPage(redirectTo);
 						}
 					},
 					onFailure : function(resp) {
 						errorMsg("Ouups ! Une erreur est survenue lors de l'enregistrement de vos données.");
 					},
 					parameters : paramstr
	});
}

function verifCond(){
	if($('verifCond').checked == false){
		alert('Vous devez accepter les conditions générales de ventes pour continuer.');
		return false;
	}
	return true;
}

function confirmOrder(ogoneForm){
	if(!verifCond()) return;
	
	var ok = confirm("Vous allez confirmer la commande et passer sur une plateforme de paiement sécurisé");
	if(ok){
		var url = '/ecommerce/handler.php';
		var action = "initPay";
		
		var php = new PHP_Serializer();
		var arParam = new Array();
	
		arParam['comment']  = $F('commentOrder');
		
		var param = (php.serialize(arParam));
	
		var paramstr = 'action='+action+'&param='+param;
		
		var myAjax = new Ajax.Request(url, {
					method: 'post',
					onSuccess : function(resp) {
						if(resp.responseText && resp.responseText.search(/errorSAVINGorderUSERdata/) >-1){
 							errorMsg("Ouups ! Vos données ne sont pas correctement complétées.");
 							ok = false;
						}
						
						if(resp.responseText && resp.responseText.search(/errorSAVINGorder/) >-1){
 							errorMsg("Ouups ! Une erreur est survenue lors de l'enregistrement de vos données.");
 							ok = false;
						}
						
 						if(ok){  							
 							$(ogoneForm).submit();
 						}
 					},
 					onFailure : function(resp) {
 						errorMsg("Ouups ! Une erreur est survenue lors de l'enregistrement de vos données...");
 					},
 					parameters : paramstr
		});
	}	
}

/********************************
 * Object PHP_Serializer
 * 	JavaScript to PHP serialize / unserialize class.
 * This class converts php variables to javascript and vice versa.
 *
 * PARSABLE JAVASCRIPT < === > PHP VARIABLES:
 *	[ JAVASCRIPT TYPE ]		[ PHP TYPE ]
 *	Array		< === > 	array
 *	Object		< === > 	class (*)
 *	String		< === > 	string
 *	Boolean		< === > 	boolean
 *	null		< === > 	null
 *	Number		< === > 	int or double
 *	Date		< === > 	class
 *	Error		< === > 	class
 *	Function	< === > 	class (*)
 *
 * (*) NOTE:
 * Any PHP serialized class requires the native PHP class to be used, then it's not a
 * PHP => JavaScript converter, it's just a usefull serilizer class for each
 * compatible JS and PHP variable types.
 * Lambda, Resources or other dedicated PHP variables are not usefull for JavaScript.
 * There are same restrictions for javascript functions*** too then these will not be sent.
 *
 * *** function test(); alert(php.serialize(test)); will be empty string but
 * *** mytest = new test(); will be sent as test class to php
 * _____________________________________________
 *
 * EXAMPLE:
 *	var php = new PHP_Serializer(); // use new PHP_Serializer(true); to enable UTF8 compatibility
 *	alert(php.unserialize(php.serialize(somevar)));
 *	// should alert the original value of somevar
 * ---------------------------------------------
 * @author              Andrea Giammarchi
 * @site		www.devpro.it
 * @date                2005/11/26
 * @lastmod             2006/05/15 19:00 [modified stringBytes method and removed replace for UTF8 and \r\n]
 * 			[add UTF8 var again, PHP strings if are not encoded with utf8_encode aren't compatible with this object]
 *			[Partially rewrote for a better stability and compatibility with Safari or KDE based browsers]
 *			[UTF-8 now has a native support, strings are converted automatically with ISO or UTF-8 charset]
 *
 * @specialthanks	Fabio Sutto, Kentaromiura, Kroc Camen, Cecile Maigrot, John C.Scott, Matteo Galli
 *
 * @version             2.2, tested on FF 1.0, 1.5, IE 5, 5.5, 6, 7 beta 2, Opera 8.5, Konqueror 3.5, Safari 2.0.3
 */

function PHP_Serializer(UTF8){function serialize(v){var s;switch(v){case null:s="N;";break;default:s=this[this.__sc2s(v)]?this[this.__sc2s(v)](v):this[this.__sc2s(__o)](v);break;};return s;};function unserialize(s){__c=0;__s=s;return this[__s.substr(__c,1)]();};function stringBytes(s){return s.length;};function stringBytesUTF8(s){var c,b=0,l=s.length;while(l){c=s.charCodeAt(--l);b+=(c<128)?1:((c<2048)?2:((c<65536)?3:4));};return b;};function __sc2s(v){return v.constructor.toString();};function __sc2sKonqueror(v){var f;switch(typeof(v)){case("string"||v instanceof String):f="__sString";break;case("number"||v instanceof Number):f="__sNumber";break;case("boolean"||v instanceof Boolean):f="__sBoolean";break;case("function"||v instanceof Function):f="__sFunction";break;default:f=(v instanceof Array)?"__sArray":"__sObject";break;};return f;};function __sNConstructor(c){return(c==="[function]"||c==="(Internal Function)");};function __sCommonAO(v){var b,n,a=0,s=[];for(b in v){n=v[b]==null;if(n||v[b].constructor!=Function){s[a]=[(!isNaN(b)&&parseInt(b).toString()===b?this.__sNumber(b):this.__sString(b)),(n?"N;":this[this.__sc2s(v[b])]?this[this.__sc2s(v[b])](v[b]):this[this.__sc2s(__o)](v[b]))].join("");++a;};};return[a,s.join("")];};function __sBoolean(v){return["b:",(v?"1":"0"),";"].join("");};function __sNumber(v){var s=v.toString();return(s.indexOf(".")<0?["i:",s,";"]:["d:",s,";"]).join("");};function __sString(v){return["s:",v.length,":\"",v,"\";"].join("");};function __sStringUTF8(v){return["s:",this.stringBytes(v),":\"",v,"\";"].join("");};function __sArray(v){var s=this.__sCommonAO(v);return["a:",s[0],":{",s[1],"}"].join("");};function __sObject(v){var o=this.__sc2s(v),n=o.substr(__n,(o.indexOf("(")-__n)),s=this.__sCommonAO(v);return["O:",this.stringBytes(n),":\"",n,"\":",s[0],":{",s[1],"}"].join("");};function __sObjectIE7(v){var o=this.__sc2s(v),n=o.substr(__n,(o.indexOf("(")-__n)),s=this.__sCommonAO(v);if(n.charAt(0)===" ")
n=n.substring(1);return["O:",this.stringBytes(n),":\"",n,"\":",s[0],":{",s[1],"}"].join("");};function __sObjectKonqueror(v){var o=v.constructor.toString(),n=this.__sNConstructor(o)?"Object":o.substr(__n,(o.indexOf("(")-__n)),s=this.__sCommonAO(v);return["O:",this.stringBytes(n),":\"",n,"\":",s[0],":{",s[1],"}"].join("");};function __sFunction(v){return"";};function __uCommonAO(tmp){var a,k;++__c;a=__s.indexOf(":",++__c);k=parseInt(__s.substr(__c,(a-__c)))+1;__c=a+2;while(--k)
tmp[this[__s.substr(__c,1)]()]=this[__s.substr(__c,1)]();return tmp;};function __uBoolean(){var b=__s.substr((__c+2),1)==="1"?true:false;__c+=4;return b;};function __uNumber(){var sli=__s.indexOf(";",(__c+1))-2,n=Number(__s.substr((__c+2),(sli-__c)));__c=sli+3;return n;};function __uStringUTF8(){var c,sls,sli,vls,pos=0;__c+=2;sls=__s.substr(__c,(__s.indexOf(":",__c)-__c));sli=parseInt(sls);vls=sls=__c+sls.length+2;while(sli){c=__s.charCodeAt(vls);pos+=(c<128)?1:((c<2048)?2:((c<65536)?3:4));++vls;if(pos===sli)
sli=0;};pos=(vls-sls);__c=sls+pos+2;return __s.substr(sls,pos);};function __uString(){var sls,sli;__c+=2;sls=__s.substr(__c,(__s.indexOf(":",__c)-__c));sli=parseInt(sls);sls=__c+sls.length+2;__c=sls+sli+2;return __s.substr(sls,sli);};function __uArray(){var a=this.__uCommonAO([]);++__c;return a;};function __uObject(){var tmp=["s",__s.substr(++__c,(__s.indexOf(":",(__c+3))-__c))].join(""),a=tmp.indexOf("\""),l=tmp.length-2,o=tmp.substr((a+1),(l-a));if(eval(["typeof(",o,") === 'undefined'"].join("")))
eval(["function ",o,"(){};"].join(""));__c+=l;eval(["tmp = this.__uCommonAO(new ",o,"());"].join(""));++__c;return tmp;};function __uNull(){__c+=2;return null;};function __constructorCutLength(){function ie7bugCheck(){};var o1=new ie7bugCheck(),o2=new Object(),c1=__sc2s(o1),c2=__sc2s(o2);if(c1.charAt(0)!==c2.charAt(0))
__ie7=true;return(__ie7||c2.indexOf("(")!==16)?9:10;};var __c=0,__ie7=false,__b=__sNConstructor(__c.constructor.toString()),__n=__b?9:__constructorCutLength(),__s="",__a=[],__o={},__f=function(){};PHP_Serializer.prototype.serialize=serialize;PHP_Serializer.prototype.unserialize=unserialize;PHP_Serializer.prototype.stringBytes=UTF8?stringBytesUTF8:stringBytes;if(__b){PHP_Serializer.prototype.__sc2s=__sc2sKonqueror;PHP_Serializer.prototype.__sNConstructor=__sNConstructor;PHP_Serializer.prototype.__sCommonAO=__sCommonAO;PHP_Serializer.prototype[__sc2sKonqueror(__b)]=__sBoolean;PHP_Serializer.prototype.__sNumber=PHP_Serializer.prototype[__sc2sKonqueror(__n)]=__sNumber;PHP_Serializer.prototype.__sString=PHP_Serializer.prototype[__sc2sKonqueror(__s)]=UTF8?__sStringUTF8:__sString;PHP_Serializer.prototype[__sc2sKonqueror(__a)]=__sArray;PHP_Serializer.prototype[__sc2sKonqueror(__o)]=__sObjectKonqueror;PHP_Serializer.prototype[__sc2sKonqueror(__f)]=__sFunction;}
else{PHP_Serializer.prototype.__sc2s=__sc2s;PHP_Serializer.prototype.__sCommonAO=__sCommonAO;PHP_Serializer.prototype[__sc2s(__b)]=__sBoolean;PHP_Serializer.prototype.__sNumber=PHP_Serializer.prototype[__sc2s(__n)]=__sNumber;PHP_Serializer.prototype.__sString=PHP_Serializer.prototype[__sc2s(__s)]=UTF8?__sStringUTF8:__sString;PHP_Serializer.prototype[__sc2s(__a)]=__sArray;PHP_Serializer.prototype[__sc2s(__o)]=__ie7?__sObjectIE7:__sObject;PHP_Serializer.prototype[__sc2s(__f)]=__sFunction;};PHP_Serializer.prototype.__uCommonAO=__uCommonAO;PHP_Serializer.prototype.b=__uBoolean;PHP_Serializer.prototype.i=PHP_Serializer.prototype.d=__uNumber;PHP_Serializer.prototype.s=UTF8?__uStringUTF8:__uString;PHP_Serializer.prototype.a=__uArray;PHP_Serializer.prototype.O=__uObject;PHP_Serializer.prototype.N=__uNull;};


/**
 * @author Ryan Johnson <ryan@livepipe.net>
 * @copyright 2007 LivePipe LLC
 * @package Control.Tabs
 * @license MIT
 * @url http://livepipe.net/projects/control_tabs/
 * @version 2.1.1
 */

if(typeof(Control) == 'undefined')
	var Control = {};
Control.Tabs = Class.create();
Object.extend(Control.Tabs,{
	instances: [],
	findByTabId: function(id){
		return Control.Tabs.instances.find(function(tab){
			return tab.links.find(function(link){
				return link.key == id;
			});
		});
	}
});
Object.extend(Control.Tabs.prototype,{
	initialize: function(tab_list_container,options){
		this.activeContainer = false;
		this.activeLink = false;
		this.containers = $H({});
		this.links = [];
		Control.Tabs.instances.push(this);
		this.options = {
			beforeChange: Prototype.emptyFunction,
			afterChange: Prototype.emptyFunction,
			hover: false,
			linkSelector: 'li a',
			setClassOnContainer: false,
			activeClassName: 'active',
			defaultTab: 'first',
			autoLinkExternal: true,
			targetRegExp: /#(.+)$/,
			showFunction: Element.show,
			hideFunction: Element.hide
		};
		Object.extend(this.options,options || {});
		(typeof(this.options.linkSelector == 'string')
			? $(tab_list_container).getElementsBySelector(this.options.linkSelector)
			: this.options.linkSelector($(tab_list_container))
		).findAll(function(link){
			return (/^#/).exec(link.href.replace(window.location.href.split('#')[0],''));
		}).each(function(link){
			this.addTab(link);
		}.bind(this));
		this.containers.values().each(this.options.hideFunction);
		if(this.options.defaultTab == 'first')
			this.setActiveTab(this.links.first());
		else if(this.options.defaultTab == 'last')
			this.setActiveTab(this.links.last());
		else
			this.setActiveTab(this.options.defaultTab);
		var targets = this.options.targetRegExp.exec(window.location);
		if(targets && targets[1]){
			targets[1].split(',').each(function(target){
				this.links.each(function(target,link){
					if(link.key == target){
						this.setActiveTab(link);
						throw $break;
					}
				}.bind(this,target));
			}.bind(this));
		}
		if(this.options.autoLinkExternal){
			$A(document.getElementsByTagName('a')).each(function(a){
				if(!this.links.include(a)){
					var clean_href = a.href.replace(window.location.href.split('#')[0],'');
					if(clean_href.substring(0,1) == '#'){
						if(this.containers.keys().include(clean_href.substring(1))){
							$(a).observe('click',function(event,clean_href){
								this.setActiveTab(clean_href.substring(1));
							}.bindAsEventListener(this,clean_href));
						}
					}
				}
			}.bind(this));
		}
	},
	addTab: function(link){
		this.links.push(link);
		link.key = link.getAttribute('href').replace(window.location.href.split('#')[0],'').split('/').last().replace(/#/,'');
		this.containers[link.key] = $(link.key);
		link[this.options.hover ? 'onmouseover' : 'onclick'] = function(link){
			if(window.event)
				Event.stop(window.event);
			this.setActiveTab(link);
			return false;
		}.bind(this,link);
	},
	setActiveTab: function(link){
		if(!link)
			return;
		if(typeof(link) == 'string'){
			this.links.each(function(_link){
				if(_link.key == link){
					this.setActiveTab(_link);
					throw $break;
				}
			}.bind(this));
		}else{
			this.notify('beforeChange',this.activeContainer);
			if(this.activeContainer)
				this.options.hideFunction(this.activeContainer);
			this.links.each(function(item){
				(this.options.setClassOnContainer ? $(item.parentNode) : item).removeClassName(this.options.activeClassName);
			}.bind(this));
			(this.options.setClassOnContainer ? $(link.parentNode) : link).addClassName(this.options.activeClassName);
			this.activeContainer = this.containers[link.key];
			this.activeLink = link;
			this.options.showFunction(this.containers[link.key]);
			this.notify('afterChange',this.containers[link.key]);
		}
	},
	next: function(){
		this.links.each(function(link,i){
			if(this.activeLink == link && this.links[i + 1]){
				this.setActiveTab(this.links[i + 1]);
				throw $break;
			}
		}.bind(this));
		return false;
	},
	previous: function(){
		this.links.each(function(link,i){
			if(this.activeLink == link && this.links[i - 1]){
				this.setActiveTab(this.links[i - 1]);
				throw $break;
			}
		}.bind(this));
		return false;
	},
	first: function(){
		this.setActiveTab(this.links.first());
		return false;
	},
	last: function(){
		this.setActiveTab(this.links.last());
		return false;
	},
	notify: function(event_name){
		try{
			if(this.options[event_name])
				return [this.options[event_name].apply(this.options[event_name],$A(arguments).slice(1))];
		}catch(e){
			if(e != $break)
				throw e;
			else
				return false;
		}
	}
});
if(typeof(Object.Event) != 'undefined')
	Object.Event.extend(Control.Tabs);
