/* Fonctions JS spécifiques au panier */


/**
* Fonction qui fait afficher 2 chiffres après la virgule dans les totaux en bas de page du l'étape 1 du panier.
*/
function affiche2ChiffresApresVirgule()
{
	$("#prixAssurance").text(parseFloat($("#prixAssurance").text()).toFixed(2));
	$("table[class=totalDossier] tr[class!=totalLine] td[class=priceCell] span").each(function ()
	{
		$(this).text(parseFloat($(this).text()).toFixed(2));
	}
	);

	$("table[class=totalDossier] tr[class=totalLine] td[class=priceCell] span em").each(function ()
	{
		$(this).text(parseFloat($(this).text()).toFixed(2));
	}
	);
	$("#totalPanierHaut").text(parseFloat($("#totalPanierHaut").text()).toFixed(2));
}

function sauverTotauxSession()
{
	var url = "ajax/save_panier_session.ajax.php";

	// Sauvegarde des totaux du dossier dans la session
	$.post(url, {champ:"recapTotaux_totalHebergement", valeur:$("#totalHebergement").text()}, function (data) {});
	$.post(url, {champ:"recapTotaux_totalOptionsHebergement", valeur:$("#totalOptionsHebergement").text()}, function (data) {});
	$.post(url, {champ:"recapTotaux_totalPrestationDossier", valeur:$("#totalPrestationDossier").text()}, function (data) {});
	$.post(url, {champ:"recapTotaux_totalMountainRiders", valeur:$("#totalMountainRiders").text()}, function (data) {});
	$.post(url, {champ:"recapTotaux_totalAssurance", valeur:$("#totalAssurance").text()}, function (data) {});
	$.post(url, {champ:"recapTotaux_totalFraisDossier", valeur:$("#totalFraisDossier").text()}, function (data) {});
	$.post(url, {champ:"recapTotaux_totalRemise", valeur:$("#totalRemise").text()}, function (data) {});
	$.post(url, {champ:"recapTotaux_totalPanier", valeur:$("#totalPanierBas").text()}, function (data) {});
	// Fin sauvegarde des totaux du dossier

}

function updateTotalBasket()
{
	$("#totalPanierBas").text(0);
	$("table[class=totalDossier] tr[class!=totalLine] td[class=priceCell] span").each(function ()
	{
		var total = parseFloat($("#totalPanierBas").text());
		if ($(this).attr("id") != "totalAssurance" && $(this).attr("id") != "totalFraisDossier")
		{
			if ($(this).attr("id") == "totalRemise")
			{
				total -= parseFloat($(this).text());
			} else {
				total += parseFloat($(this).text());
			}
		}
		$("#totalPanierBas").text(total);
		var tauxAssurance = parseFloat($("#tauxAssurance").val());
		var totalAssurance = (total  * tauxAssurance) / 100;
		$("#prixAssurance").text(totalAssurance.toFixed(2));
//		alert(total + " || " + tauxAssurance + " || " + totalAssurance);

	});

	if ($("#assurance:checked").length > 0)
	{
		$("#totalAssurance").text($("#prixAssurance").text());
	}
	$("#totalPanierBas").text(parseFloat($("#totalFraisDossier").text())+parseFloat($("#totalPanierBas").text())+parseFloat($("#totalAssurance").text()));
	$("#totalPanierHaut").text($("#totalPanierBas").text());

	affiche2ChiffresApresVirgule();
	sauverTotauxSession()
}

