var postForm=true;

//APPEL DES PLUGINS ET AUTRE FONCTION DANS LE FICHIER
function setEcommercePage(){
	
	setQuantity($('.quantity_wrap'));
    
    setPrice();
    
  
    
    verifOrder();
    
    //MET EN PLACE LE SLIDER
    slider();
    setPriceSlider();
	
	
	addModalAddressLiv();
	editModalAddressLiv();
	delModalAddressLiv();
	setAddressLiv();
}
// = > BOUTON + - AUTOUR DE INPUT
	function setQuantity(elm){
		$(elm).find('.quantity').numeric();
		//animation camp quantity
		$(elm).find('.quantity_more').click(function(){
			var max = $(this).prev('.quantity').attr('rel').split('//');
			var elmQuantity = $(this).prev('.quantity');
			
			max = parseInt(max[1]);
			if(max==0)max=100000000;
			elmQuantity.attr('value', parseInt(elmQuantity.attr('value'))+1);
			if(parseInt(elmQuantity.attr('value'))>max) elmQuantity.attr('value',max);    
			
			//callBack
			setPrice();
			setAddressLiv();
			setPriceSlider(elmQuantity);

		});
		$(elm).find('.quantity_less').click(function(){
			var min = $(this).next('.quantity').attr('rel').split('//');
			var elmQuantity = $(this).next('.quantity');
			
			min = parseInt(min[0]);
			elmQuantity.attr('value', parseInt(elmQuantity.attr('value'))-1);
			if(parseInt(elmQuantity.attr('value'))<min) elmQuantity.attr('value',min);    
			
			//callBack
			setPrice();
			setAddressLiv();
			setPriceSlider(elmQuantity);
		});
		
		$(elm).find('.quantity').keyup(function(){
			var minMax = $(this).attr('rel');
			
			min = parseInt(minMax[0]);
			max = parseInt(minMax[1]);
			if(parseInt($(this).attr('value'))<min) $(this).attr('value',min);    
			if(parseInt($(this).attr('value'))>max) $(this).attr('value',max);    
			setPrice();
			setAddressLiv();
			setPriceSlider($(this));
		});
		$(elm).find('.quantity').focusout(function(){
			var minMax = $(this).attr('rel');		
			min = parseInt(min[0]);
			max = parseInt(max[0]);
			if(parseInt($(this).attr('value'))<min) $(this).attr('value',min);    
			if(parseInt($(this).attr('value'))>max) $(this).attr('value',max);    
			setPrice();
			setAddressLiv();
			setPriceSlider($(this));
		});
    
    
    
    
    
    
    
   
    
	}

// => CALCUL DES PRIX SUR STAGE_ONE.PHP
    function setPrice(){
        if($('.product_description').length){
            var priceTTC=0;
            var priceHT=0;
            var priceBundleTTC=parseInt($('#ttcBundleDefault').attr('value'));
            $('.quantity').each(function(){
                quantity = $(this).attr('value');
                tva = $(this).parent().next('.product_price').find('.taux_tva').attr('value');
				log(tva);
                uniqueHT = $(this).parent().next('.product_price').find('.ht').attr('value');
				
                uniqueBundleTTC = $(this).parent().next('.product_price').find('.ttcBundle').attr('value');
                $(this).parent().next('.product_price').find('span').html(round(uniqueHT*((tva/100)+1)*quantity));
                
                priceTTC = priceTTC + round(uniqueHT*((tva/100)+1)*quantity);
                priceHT = priceHT+round(uniqueHT*quantity);
                priceBundleTTC = priceBundleTTC+(uniqueBundleTTC*quantity);
            });
            $('#priceTTC').html(round(priceTTC));
            $('#priceHT').html(round(priceHT));
            $('#priceBundleTTC').html(round(priceBundleTTC));
        }
    }

// => VERIFIE QU'ON PEUT PASSER à l'étape suivante, ecomemrce
    function verifOrder(){
        $('#submit_order').click(function(){
			//si prix groupé inférieur a prix de base, on le signale dans une modal
            if(parseInt($('#priceBundleTTC').html()) < parseInt($('#priceTTC').html())){
                $('#bundleVSsimple').dialog({
                    width: 600,
                    resizable: false,
                    disabled:true,
                    draggable:false,
                    buttons: {
                        simpleOrder :function(){
                            $('#order').submit();
                        },
                        bundleOrder: function() {
							$('#bundleOrder').submit();  
                        }
                    },
                    open: function(event, ui) { 
                        $('#shouldBundlePrice').html($('#priceBundleTTC').html());
                        $('#shouldSimplePrice').html($('#priceTTC').html());
                        backOpac(true);
                        $(this).css('height', '100%');
                        $(this).dialog('option', 'position', 'center');
                    },close: function(){
                         backOpac(false);
                    }
                });
                endLoading("ttt");
            }else if(postForm==true){
				if($('#submit_order').attr('type')=='button')$('#order').submit();
			}else{
				$('#submit_order_dialog').dialog({
					width: 400,
					resizable: false,
					disabled:true,
					draggable:false,
					buttons: {
						ok: function() {
							$( this ).dialog('destroy');
							backOpac(false);
						}
					},
					open: function(event, ui) { 
						backOpac(true);
						$(this).css('height', '100%');
						$(this).dialog('option', 'position', 'center');
					},
					close: function(){
						backOpac(false);
					}
				});
				$(".ui-dialog-titlebar").css('display','block'); 
			}
        });
    }
