
function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
}


function getUrlParam(parameter, defaultvalue){
    var urlparameter = defaultvalue;
    if(window.location.href.indexOf(parameter) > -1){
        urlparameter = getUrlVars()[parameter];
        }
    return urlparameter;
}


jQuery(document).ready(function($) {
	$("select.chosen-select").chosen({no_results_text: "Oops, nothing found!"});

   	$("#mobile-navigation li.menu-item-has-children > a").click(function(e) {
    e.preventDefault();
    $(this).parent().find('ul.sub-menu').toggle();
    });
});

/* Open */
function openNav() {
  document.getElementById("myNav").style.height = "100%";
}

/* Close */
function closeNav() {
  document.getElementById("myNav").style.height = "0%";
}

const validateEmail = (email) => {
	return email.match(
	  /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
	);
  };


var UDP_CLIENT_ID=0;

var UDP_SESSION_ID=0;

jQuery(document).ready(function($) {
  			// grab the initial top offset of the navigation
  		   	var stickyNavTop = $('header#navibar').offset().top;

  		   	// our function that decides weather the navigation bar should have "fixed" css position or not.
  		   	var stickyNav = function(){
  			    var scrollTop = $(window).scrollTop(); // our current vertical position from the top

  			    // if we've scrolled more than the navigation, change its position to fixed to stick to top,
  			    // otherwise change it back to relative
  			    if (scrollTop > stickyNavTop) {
  			        $('header#navibar').addClass('sticky');
  			    } else {
  			        $('header#navibar').removeClass('sticky');
  			    }
  			};

  			stickyNav();
  			// and run it again every time you scroll
  			$(window).scroll(function() {
  				stickyNav();
  			});


	$( "#udp_formation_details div.so-panel div.so-widget-sow-editor div.textwidget").each(function(index) { if($(this).html().trim() == '') { $(this).parent().parent().hide(); }});

	if($('a.also-on-demand-link').length){
		if(UDP_TRAINING.also_on_demand == 1){			
			$('a.also-on-demand-link').show();
		}else{
			$('a.also-on-demand-link').hide();
		}
	}

	if($('a.subscribe-session-button').length){		
		onSessionSelectionChange(true);
	}

	$( 'select[name="training_session"]' ).change(function() {
		onSessionSelectionChange(false);
	  });



	function getFieldValue(name,trim=false){
		var val = $('input[name="' + name + '"]').val();
		if(trim){
			val = val.trim();
		}

		return val;

	}

	function resetFieldValue(name){
		return $('input[name="' + name + '"]').val('');
	}

	function getTextareaFieldValue(name){
		return $('textarea[name="' + name + '"]').val();
	}


	function getSelectFieldValue(name){
		return $('select[name="' + name + '"]').val();
	}

	function resetTextareaFieldValue(name){
		$('textarea[name="' + name + '"]').val('');
	}


	function resetSelectFieldValue(name){
		$('select[name="' + name + '"]').val('');
	}

	function getCheckFieldValue(name){
		if($('input[name="' + name + '"]').prop('checked')) return 'Oui';
		return 'Non';
	}

	function resetCheckFieldValue(name){
		$('input[name="' + name + '"]').prop("checked", false);
	}

	function checkFieldNotEmpty(name){

		var type = 'input';

		if($('textarea[name="' + name + '"]').length)
			type = 'textarea';

		if($('select[name="' + name + '"]').length)
			type = 'select';

			if(!$(type + '[name="' + name + '"]').val() && $(type + '[name="' + name + '"]').is(':visible')){
				$('.error',$(type + '[name="' + name + '"]').parent()).show();
				$('p.has-error').show();
				return false;
			}else{
				$('.error',$(type + '[name="' + name + '"]').parent()).hide();
				return true;
			}
	}


	function checkFieldChecked(name){

		if(!$('input[name="' + name + '"]').prop('checked') && $('input[name="' + name + '"]').is(':visible')){
			$('.error',$('input[name="' + name + '"]').parent().parent()).show();
			$('p.has-error').show();
			return false;
		}else{
			$('.error',$('input[name="' + name + '"]').parent().parent()).hide();
			return true;
		}
	}

	function checkRadioFieldChecked(name){		
		if(!$('input[name="' + name + '"]:checked').val() && $('input[name="' + name + '"]').is(':visible')){
			$('.error',$('input[name="' + name + '"]').parent().parent().parent()).show();
			$('p.has-error').show();
			return false;
		}else{
			$('.error',$('input[name="' + name + '"]').parent().parent().parent()).hide();
			return true;
		}
	}

	function checkSubscription(){
		$('p.has-error').hide();
		var b = true;
		if(!checkFieldChecked('conditions')) b=false;
		if(!checkFieldChecked('prerequis_condition')) b=false;
		if(!checkRadioFieldChecked('user_type')) b=false;
		if(!checkFieldNotEmpty('firstname')) b=false;
		if(!checkFieldNotEmpty('lastname')) b=false;
		if(!checkFieldNotEmpty('phone')) b=false;
		if(!checkFieldNotEmpty('address')) b=false;
		if(!checkFieldNotEmpty('cp')) b=false;
		if(!checkFieldNotEmpty('city')) b=false;
		if(!checkFieldNotEmpty('society')) b=false;
		if(!checkFieldNotEmpty('howyouknow')) b=false;
		if(!checkFieldNotEmpty('society_address')) b=false;
		if(!checkFieldNotEmpty('society_cp')) b=false;
		if(!checkFieldNotEmpty('society_city')) b=false;
		return b;
	}


	function checkDemand(){
		$('p.has-error').hide();
		var b = true;
		if(!checkFieldChecked('conditions')) b=false;
		if(!checkFieldNotEmpty('demand_type')) { b=false; console.log('demand_type error'); }
		if(!checkFieldNotEmpty('firstname')) { b=false; console.log('firstname error'); }
		if(!checkFieldNotEmpty('lastname')) { b=false; console.log('lastname error'); }
		if(!checkFieldNotEmpty('phone')) { b=false; console.log('phone error'); }
		if(!checkFieldNotEmpty('address')) { b=false; console.log('address error'); }
		if(!checkFieldNotEmpty('cp')) { b=false; console.log('cp error'); }
		if(!checkFieldNotEmpty('city')) { b=false; console.log('city error'); }
		if(!checkFieldNotEmpty('theme')) { b=false; console.log('theme error'); }
		if(!checkFieldNotEmpty('public')) { b=false; console.log('public error'); }
		if(!checkFieldNotEmpty('group_need')) { b=false; console.log('group_need error'); }
		if(!checkFieldNotEmpty('dates')) { b=false; console.log('dates error'); }
		return b;
	}

	function checkDonation(){
		$('p.has-error').hide();
		var b = true;
		if(!checkFieldNotEmpty('firstname')) b=false;
		if(!checkFieldNotEmpty('lastname')) b=false;
		if(!checkFieldNotEmpty('phone')) b=false;
		if(!checkFieldNotEmpty('address')) b=false;
		if(!checkFieldNotEmpty('cp')) b=false;
		if(!checkFieldNotEmpty('city')) b=false;
		if(!checkFieldNotEmpty('society')) b=false;
		if(!checkFieldNotEmpty('society_address')) b=false;
		if(!checkFieldNotEmpty('society_cp')) b=false;
		if(!checkFieldNotEmpty('society_city')) b=false;
		return b;
	}

	function checkPreorder(){
		$('p.has-error').hide();
		var b = true;
		if(!checkFieldNotEmpty('firstname')) b=false;
		if(!checkFieldNotEmpty('lastname')) b=false;
		if(!checkFieldNotEmpty('phone')) b=false;
		if(!checkFieldNotEmpty('address')) b=false;
		if(!checkFieldNotEmpty('cp')) b=false;
		if(!checkFieldNotEmpty('city')) b=false;
		if(!checkFieldNotEmpty('society')) b=false;
		if(!checkFieldNotEmpty('society_address')) b=false;
		if(!checkFieldNotEmpty('society_cp')) b=false;
		if(!checkFieldNotEmpty('society_city')) b=false;
		return b;
	}

	function getRadioFieldValue(name){
		return $('input[name="' + name + '"]:checked').val();
	}



	function getSubscribeData(){
		return {
			socpeopleid: UDP_CLIENT_ID,
			sessionid: UDP_SESSION_ID,
			trainingid: UDP_TRAINING_ID,
			session_title: $("#subscribe_session_form .subscribe_title").html(),
			training_title: UDP_TRAINING.title,
			email: getFieldValue('email',true),
			firstname: getFieldValue('firstname'),
			lastname: getFieldValue('lastname'),
			phone: getFieldValue('phone'),
			address: getFieldValue('address'),
			cp: getFieldValue('cp'),
			city: getFieldValue('city'),
			user_type: getRadioFieldValue('user_type'),
			society_activity: getFieldValue('society_activity'),
			subscribe_for_cfm: getCheckFieldValue('subscribe_for_cfm'),
			society: getFieldValue('society'),
			society_address: getFieldValue('society_address'),
			society_cp: getFieldValue('society_cp'),
			society_city: getFieldValue('society_city'),
			tva_number: getFieldValue('tva_number'),			
			newsletter:getCheckFieldValue('newsletter'),
			custom_newsletter:getCheckFieldValue('custom_newsletter'),
			howyouknow: getFieldValue('howyouknow'),
			remark: getTextareaFieldValue('remark'),			
			contactEdited: ($('input[name="firstname"]').is(':visible'))?1:0
		};
	}

	function getDonationData(){
		return {
			socpeopleid: UDP_CLIENT_ID,
			donation_amount: $('#donation_amount').val(),
			email: getFieldValue('email',true),
			firstname: getFieldValue('firstname'),
			lastname: getFieldValue('lastname'),
			phone: getFieldValue('phone'),
			address: getFieldValue('address'),
			cp: getFieldValue('cp'),
			city: getFieldValue('city'),
			rrn: getFieldValue('rrn'),
			i_am_a_society: getCheckFieldValue('i_am_a_society'),
			society_activity: getFieldValue('society_activity'),
			subscribe_for_cfm: getCheckFieldValue('subscribe_for_cfm'),
			society: getFieldValue('society'),
			society_address: getFieldValue('society_address'),
			society_cp: getFieldValue('society_cp'),
			society_city: getFieldValue('society_city'),
			tva_number: getFieldValue('tva_number'),
			contactEdited: ($('input[name="firstname"]').is(':visible'))?1:0
		};
	}


	function getPreorderData(){
		return {
			socpeopleid: UDP_CLIENT_ID,
			email: getFieldValue('email',true),
			firstname: getFieldValue('firstname'),
			lastname: getFieldValue('lastname'),
			phone: getFieldValue('phone'),
			address: getFieldValue('address'),
			cp: getFieldValue('cp'),
			city: getFieldValue('city'),
			i_am_a_member: getCheckFieldValue('i_am_a_member'),
			promo_code: getFieldValue('promo_code'),
			i_am_a_society: getCheckFieldValue('i_am_a_society'),
			society_activity: getFieldValue('society_activity'),
			subscribe_for_cfm: getCheckFieldValue('subscribe_for_cfm'),
			society: getFieldValue('society'),
			society_address: getFieldValue('society_address'),
			society_cp: getFieldValue('society_cp'),
			society_city: getFieldValue('society_city'),
			tva_number: getFieldValue('tva_number'),
			contactEdited: ($('input[name="firstname"]').is(':visible'))?1:0
		};
	}


	function getDemandData(){
		return {
			socpeopleid: UDP_CLIENT_ID,
			email: getFieldValue('email',true),
			firstname: getFieldValue('firstname'),
			lastname: getFieldValue('lastname'),
			society_activity: getFieldValue('society_activity'),
			society: getFieldValue('society'),
			tva_number: getFieldValue('tva_number'),
			phone: getFieldValue('phone'),
			address: getFieldValue('address'),
			cp: getFieldValue('cp'),
			city: getFieldValue('city'),
			society_address: getFieldValue('address'),
			society_cp: getFieldValue('cp'),
			society_city: getFieldValue('city'),
			i_am_a_society: 'Oui',
			udp_contact: getFieldValue('udp_contact'),
			demand_type: getSelectFieldValue('demand_type'),
			theme: getTextareaFieldValue('theme'),
			more_info: getTextareaFieldValue('more_info'),
			public: getTextareaFieldValue('public'),
			group_need: getTextareaFieldValue('group_need'),
			duration: getFieldValue('duration'),
			dates: getFieldValue('dates'),
			newsletter: getFieldValue('newsletter'),
			custom_newsletter: getFieldValue('custom_newsletter'),
			remark: getTextareaFieldValue('remark'),
			contactEdited: ($('input[name="firstname"]').is(':visible'))?1:0
		};
	}

	function resetDemandData(){
		resetFieldValue('email');
		resetFieldValue('firstname');
		resetFieldValue('lastname');
		resetFieldValue('phone');
		resetFieldValue('address');
		resetFieldValue('cp');
		resetFieldValue('city');
		resetFieldValue('society_activity');
		resetFieldValue('society');
		resetFieldValue('tva_number');
		resetFieldValue('udp_contact');
		resetSelectFieldValue('demand_type');
		resetTextareaFieldValue('theme');
		resetTextareaFieldValue('more_info');
		resetTextareaFieldValue('public');
		resetTextareaFieldValue('group_need');
		resetFieldValue('duration');
		resetFieldValue('dates');
		resetCheckFieldValue('newsletter');
		resetCheckFieldValue('custom_newsletter');
		resetTextareaFieldValue('remark');
	}

	function resetSubscribeData(){

		resetFieldValue('email');
		resetFieldValue('firstname');
		resetFieldValue('lastname');
		resetFieldValue('phone');
		resetFieldValue('address');
		resetFieldValue('cp');
		resetFieldValue('city');
		resetCheckFieldValue('user_type');
		resetCheckFieldValue('subscribe_for_cfm');
		resetFieldValue('society_activity');
		resetFieldValue('society');
		resetFieldValue('society_address');
		resetFieldValue('tva_number');		
		resetCheckFieldValue('newsletter');
		resetCheckFieldValue('custom_newsletter');
		resetFieldValue('howyouknow');
		resetTextareaFieldValue('remark');
	}

	function resetDonationData(){

		resetFieldValue('email');
		resetFieldValue('firstname');
		resetFieldValue('lastname');
		resetFieldValue('phone');
		resetFieldValue('address');
		resetFieldValue('cp');
		resetFieldValue('city');
		resetFieldValue('rrn');
		resetCheckFieldValue('i_am_a_society');
		resetFieldValue('society');
		resetFieldValue('society_address');
		resetFieldValue('tva_number');
	}

	function resetPreorderData(){

		resetFieldValue('email');
		resetFieldValue('firstname');
		resetFieldValue('lastname');
		resetFieldValue('phone');
		resetFieldValue('address');
		resetFieldValue('cp');
		resetFieldValue('city');
		resetFieldValue('promo_code');
		resetCheckFieldValue('i_am_a_society');
		resetCheckFieldValue('i_am_a_member');
		resetFieldValue('society');
		resetFieldValue('society_address');
		resetFieldValue('tva_number');
	}

	function getCurrentSessionInfo(id){
		for(session_info of UDP_SESSIONS_INFO){
			if(session_info.id == id)	return session_info;
		}
		return null;
	}

	function getModulesDatesText(session){
		var text = "";

		for(module of session.modules){
			text += "<h6>" + module.title + "</h6>";
			text += "<p>" + module.datesText + " ( formateur: " + module.trainer + ")</p>";
		}
		return text;
	}

	function onSessionSelectionChange(firstLoad){

		var session_id = 0;

		if(firstLoad){
			session_id = getUrlParam('sessionId',0);
		}

		if(!session_id)
			session_id = $('select[name="training_session"] option:selected').val();

		if(session_id && UDP_SESSIONS_INFO){
			$(".more-information-link").hide();
			var session = getCurrentSessionInfo(session_id);
			if(session != null){

				if(UDP_TRAINING_ID != session.training_id){
					UDP_TRAINING_ID	= session.training_id;
				}
				$("a.course-detail-link").attr("href",'/formation?id=' + session.training_id);
				$(".session-info-training-title .session-info-value").html(session.training_title);
				$(".session-info-duration .session-info-value").html(session.duration_days_text);

				$(".session-info-trainers .session-info-value").html(session.trainers);
				$(".session-info-place .session-info-value").html(session.place);
				$(".session-infos").show();

				if(session.prerequis && session.prerequis.length > 3){
					$(".prerequis_text").html(session.prerequis);
					$(".prerequis_validation").show();					
				}else{
					$(".prerequis_validation").hide();
					$(".prerequis_text").html('');
				}

				if(session.is_long_training){
					$(".session-info-modules .session-info-value").html(getModulesDatesText(session));
					$(".session-info-dates").hide();
					$(".session-info-trainers").hide();
					$(".session-info-modules").show();
				}else{
					$(".session-info-dates .session-info-value").html(session.dates_text);
					$(".session-info-dates").show();
					$(".session-info-trainers").show();
					$(".session-info-modules").hide();
				}

				$( ".session-partner-item" ).each(function( index ) {
					$( this ).hide();
				});

				if(session.place_available && session.place_available > 0)
					$('.session-no-place-available').hide();
				else
					$('.session-no-place-available').show();

				for(var partner of session.partners ){
					$( '.session-partner-' +  partner).show();
				}
			}else{
				$(".session-infos").hide();
			}
		}else{
			$(".session-infos").hide();
			$( ".session-partner-item" ).each(function( index ) {
				$( this ).hide();
			});

			$(".subscribe-session-button").hide();
			$(".more-information-link").show();
		}
	}


	function initForm(){
		$('p.text-to-modify-client').hide();
		$('p.text-to-add-client').hide();
		$('div.all-fields').hide();
		$('div.fields-edition').hide();
		$('div.user_type_choice').hide();
		$('div.fields-society').hide();
		$( ".udp-form .error").each(function(index) {	$(this).hide(); });
		$( ".udp-form .has-error").hide();
		$( ".udp-form .form-error").hide();
	}

	function initSubscribeForm(){
		initForm();
		var training_session_date = $('select[name="training_session"] option:selected').html();
		UDP_SESSION_ID = $('select[name="training_session"] option:selected').val();
		var training_title = $('.training_title').html();
		$("#subscribe_session_form .subscribe_title").html('Inscription à la session ' + training_session_date);
		$("#subscribe_session_form .subscribe_training").html(training_title);
	}

	function initDemandForm(){
		initForm();
	}

	function initDonationForm(){
		initForm();
		var amount=$('#donation_amount').val();
		$('.donation_amount').html(amount);
		$('.field-rrn').hide();

		if(amount == '' || amount < 0){
			$('.invalid-amount').show();
			$('.search-email-field').hide();
		}else{
			$('.invalid-amount').hide();
			$('.search-email-field').show();
		}
	}

	function initPreorderForm(){
		initForm();
		var hasProduct = $('table.cartInfo-summary tbody tr').length;

		if(hasProduct == 0){
			$('.no-products').show();
			$('.search-email-field').hide();
		}else{
			$('.no-products').hide();
			$('.search-email-field').show();
		}
	}

	function showError(message){
		$(".udp-form .text-form-error").html(message);
		$(".udp-form .form-error").show();
	}


	$("a.subscribe_session_popup").click(function(){
		resetSubscribeData();
		initSubscribeForm();
	});

	$("a.donation_popup").click(function(){
		resetDonationData();
		initDonationForm();
	});

	$("a.preorder_popup").click(function(){
		resetPreorderData();
		initPreorderForm();
	});

	$("a.action-modify-client").click(function(){
		$('div.fields-edition').show();
		$('div.user_type_choice').show();
		$('p.text-to-modify-client').hide();
	});

	$('input[name="user_type"]').change(function() {		
		const selectedValue = $('input[name="user_type"]:checked').val();		
		if (selectedValue === 'i_am_a_society') {
			$('div.fields-society').show();
		} else {
			$('div.fields-society').hide();
		}

		if (selectedValue === 'one_formaction') {
			$('div.one_formaction-alert').show();
			$('div.fields-edition').hide();
			$('div.submit-wrapper').hide();
			$('p.text-to-modify-client').hide();
		} else {
			$('div.one_formaction-alert').hide();
			$('div.fields-edition').show();
			$('div.submit-wrapper').show();
		}

	});


	$(".udp-form button.validate_email").click(function(event){
			event.preventDefault();

			try{

			if($( "#subscribe_session_form" ).length ){
				initSubscribeForm();
			}
			else if($( "#custom_demand_form" ).length){
				initDemandForm();
			}else{
				initForm();
			}

			var email=$('.udp-form input[name="email"]').val().trim();
			if(validateEmail(email)){
				$('.error',$('.udp-form input[name="email"]').parent().parent()).hide();
				$.get( "/wp-content/themes/udp/udp-ajax.php?action=check_client&email=" + email, function( data ) {
				if(data){
					var client=JSON.parse(data);
					if(client.id){
						$('span.client-firstname').html(client.firstname);
						$('span.client-lastname').html(client.lastname);
						$('div.all-fields').show();						
						
						if(!client.hasRNN){
							$('.field-rrn').show();
						}

						if(client.hasAddress){
							$('p.text-to-modify-client').show();
							$('p.text-to-add-client').hide();
						}
						else{
							$('p.text-to-modify-client').hide();
							$('div.user_type_choice').show();
							$('div.fields-edition').show();
						}
						
						UDP_CLIENT_ID = client.id;
					}else{
						$('p.text-to-modify-client').hide();
						$('div.all-fields').show();						
						$('p.text-to-add-client').show();
						$('div.user_type_choice').show();
						$('div.fields-edition').show();
						UDP_CLIENT_ID=0;
					}

				}else{
					alert('check_client return no data');
				}
				});
			}else{
				$('.error',$('.udp-form input[name="email"]').parent().parent()).show();
				$('.invalid-email').html(email);
			}

		}catch(error){
			alert('error when check_client, error is ' + JSON.stringify(error));
		}
	});


	$("button.subscribe:not(:disabled)").click(function(event){
			event.preventDefault();			
			$(".udp-form .form-error").hide();
			if(checkSubscription()){
				$(this).attr('disabled','true');
				$.post( "/wp-content/themes/udp/udp-ajax.php?action=subscribe",getSubscribeData(), function( data ) {
					if(data != ''){
						var resp=JSON.parse(data);
						if(resp == null){
							showError('pas de réponse du service web data:' + data);
						}
						else {
							if(resp.status != 'success'){
								showError('status: ' + resp.status + ' message: ' + resp.message);
							} else{

							$('#subscribe_session_form .mfp-close').trigger("click");
							resetSubscribeData();
							initSubscribeForm();
							$('a.confirmation_popup').trigger('click');
							}
						}
					}else{
						showError('pas de réponse du service web');
					}

					$(this).removeAttr('disabled');
				});
			}else{

				$(this).removeAttr('disabled');
			}
	});


	$("button.demand:not(:disabled)").click(function(event){
		event.preventDefault();		
		$(".udp-form .form-error").hide();
		if(checkDemand()){
			$(this).attr('disabled','true');
			$.post( "/wp-content/themes/udp/udp-ajax.php?action=demand",getDemandData(), function( data ) {
				if(data != ''){
					var resp=JSON.parse(data);
					if(resp == null){
						showError('pas de réponse du service web data:' + data);
					}
					else {
						if(resp.status != 'success'){
							showError('status: ' + resp.status + ' message: ' + resp.message);
						} else{


						resetDemandData();
						initDemandForm();
						$('a.confirmation_popup').trigger('click');
						}
					}
				}else{
					showError('pas de réponse du service web');
				}
				$(this).removeAttr('disabled');
			});

		}else{
			$(this).removeAttr('disabled');
		}
	});


	$("button.donation").click(function(event){
		event.preventDefault();
		$(".udp-form .form-error").hide();
		if(checkDonation()){
			$.post( "/wp-content/themes/udp/udp-ajax.php?action=donation",getDonationData(), function( data ) {
				if(data != ''){
					var resp=JSON.parse(data);
					if(resp == null){
						showError('pas de réponse du service web data:' + data);
					}
					else {
						if(resp.status != 'success'){
							showError('status: ' + resp.status + ' message: ' + resp.message);
						} else{
						window.location.replace(resp.redirectUrl);
						}
					}
				}else{
					showError('pas de réponse du service web');
				}
			});

		}
	});


	  $("button.preorder:not(:disabled)").click(function(event){
		event.preventDefault();
		
		$(".udp-form .form-error").hide();
		if(checkPreorder()){
			$(this).attr('disabled','true');
			$.post( "/wp-content/themes/udp/udp-ajax.php?action=preorder",getPreorderData(), function( data ) {
				if(data != ''){
					var resp=JSON.parse(data);
					if(resp == null){
						showError('pas de réponse du service web data:' + data);
						$(this).removeAttr('disabled');
					}
					else {
						if(resp.status != 'success'){
							showError('status: ' + resp.status + ' message: ' + resp.message);
							$(this).removeAttr('disabled');
						} else{
						window.location.replace('/pre-commande-envoyee');
						}
					}
				}else{
					showError('pas de réponse du service web');
				}
			});

		}
	});

});