function calculOptionsParticipant(pParticipant, pNumOption, pTypeOption)
{
	// Reconstruction de l'id de l'option sélectionnée
	id_select = 'prestation_' + pParticipant + '_' + pNumOption + '_' + pTypeOption;
	$("#"+id_select+" option:selected").each(function () {

		if ($("#bt_"+id_select+" span").text().toLowerCase().trim() == "supprimer")
		{
		// Cas pour la suppression d'une option
			var infosOption = $(this).val().split("_");

			$("#prestation_"+pParticipant+"_"+pTypeOption).val(0);
			//$("#h3_prestation_"+pParticipant+"_"+pTypeOption+" em").text(0);
			$("#h3_prestation_"+pParticipant+"_"+pTypeOption+" em").text( parseFloat( $("#h3_prestation_"+pParticipant+"_"+pTypeOption+" em").text() ) - parseFloat(infosOption[1]) );
			$("#bt_"+id_select+" span").text("ajouter");

			var url = 'ajax/save_panier_session.ajax.php';
			$.post(url, {champ:"participants_" + pParticipant + "_options_" + pTypeOption, valeur:infosOption[0], idPrix: infosOption[2], suppression:1}, function (data) {});
		} else {
		// Cas pour l'ajout d'une option
			var infosOption = $(this).val().split("_");

			// Initialisation du champs hidden et de l'affichage du prix
			//$("#prestation_"+pParticipant+"_"+pTypeOption).val($(this).val());
			//$("#h3_prestation_"+pParticipant+"_"+pTypeOption+" em").text(infosOption[1]);
			$("#h3_prestation_"+pParticipant+"_"+pTypeOption+" em").text( parseFloat( $("#h3_prestation_"+pParticipant+"_"+pTypeOption+" em").text() ) + parseFloat(infosOption[1]) );

			//Mise à jour des libellés des boutons
			//$("#optionSlider_prestation_"+pParticipant+"_"+pTypeOption+" a[class~=btn_purple_small] > span").text("ajouter");
			$("#bt_"+id_select+" span").text("supprimer");
			var url = 'ajax/save_panier_session.ajax.php';
			$.post(url, {champ:"participants_" + pParticipant + "_options_" + pTypeOption, valeur:infosOption[0], idPrix: infosOption[2]}, function (data) {});
		}
		$("#h3_prestation_"+pParticipant+"_"+pTypeOption+" em").text( parseFloat( $("#h3_prestation_"+pParticipant+"_"+pTypeOption+" em").text()).toFixed(2) );
		//Calcul du nouveau total pour le participant
		calculTotalPrestationParticipant(pParticipant)

		// Mise à jour du total des prestations (bas de page)
		$("#totalPrestationDossier").text(0);
		$("ul[class=optionSlider] > li > h3 em").each(function () {
			var total = parseFloat($("#totalPrestationDossier").text());
			total += parseFloat($(this).text());
			$("#totalPrestationDossier").text(total);
		});

		// Mise à jour du total du panier
		updateTotalBasket();
		
	});
}
function calculTotalPrestationParticipant(pParticipant)
{
	//Remise à zéro du total pour le participant
	$("#total_presta_"+pParticipant).text(0);
	$("#optionSlider_"+pParticipant+" > li > h3 em").each(function (total) {
		var total = parseFloat($("#total_presta_"+pParticipant).text());
		total += parseFloat($(this).text());
		$("#total_presta_"+pParticipant).text(total);
	});
		
	if ($("#selectFormuleHebergement_"+pParticipant).length)
	{
			var hebParticipant = parseFloat($("#selectFormuleHebergement_"+pParticipant+" option:selected").val().split("_")[3]);
		$("#total_presta_"+pParticipant).text(hebParticipant+parseFloat($("#total_presta_"+pParticipant).text()));
		$.ajax({
			async: false,
			type: "POST",
			url: 'ajax/save_panier_session.ajax.php',
			data : "champ=participants_" + pParticipant + "_totalPrestations&valeur=" + $("#total_presta_"+pParticipant).text()
		});
	}
	
  if ($('#total_presta_' + pParticipant).text() != '0')
	{       
    $('#total_presta_' + pParticipant).parent('strong').addClass('blueBox');
  }else{
    $('#total_presta_' + pParticipant).parent('strong').removeClass();
  }
	$("#total_presta_"+pParticipant).text( parseFloat($("#total_presta_"+pParticipant).text()).toFixed(2) );

}

function toggleInsurance()
{
	if ($("#assurance:checked").length > 0)
	{
		$("#totalAssurance").text($("#prixAssurance").text());
		var url = 'ajax/save_panier_session.ajax.php';
		$.post(url, {champ:"souscriptionAssurance" , valeur:1}, function (data) {});
	} else {
		$("#totalAssurance").text(0);
		var url = 'ajax/save_panier_session.ajax.php';
		$.post(url, {champ:"souscriptionAssurance" , valeur:0}, function (data) {});
	}
	updateTotalBasket();
}

function toggleMountainRiders()
{
	if ($("#mountainRiders:checked").length > 0)
	{
		$("#totalMountainRiders").text($("#prixMountainRiders").text());

		var url = 'ajax/save_panier_session.ajax.php';
		$.post(url, {champ:"mountainRiders" , valeur:1}, function (data) {});
	} else {
		$("#totalMountainRiders").text(0.00);

		var url = 'ajax/save_panier_session.ajax.php';
		$.post(url, {champ:"mountainRiders" , valeur:0}, function (data) {});
	}
	updateTotalBasket();
}