// => SLIDER OFFRE GROUPEE
    function slider(){
        $("#sliderNumberBooks" ).slider({
			range: "min",
			value: 0,
			min: 0,
			max: 50,
			slide: function( event, ui ) {
				//
				$(this).parent().next('.quantity_wrap').find('.quantity').attr('value',ui.value);
                setPriceSlider($(this));
			}
		});
       
        $("#sliderNumberAccess").slider({
			range: "min",
			value: 5,
			min: 0,
			max: 50,
			slide: function( event, ui ) {
				//modifie champ quantity lorsque qu'on slide
				$(this).parent().next('.quantity_wrap').find('.quantity').attr('value',ui.value);
				setPriceSlider($(this));
			},
			change: function(event, ui) {
				//empeche le slider de descendre en dessous de 5
				if(ui.value<5)$(this).slider('value',5);
				//setPriceSlider($(this));
			}
		});
    }
// CALCUL PRIX SUR STAGE_BUNDLE_ONE.php
    function setPriceSlider(elm){
		setQuantitySlider(elm);
		
		if($('.slider_wrap').length){
            var priceTTC=parseInt($('#bundlePriceTTC').attr('value'));
            var priceHT=parseInt($('#bundlePriceHT').attr('value'));
            
            $('.quantity').each(function(){
                quantity = $(this).attr('value');
				$(this).parent().prev('.slider_wrap').find('div').slider('value',quantity);
				tva = $(this).parent().next('.slider_price').find('.taux_tva').attr('value');
                uniqueHT = $(this).parent().next('.slider_price').find('.ht').attr('value');
                
                $(this).parent().next('.slider_price').find('span').html(round(uniqueHT*((tva/100)+1)*quantity));
                
                priceTTC = priceTTC+(uniqueHT*((tva/100)+1)*quantity);
                
                priceHT = priceHT+(uniqueHT*((tva/100)+1)*quantity);
                
            });
            $('#priceTTC').html(round(priceTTC));
            $('#priceHT').html(round(priceHT));
        }
    }
	
// => MODIFIE LES QUANTITES SUR LE SLIDE
	function setQuantitySlider(elm){
		//MODIFICATION CHAMP INPUT
		if($(elm).attr('class')=="quantity" && $(elm).attr('id')=="book"){
			//augmente le nombre de livre et le nombre d'accès
			if(parseInt($(elm).attr('value'))>parseInt($('#access').attr('value')))$('#access').attr('value', $(elm).attr('value'));
		
		}else if($(elm).attr('class')=="quantity" && $(elm).attr('id')=="access"){
			//diminue le nombre d'accès et le nombre de livre
			if(parseInt($(elm).attr('value'))<parseInt($('#book').attr('value')))$('#book').attr('value', $(elm).attr('value'));
		
		}else if($(elm).attr('id')=="sliderNumberBooks"){
			//augmente le nombre de livre et le nombre d'accès
			elm = $(elm).parent().next('.quantity_wrap').find('.quantity');
			if(parseInt(elm.attr('value'))>parseInt($('#access').attr('value')))$('#access').attr('value', elm.attr('value'));
	
		}else if($(elm).attr('id')=="sliderNumberAccess"){
			//diminue le nombre d'accès et le nombre de livre
			elm = $(elm).parent().next('.quantity_wrap').find('.quantity');
			if(parseInt(elm.attr('value'))<parseInt($('#book').attr('value')))$('#book').attr('value', elm.attr('value'));
		}
		if(parseInt($('#access').attr('value'))<5){
			$('#access').attr('value',"5");
		}
	}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////ADRESSE DE LIVRAISON ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var numberBook = 0;
var restBookLiv =0;
var bookLiv =0;
var fraisLiv=0;