/* CART MANAGEMENT */


jQuery(document).ready(function($) {

	function addProduct(productId){
		$.post( "/wp-content/themes/udp/udp-ajax.php?action=addProduct",{'productId' : productId}, function( data ) {
			if(data != ''){
				console.log(data);
				var resp=JSON.parse(data);
				if(resp == null){
					console.log('pas de réponse du service web data:' + data);
				}
				else {
					if(resp.status != 'success'){
						console.log('status: ' + resp.status + ' message: ' + resp.message);
					} else{
						refreshCartInfo();
					}
				}
			}else{
				console.log('pas de réponse du service web');
			}
		});
	}
	
	function modifyProductQuantity(productId,quantity){
		$.post( "/wp-content/themes/udp/udp-ajax.php?action=modifyProductQuantity",{'productId' : productId, 'quantity' : quantity}, function( data ) {
			if(data != ''){
				console.log(data);
				var resp=JSON.parse(data);
				if(resp == null){
					console.log('pas de réponse du service web data:' + data);
				}
				else {
					if(resp.status != 'success'){
						console.log('status: ' + resp.status + ' message: ' + resp.message);
					} else{
						refreshCartInfo();
					}
				}
			}else{
				console.log('pas de réponse du service web');
			}
		});
	}
	
	function removeProduct(productId){
		$.post( "/wp-content/themes/udp/udp-ajax.php?action=removeProduct",{'productId' : productId}, function( data ) {
			if(data != ''){
				console.log(data);
				var resp=JSON.parse(data);
				if(resp == null){
					console.log('pas de réponse du service web data:' + data);
				}
				else {
					if(resp.status != 'success'){
						console.log('status: ' + resp.status + ' message: ' + resp.message);
					} else{
						refreshCartInfo();
					}
				}
			}else{
				console.log('pas de réponse du service web');
			}
		});
	}

	function refreshCartInfo(){
		console.log("refreshCartInfo");
		if($(".cartInfo-summary").length){
			console.log("refreshCartInfo call getCartInfo");
			$.get( "/wp-content/themes/udp/udp-ajax.php?action=getCartInfo", function( data ) {
				if(data){
					console.log(data);
					var cart=JSON.parse(data);
					console.log(cart);
					$('.cartInfo-quantity').each(function(){
						$(this).html(cart['quantity']);
					});

					$('.cartInfo-total').each(function(){
						$(this).html(cart['total'] + ' €');
					});

					$('.cartInfo-totalMember').each(function(){
						$(this).html(cart['total_member'] + ' €');
					});

					$('table.cartInfo-summary tbody').html('');
					if(cart.items.length){
						for(let item of cart.items){
							$('table.cartInfo-summary tbody').append('<tr>'
							+ '<td><img src="/products/' + item.product.reference + '/' + item.product.images[0] + '"/></td>'							
							+ '<td>' + item.product.title + '</td>' 
							+ '<td><input type="number" class="cartModifyProductQuantity" name="price" value="' + item.quantity + '" data--product-id="' + item.product.id + '"></td>'
							+ '<td>' + item.total_price + '€' + ((item.total_price_member >0)? '<br/> Membre:' + item.total_price_member + '€' : '') +  '</td>'
							+ '<td><div class="cartRemoveProduct icon dripicons-trash" data--product-id="' + item.product.id + '"></div></td>'
							+ '</tr>'
							);
						}
					}else {
						$('table.cartInfo-summary tbody').append("<tr class=\"no-product-text\"><td colspan=\"6\">Vous n'avez actuellement aucun produit dans votre panier</td></tr>");
					}

	
				}else{
					alert('refreshCartInfo' +  data);
				}
			});
		}
	}


	refreshCartInfo();

	$(document).on('click','.cartAddProduct',function() {
		addProduct($(this).attr('data--product-id'));
	  });

	  $(document ).on('click','.cartRemoveProduct',function() {
		removeProduct($(this).attr('data--product-id'));
	  });

	  $(document ).on('change','.cartModifyProductQuantity',function() {
		modifyProductQuantity($(this).attr('data--product-id'),$(this).val());
	  });

	  $(document ).on('click','.cartModifyProductQuantity',function() {
		modifyProductQuantity($(this).attr('data--product-id'),$("input",$(this).parent()).val());
	  });
	 
	  
	  
});