function saveSession(obj)
{
	var url = "ajax/save_panier_session.ajax.php";
	var chNom = $(obj).attr("name").split("_");
	
	if ( chNom[0] == "selectFormuleHebergement") {
		var infosFormules = $(obj).val().split("_");
		$.post(url, {champ:"participants_"+chNom[1]+"_hebergement", valeur:infosFormules[0]}, function (data) {});
		$.post(url, {champ:"participants_"+chNom[1]+"_formule", valeur:infosFormules[1]}, function (data) {});
		updatePrixPersonne();
	} else {
		$.post(url, {champ:$(obj).attr("name"), valeur:$(obj).val()}, function (data) {});
	}
}

function updatePrixPersonne() {
	var total = 0;
	var totalRemise = 0;
	
	$("#mainContent_panier p.formuleHebergement option:selected").each(function () {
		var infosOpt = $(this).val().split("_");
		var infosName = $(this).parent().attr('name').split("_")
		total = total+parseFloat(infosOpt[2]);
		totalRemise = totalRemise+parseFloat(infosOpt[3]);
		calculTotalPrestationParticipant(infosName[1]);
	})
	if ( $("#mainContent_panier p.formuleHebergement").length )
	{
		$("#totalHebergement").text(total);
		var remise = (total-totalRemise);
		$("#totalRemise").text((total-totalRemise).toFixed(2));
		$("#totalHebDroite").text(totalRemise.toFixed(2));
	}
	updateTotalBasket();
	
}

function valid_participants(pNbParticipants,checkAllParts)
{
  var prefix = "_part";
	var okPanier = true;
  for (i=0;i<pNbParticipants;i++)
  {
  		if(checkAllParts || i == 0)
  		{
  			if(!checkMainInfo(prefix + i))
  			{
  				return false;	
  			}
		}
	  
	  if ($('#selectFormuleHebergement_'+i).length && $('#selectFormuleHebergement_'+i+' option:selected').val() == "0_0_0_0")
	  {
	    alert(get_trad_champ("formule_obligatoire_participant") + parseInt(i+1));
	    return false;
	  }
	  
	  var iParticipant = i+1;
	  var ulParticipant = '#optionSlider_'+parseInt(i); //+' div.optionSlider_content';

	  $(ulParticipant+" h3").each(
	  	function () {
  			if (parseFloat($(this).find('em').text()) != 0.00) {
  			
  				if(!checkMainInfo(prefix + i))
	  			{
	  				okPanier = false;
	  				return false;	
	  			}
  				
		  		var infosTypePackage = $(this).attr('id').split('_');
	  			
	  			var mandatoryInfos = $('#co_prestation_' + infosTypePackage[3]).val().split(';');

	  			// Vérification de la validité de la valeur
	  			for (k=0; k<mandatoryInfos.length; k++)
	  			{
	  				mandatoryInfos[k] = mandatoryInfos[k].split('|');
		  			var mandatoryField = mandatoryInfos[k][0] + parseInt(i);

		  			var myValue = $('#'+mandatoryField).val();
		  			switch (mandatoryInfos[k][1])
		  			{
		  				case 'date':
								var reg=new RegExp("^[0-9]{2}/[0-9]{2}/[0-9]{4}$","g");
								if (!reg.test(myValue))
				  			{
							    okPanier = false;
				  			}
				  			break;
				  		case 'int':
				  			if ( (myValue == '') || (myValue != parseInt(myValue)) ) {
							    okPanier = false;
				  			}
				  			break;
				  		case 'float':
				  			if ( (myValue == '') || (myValue != parseFloat(myValue)) ) {
							    okPanier = false;
				  			}
				  			break;
				  		case 'numeric':
				  			if ( (myValue == '') || !isNaN(myValue) ) {
							    okPanier = false;
				  			}
				  			break;
				  		default:
				  			if (myValue == '') {
							    okPanier = false;
				  			}
				  			break;
		  			}
		  			if (!okPanier) {
					    alert(get_trad_champ(mandatoryInfos[k][2]) + parseInt(iParticipant));
		  				return false;
		  			}
		  		}
			  }
	  	});
  	if (!okPanier) {
  		
  		return okPanier;
  	}
  }
	
	pleaseWaitLayer(true);
  return okPanier;
}