// DETERMINE NOMBRE DE LIVRE A LIVRER ET LES FRAIS DE LIVRAISON CORRESPONDANT
	function setAddressLiv(){
		if($('#numberBook').length){
			numberBook = $('#numberBook').attr('value');
			bookLiv=0;
			fraisLiv=0;
	
			$('.quantity').each(function(){
				bookLiv = parseInt($(this).attr('value'))+bookLiv;
				bookThis = parseInt($(this).attr('value'));
				
				//frais de livraison pour chaque ligne
				tarifLiv= parseInt($.trim($(this).parents('.lineOrder').find('.product_price .tarifLiv').attr('value')));
				fraisLiv = bookThis*tarifLiv + fraisLiv;
				$(this).parents('.lineOrder').find('.product_price span').html(bookThis*tarifLiv);
				
			});
			
			restBookLiv = numberBook - bookLiv;

			$('#restBookLiv').html(restBookLiv);
			$('#fraisLiv').html(fraisLiv);
			
			if(restBookLiv==0){
				$('#submit_order').parent().attr('id','');
				postForm=true;
				$('#warningLiv').hide();
				$('#restBookLiv').removeClass('error');
			}else if(restBookLiv!=0){
				//affiche warning et on empeche le post
				postForm=false;
				$('#restBookLiv').addClass('error');
				$('#warningLiv').show();
				$('#submit_order').parent().attr('id', 'btn_submit_account_disabled');
				$('#submit_order_dialog .lineModal').html($('#warningLiv').html());
				
			}
			
		}
	}


//AJOUTER ADRESSE DE LIVRAISON
	function addModalAddressLiv(){
		$('#addAdressLiv').click(function(){
			modalAddressLiv("new", $(this));
		});
	}
// => EDITER ADRESSE DE LIVRAISON
	function editModalAddressLiv(){
		$('.editAdressLiv').click(function(){
			modalAddressLiv($(this).attr('rel'), $(this));
		});
	}
// => SUPPRIMER ADRESSE DE LIVRAISON	
	function delModalAddressLiv(){
		if($('.lineOrder').length>1){
			$('.delAdressLiv').show();
			$('.delAdressLiv').click(function(){
				$(this).parents('.lineOrder').remove();
				delModalAddressLiv();
			});
		}else{
			$('.delAdressLiv').hide();
		}
		setAddressLiv();
	}
// => MODAL EDITION ADRESSE LIVRAISON
	function modalAddressLiv(id, elm){
		loading();
		log(id);
		$.ajax({
			type: "POST",
			url: domain+"/do/modal/gdm_modal_adress_liv.php",
			data: "profileId="+id+"&orderId=2&language="+$('#languageFiche').attr('value'),
			success: function(modal){
				$('#modal').html(modal);
				if($('#modalForm').length==0){
					errorModal();
				}else{
					$('#modalForm').dialog({
						width: 600,
						resizable: false,
						disabled:true,
						draggable:false,
						buttons: {
							cancel: function() {
								closeModal($(this));
								backOpac(false);
							},
							save: function() {
								var pass = require($('#modalFormPost'));
								if(pass==true){
									saveAddressLiv($('#modalFormPost').serialize(),elm);
									closeModal($('#modalForm'));
									backOpac(false);
								}
							}
						},
						open: function(event, ui) { 
							backOpac(true);
							$(this).css('height', '100%');
							$(this).dialog('option', 'position', 'center');
							
							
						},
						close: function(event, ui) { 
							backOpac(false);
							closeModal($(this));
						}
		
					});
					endLoading();
				}
			}
		});	
	}
// SAUVEGARDE ADRESSE LIVRAISON
	function saveAddressLiv(data, elm){
		$.ajax({
			type: "POST",
			url: domain+"/do/modal/gdm_modal_adress_liv.php",
			data: "save=true&"+data,
			success: function(newValue){
				
				var val = $.trim(newValue).split('SEP/');
				
				//nouvelle adresse
				if($(elm).attr('id')=="addAdressLiv"){
					//copie ligne existante
					$('.lineOrder:last').after('<div class="lineOrder">'+$('.lineOrder:last').html()+'</div>');
					//remplace description
					$('.lineOrder:last').find('.product_description').html(val[2]);
					
					//SET la quantity (si vous avez pas compris je suis bilingue ;) 
					$('.lineOrder:last').find('.quantity').attr('value','1');
					$('.lineOrder:last').find('.quantity').attr('name',$('#defaultProductId').attr('rel')+'['+val[0]+']');
				
					//Frais de livraison
					$('.lineOrder:last').find('.tarifLiv').attr('value',val[1]);
					
					
					
					////////////////////////EDIT AND DEL NOUVEAU LINEORDER//////////////////////
					//rel edit contient le profilId
					$('.lineOrder:last').find('.editAdressLiv').attr('rel',val[0]);
					
					$('.lineOrder:last').find('.editAdressLiv').click(function(){
						modalAddressLiv($(this).attr('rel'), $(this));
					});
					setQuantity($('.lineOrder:last').find('.quantity_wrap'));
					delModalAddressLiv();
					
				//edit adresse
				}else{
					//description
					$(elm).parents('.lineOrder').find('.product_description').html(val[2]);
					//quantity
					$(elm).parents('.lineOrder').find('.quantity').attr('name',$('#defaultProductId').attr('rel')+'['+val[0]+']');
					//frais livraison
					$(elm).parents('.lineOrder').find('.tarifLiv').attr('value',val[1]);
					
					//rel edit contient le profilId
					$(elm).parents('.lineOrder').find('.editAdressLiv').attr('rel',val[0]);

				}
				setAddressLiv();
			}
		});
	}