function verifPackSelectionne(pIdSelect, pLibAjout, pLibSupprimer)
{
	var infosPackage = pIdSelect.split("_");

	if ($("#bt_"+pIdSelect+" span").text().toLowerCase().trim() == pLibSupprimer.toLowerCase().trim()) {
		$("#"+id_select+" option:selected").each(function () {
			var infosOption = $(this).val().split("_");
			
			var url = 'ajax/save_panier_session.ajax.php';
			$.post(
				url,
				{champ:"participants_" + infosPackage[1] + "_options_" + infosPackage[3], valeur:infosOption[0], idPrix: infosOption[2]},
				function (data) {});
		});
		CalculTotalTypePackageParticipant(infosPackage[3], infosPackage[1], pLibSupprimer);

		// Mise à jour du total des prestations (bas de page)
		$("#totalPrestationDossier").text(0);
		$("ul[class=optionSlider] > li > h3 em").each(function () {
			var total = parseFloat($("#totalPrestationDossier").text());
			total += parseFloat($(this).text());
			$("#totalPrestationDossier").text(total.toFixed(2));
		});

	}
}

// Fonction qui calcul le total pour un type de package donné pour un participant donné
function CalculTotalTypePackageParticipant (pTypePackage, pParticipant, pLibSupprimer)
{
	var totalPackageParticipant = 0;
	
	$("#optionSlider_prestation_"+pParticipant+"_"+pTypePackage+" option:selected").each( function() {
		var idSelect = $(this).parent().attr('id');
		var idBtSelect = 'bt_'+idSelect;
		var infosOption = $(this).val().split("_");
		
		if ( $('#'+idBtSelect+" span").text().toLowerCase().trim() == pLibSupprimer.toLowerCase().trim()) {
			totalPackageParticipant += parseFloat(infosOption[1]);
		}
	});
	
	$("#h3_prestation_"+pParticipant+"_"+pTypePackage+" em").text( totalPackageParticipant.toFixed(2) );
	calculTotalPrestationParticipant(pParticipant);
	updateTotalBasket();
}

function CalculTotalTypePackageParticipantPourTous(pLibSupprimer)
{
	var nbParticipant = $("#selectNumParticipant option:selected").val();
	
	for (i=0; i<nbParticipant; i++) {
		$("#optionSlider_"+i+" h3").each( function() {
			var infosH3 = $(this).attr('id').split('_');
			CalculTotalTypePackageParticipant(infosH3[3], i, pLibSupprimer);
		});
	}
}

function validPanier()
{
	var nbParticipants = $("#selectNumParticipant :selected").val();
	if ($("#assurance:checked").length > 0)
	{
		return valid_participants(nbParticipants,true);
	}
	return valid_participants(nbParticipants,false);
}


function copyToMainElement(obj)
{
	var elementId = $(obj).attr("id").split("_presta_");
	if(elementId.length == 2)
	{	
		mainElementId = elementId[0];
		if(document.getElementById(mainElementId))
		{
			$("#"+mainElementId).val($(obj).val());
		}
		$("#"+mainElementId).trigger("onblur");
	}
}

function copyToOtherElement(obj,other)
{
	var elementId = $(obj).attr("id").split("_presta_");
	if(elementId.length == 2)
	{	
		mainElementId = elementId[0];
		otherElementId = mainElementId + "_presta_" + other;
		if(document.getElementById(otherElementId))
		{
			$("#"+otherElementId).val($(obj).val());
		}
	}
		
}

function checkMainInfo(prefix)
{

	if (document.getElementById("civMme" + prefix).checked == false && document.getElementById("civMlle" + prefix ).checked == false && document.getElementById("civMr" + prefix).checked == false)
	{
		alert(get_trad_champ("civilite_obligatoire_participant") + parseInt(i+1));
	     	return false;
	}
	if (document.getElementById("nom" + prefix ).value == "")
	{
		alert(get_trad_champ("nom_obligatoire_participant") + parseInt(i+1));
	     	return false;
	}

	if (document.getElementById("prenom" + prefix ).value == "")
	{
		alert(get_trad_champ("prenom_obligatoire_participant") + parseInt(i+1));
	    	return false;
	}	
	return true;
}
