/**
 * @version 1.0
 *
 * @copyright Copyright 2009 WnG Solutions Sàrl, all rights reserved
 * @author Dorian Villet <dorian.villet AT wng DOT ch>
 * @package sondage_prohelvetia
 */

/**
 * Gestion du javascript pour tout le site
 */
$(document).ready(function() {
			
	/*
	 * Affichage d'un loader lors des requêtes AJAX
	 */
	$().ajaxStart(function() {
		if (!($('#contentModal').hasClass('contentModalLoading'))) $('#contentModal').prepend('<div class="contentModalLoading" style="display: none;">Please wait... <span class="hideMe">loading...</span></div>');
		$('#contentModal .contentModalLoading').show();
	}).ajaxStop(function() {
		$('#contentModal .contentModalLoading').hide();
	});
								
	/*
	 * Login
	 */
	var manageLoginFields = function() {
		
		// On récupère la valeur du champ
		var value = $(this).val();
		
		// On vide le champ si c'est la valeur par défaut
		if (value == 'Login' || value == 'Password') $(this).val('');
		
		// On change le type du champ de mot de passe
		if (value == 'Password') {
			
			// On ajoute après un input en champ password
			$('#parent_password_text')
				.after($('<input />')
					.addClass('text')
					.attr({
						type: 'password',
						name: 'parent_password',
						id: 'parent_password'
					})
				)
				.hide();
			
			// On cache cet input et on affiche le nouveau
			$('#parent_password').focus();
		}
	};
	
	$('#parent_username, #parent_password_text').live('click', manageLoginFields);
	$('#parent_username, #parent_password_text').focus(manageLoginFields);
	$('#parent_username, #parent_password_text').blur(manageLoginFields);
	
	/*
	 * Calendrier
	 */

	// Année de naissance
	applyDatepicker('#birthdate', {
		changeMonth: true,
		changeYear: true,
		showOn: 'focus',
		minDate: new Date(1992, 1 - 1, 1),
		maxDate: '-8Y'
	});

	// Dates d'arrivée et de départ
	applyDatepicker('.changeToCalendar.futureDate', {
		changeMonth: true,
		changeYear: true,
		showOn: 'focus',
		minDate: '+1D',
		maxDate: '+2Y'
	});
	
	/*
	 * Gestion des tableaux
	 */
	$('table tbody tr').hover(function() { hoverUp($(this)); }, function() { hoverDown($(this)); });
	
	/*
	 * Gestion des "pseudos liens*
	 */

	// Variable pour le style des (pseudos) liens
	var anchorUp = { color: '#f6c520', background: '#2d2d2d' };
	var anchorDown = { color: '#3e3e3e', background: 'none' };
	
	$('.anchorLike').hover(
		function() { $(this).css(anchorUp); },
		function() { $(this).css(anchorDown); }
	);
	$('ul.gallery:not(.noHover) li').hover(
		function() { $('ul.gallery li.' + $(this).attr('class') + ' span.label').css(anchorUp); },
		function() { $('ul.gallery li.' + $(this).attr('class') + ' span.label').css(anchorDown); }
	);
	
	/*
	 * Gestion des menus
	 */
	 
	// Fix pour Opera
	$('#menus ul.menuSub').css('display', 'none');
	
	// On gère l'affichage du menu secondaire
	$('#menus ul.menuMain li').hover(
		function() { $(this).find('ul.menuSub:first').show(); },
		function() { $(this).find('ul.menuSub:first').hide(); }
	);
	
	// On gère la classe de l'élément du menu principal qui contient le menu secondaire
	$('#menus ul.menuSub').hover(
		function() { if (!$(this).parent().hasClass('active')) $(this).parent().addClass('active temp'); },
		function() { if ($(this).parent().hasClass('temp')) $(this).parent().removeClass('active'); }
	);
	
	/*
	 * Gestion de la galerie photo
	 */
	$('#photosGallery li').live('click', function() {
			
		// On récupère le titre de la galerie
		var galleryTitle = $('#photosGallery li.' + $(this).attr('class') + ' span.label').html();
	
		// On va chercher le flash de la galerie
		$.ajax({
			type: 'POST',
			url: 'ajax/photo_gallery.ajax.php',
			data: 'gallery=' + $(this).attr('class'),
			success: function(html) {
				
				// Configuration et contenu de la box
				$('#contentModal')
					.dialog({
						title: galleryTitle,
						width: 620,
						modal: true,
						show: 'blind',
						hide: 'blind',
						draggable: false,
						resizable: false,
						closeOnEscape: false,
						position: defaultContentModalPositions,
						buttons: { 'Go back': defaultContentModalCloseButton }
					})
					.append(html)
					.dialog('open');
			}
		});
	});
	
	/*
	 * Gestion du contentModal
	 */
	$('a[rel=contentModal]').live('click', function() {
	
		// On récupère l'ID du lien
		var id = $(this).attr('id').split('-');
		
		// On vérifie si on a sauvé
		var hasSaved = false;
		
		// On prépare le titre de la fenêtre
		var modalTitle = null;
		
		// S'il y a l'attribut title, on l'utilise
		if ($(this).attr('title') != '') {
			modalTitle = $(this).attr('title');
		} else {
	
			// S'il y a une icône, on prends le HTML du <span>, sinon le <a>
			modalTitle = $(this).hasClass('icon') ? $('#' + $(this).attr('id') + ' span').html() : $(this).html();
		}
		
		// Premier fichier à charger
		var formFile = id[0] + '_form';
		var formData = null;
	
		// On prépare les paramètres
		if (id[1] != undefined) formData = 'id=' + id[1];
		
		// On va chercher le contenu de la box d'ajout
		$.ajax({
			type: 'POST',
			url: 'ajax/' + formFile + '.ajax.php',
			data: formData,
			success: function(form) {
		
				// On prépare les boutons (et donc les actions)
				var closeButton = function() {
					
					// On ferme la box
					defaultContentModalCloseButton();
					
					// On met à jour le contenu de la page du site s'il y a eu des changements
					if (hasSaved) {
						hasSaved = false;
						
						// On recharge le contenu
						loadContent(id[0] + '_refresh');
					}
					
					// On cache les notifications
					$('#modalResult').html('').hide();
				};
				var saveButton = function() {
									
					// On envoye la requête AJAX pour checker les données
					$.ajax ({
						type: 'POST',
						url: 'ajax/' + formFile + '_check.ajax.php',
						data: $('#contentModal form').serialize(),
						dataType: ($.browser.msie) ? 'text' : 'xml',

						// Check if the AJAX request was done successfully
						success: function(data) {
						
							var xml;

							// IE corrections for correct XML use
							if (typeof data == 'string') {
								xml = new ActiveXObject ('Microsoft.XMLDOM');
								xml.async = false;
								xml.loadXML (data);
							} else {
								xml = data;
							}
					
							// On cache le texte de confirmation
							$('#confirmationText').fadeOut();
							
							// On gère le callback
							var callback = null;
							var callbackTime = 0;
							
							// Si tout est ok
							if ($(xml).find('result').text() == '1') {
							
								// On définit qu'on a sauvé
								hasSaved = true;
								
								// On met à jour les boutons
								$('#contentModal').dialog('option', 'buttons', { 'Go back': closeButton });
								
								// On gère le callback
								callback = closeButton;
								callbackTime = 2;
							}
							
							// On met à jour les notifications
							updateNotification(xml, 'modalResult', callback, callbackTime);
						}
					});
				};
				
				// Configuration et contenu de la box
				$('#contentModal')
					.dialog({
						title: modalTitle,
						width: 700,
						modal: true,
						show: 'blind',
						hide: 'blind',
						draggable: false,
						resizable: false,
						closeOnEscape: false,
						position: defaultContentModalPositions,
						buttons: { 'Go back': closeButton, 'Save': saveButton }
					})
					.append(form)
					.dialog('open');
				
				/*
				 * Exceptions
				 *
				 * @internal L'instanciation de l'upload s'effectue à cet endroit car il est nécessaire que le div soit chargé dans le DOM.
				 */
				
				// Pas de bouton "Saved" si c'est les informations russes
				if (formFile == 'camp_russia_form') {
				
					// On met à jour les boutons
					$('#contentModal').dialog('option', 'buttons', { 'Go back': closeButton });
				}
				
				// Upload d'image à l'ajout d'enfant
				if (formFile == 'parents_kids_form' || formFile == 'agents_kids_form') {
				
					// Chargement de la classe d'upload
					new Ajax_upload('uploadPicture', {
						action: 'ajax/upload_kid_image.ajax.php',
						name: 'upload',
						onSubmit: function(file, extension) {
							this.setData({
								idCamper: $('#idCamper').val()
							});
						},
						onComplete: function(file, xml) {
							
							// On met à jour les notifications s'il y a des erreurs
							if ($(xml).find('result').text() == 0) {
								updateNotification(xml, 'modalResult');
							} else {
								$('#modalResult').fadeOut();
							}
						
							// On vérifie s'il y a un ID de campeur donné ou si on doit utiliser le nom du fichier
							var filename = $(xml).find('file').text();
							
							// On garde le nom de l'input ou on stock l'image
							var filesrc = 'camper_photo.php?id=' + filename;
							var inputID = 'input[type=hidden][name=image]';
							
							// On met à jour l'image si le résultat est positif
							if ($(xml).find('result').text() == 1) {
							
								// On vérifie si une image est déjà affichée
								if ($(inputID).val() != '') {
								
									// On cache l'image, on change la source, on réaffiche
									$('#uploadPicturePreview img').fadeOut('normal', function() {
										$(this).attr('src', filesrc).fadeIn('slow');
									});
									
									// On sauve dans un fichier hidden pour l'insertion SQL
									$(inputID).val(filename);
									
								} else {
									
									// On crée l'image si elle n'existe pas
									$('#uploadPicturePreview').hide().html($('<img />')
										.attr({
											alt: file,
											src: filesrc
										})
									).fadeIn('slow');
								
									// On sauve dans un fichier hidden pour l'insertion SQL
									$(inputID).val(filename);
								}
							}
						}
					});
					
					// On annule l'effet du lien d'upload
					return false;
				}
			}
		});
		
		// On annule l'effet du lien
		return false;
	});

	/*
	 * Ajout d'un enfant - Même adresse
	 */
	$('#jqueryKidForm input[type=checkbox][id=address]').live('click', function() {
		
		// On cache ou on affiche la zone d'adresse
		if ($(this).is(':checked')) {
			$('#jqueryKidForm .sameAddress').slideUp();
		} else {
			$('#jqueryKidForm .sameAddress').slideDown();
		}
	});
	
	/**
	 * Gestion des checkbox dans les steps
	 */
	$('.accordion input[type=checkbox][id^=arrivalDatas_], .accordion input[type=checkbox][id^=departureDatas_], .accordion input[type=checkbox][id^=sameAsLastYear_]').live('click', function() {
	
		// On récupère l'ID splitté
		var splittedID = $(this).attr('id').split('_');
		var id = '#' + splittedID[0] + 'Zone_' + splittedID[1];
		
		// On affiche / cache la zone en rapport
		if ($(this).is(':checked')) {
			$(id).slideUp();
		} else {
			$(id).slideDown('slow');
		}
	});
	
	/**
	 * Gestion des checkbox dans les steps
	 */
	$('.accordion input[type=checkbox][id^=transport_aeroport_]').live('click', function() {
	
		// On récupère l'ID de la zone à gérer
		var id = '#transport_aeroport_zone_' + $(this).attr('id').split('_')[2];
		
		// On affiche / cache la zone en rapport
		if ($(this).is(':checked')) {
			$(id).slideDown('slow');
			moreInfosAirportPickup();
			// Informations diverses
			/*var text = '<p>You have chosen the pick-up from the airport. This includes welcome from our staff at the Arrival hall, Car transfer to the camp with our staff and / or driver. Upon departure, we will reconfirm your flight tickets, make sure you have a seat preselected, we will handle with you all check-in formalities, our staff will remain with you in the airport until your flight is ready to board and will remain in the airport until the plane takes off. A member of the Direction will be present in the Airport on Departure days.</p>';
			
			// On ajoute le contenu
			$('#contentModal')
				.dialog({
					title: 'Transport informations',
					width: 700,
					modal: true,
					show: 'blind',
					hide: 'blind',
					draggable: false,
					resizable: false,
					closeOnEscape: false,
					position: defaultContentModalPositions,
					buttons: { 'Go back': defaultContentModalCloseButton }
				})
				.append($('<p></p>').html(text))
				.dialog('open');*/
		} else {
			$(id).slideUp();
		}
	});
	
	$('a[class=moreInfosAirportPickup]').live('click', function() {
		moreInfosAirportPickup();
		return false;
	});
	
	function moreInfosAirportPickup() {
		// Informations diverses
		var text = '<p>You have chosen the pick-up from the airport. This includes welcome from our staff at the Arrival hall, Car transfer to the camp with our staff and / or driver. Upon departure, we will reconfirm your flight tickets, make sure you have a seat preselected, we will handle with you all check-in formalities, our staff will remain with you in the airport until your flight is ready to board and will remain in the airport until the plane takes off. A member of the Direction will be present in the Airport on Departure days.</p>';
		
		// On ajoute le contenu
		$('#contentModal')
			.dialog({
				title: 'Transport informations',
				width: 700,
				modal: true,
				show: 'blind',
				hide: 'blind',
				draggable: false,
				resizable: false,
				closeOnEscape: false,
				position: defaultContentModalPositions,
				buttons: { 'Go back': defaultContentModalCloseButton }
			})
			.append($('<p></p>').html(text))
			.dialog('open');
	}
	
	/*
	 * Steps
	 */
	$('#stepsNavigation #prev, #stepsNavigation #next, #stepsNavigation #finalize').live('click', function() {
	
		// On gère les steps
		$(this).step();
		
		// On annule l'effet du lien
		return false;
	});
	
	// Définir une step
	$('a[id^=setStepTo_]').live('click', function() {
	
		// On récupère l'ID
		var id = $(this).attr('id');
	
		// On change la session PHP
		$.ajax({
			type: 'POST',
			url: 'ajax/change_step_session.ajax.php',
			data: 'step=' + id.split('_')[1],
			cache: false,
			success: function(){			
				
				// On redirige sur le lien
				window.location = $('#' + id).attr('href');
			}
		});
		
		// On annule le lien
		return false;
	});

	/**
	 * Gestion du bouton "sauver" des steps
	 *
	 * @internal Pour les select, le code est exécuté après le chargement de la step (à cause du "change" par supporté par "live")
	 * @see jquery.steps.js
	 */
	$('.accordion form input:checkbox, .accordion form input:radio').live('click', function() { enableSaveButton(this); });
	$('.accordion form input:text, .accordion form textarea').live('keyup', function() { enableSaveButton(this); });
	
	/*
	 * Gestion de l'accordéon
	 */
	$('.accordion .titleBar:not(.completed)').live('click', function() {
	
		// On récupère l'ID
		var nextID = '#kid_' + (parseInt($(this).attr('id').split('_')[1]) + 1);
	
		// Est-ce qu'il est actif ?
		if (!$(this).hasClass('active')) {
		
			// On enlève la marge sur le h3 suivant
			$(nextID).animate({ marginTop: '0px' });
			
			// On ajoute la classe active
			$(this).addClass('active');

		} else {
		
			// On remet la marge sur le h3 suivant
			$(nextID).animate({ marginTop: '4px' });
			
			// On enlève la classe active
			$(this).removeClass('active');
		}
		
		// On ouvre/ferme le contenu
		$(this).next().slideToggle('slow');
	});
	
	/*
	 * On gère les actions de l'accordéon
	 */
	$('.accordion fieldset .buttonBox a.saveButton, .accordion fieldset .applyToAllKids a').live('click', function() {
	
		// Si le bouton est désactivé
		if ($(this).hasClass('disabled')) {alert('There is no modification to save!'); return false;}
			
		// On vérifie que la box content modal n'est pas en cours de fermeture
		if (typeof(contentModalTimer) == 'number') return false;
	
		// On récupère le type d'utilisateur
		var userType = $('#loginType').val() + 's';
	
		// Gestion du rafraichissement du contenu
		var hasSaved = false;
		
		// On split l'ID
		var splittedID = $(this).attr('id').split('_');
		var accordion = splittedID[1];
		var caller = splittedID[2];
		
		// On récupère l'étape
		var step = $('#' + userType + '_campkits_step').val();
		
		// On met à jour l'ID de l'accordéon
		$('#' + userType + '_campkits_accordion').val($(this).attr('id').split('_')[1]);
		
		// Textes par défaut
		var text = 'Are you sure the information you\'ve entered are correct ?';
		var text2 = false;
		
		// On prépare le texte de la confirmation en fonction de la step
		if (step == 1) text = 'Are you sure you want this camper to apply the defined session?';		
		if (step == 1 || step == 3) text2 = 'Once confirmed, you won\'t be able to change it in your personal space.';
		if (step == 5 && caller == 'applyToAllKids') text2 = 'Those information will be duplicated for all your campers !';
		
		// On vérifie si les dates sont valides
		var step5execution = function() {
							
			$.ajax({
				type: 'POST',
				url: 'ajax/parents_campkits_step5_check_date.ajax.php',
				data: $('#kid_' + accordion + '_form').serialize(),
				dataType: ($.browser.msie) ? 'text' : 'xml',

				// Check if the AJAX request was done successfully
				success: function(data) {
					var xml;

					// IE corrections for correct XML use
					if (typeof data == 'string') {
						xml = new ActiveXObject ('Microsoft.XMLDOM');
						xml.async = false;
						xml.loadXML (data);
					} else {
						xml = data;
					}
			
					// S'il y a une erreur, on ajoute un texte d'information
					if ($(xml).find('result').text() == '0') {
						text = $(xml).find('message').text();
					}
					
					// On exécute la suite
					execution();
				}
			});
		};
		
		// Fonction d'exécution de la suite du code
		var execution = function() {
		
			// Texte supplémentaire
			if (text2) $('#contentModal #confirmationText').append($('<li></li>').addClass('info').html(text2));
			
			// On gère les différentes actions
			var closeButton = function() {
						
				// On ferme la box
				defaultContentModalCloseButton();
			
				// On met à jour le contenu
				if (hasSaved) {
					hasSaved = false;
				
					// On met à jour le contenu de la page derrière
					$(this).step(function() {
			
						// On réaffiche le lien "suivant"
						if (step == 1) $('#next').fadeIn('slow');
					
						// On ouvre l'enfant édité
						$('#kid_' + accordion).addClass('active');
						$('#kid_' + accordion + ' h3').animate({ marginTop: '0px' });
						$('#kid_' + accordion + '_form').slideDown('slow');
					});
				}
				
				// On cache les notifications
				$('#modalResult').html('').hide();
			};
			var saveButton = function() {
								
				// On envoye la requête AJAX pour checker les données
				$.ajax ({
					type: 'POST',
					url: 'ajax/' + userType + '_campkits_step' + step + '_check.ajax.php',
					data: $('#kid_' + accordion + '_form').serialize(),
					dataType: ($.browser.msie) ? 'text' : 'xml',
	
					// Check if the AJAX request was done successfully
					success: function(data) {
					
						var xml;
	
						// IE corrections for correct XML use
						if (typeof data == 'string') {
							xml = new ActiveXObject ('Microsoft.XMLDOM');
							xml.async = false;
							xml.loadXML (data);
						} else {
							xml = data;
						}
						
						// On cache le texte de confirmation
						$('#confirmationText').fadeOut();
						
						// On gère le callback
						var callback = null;
						var callbackTime = 0;
						
						// Si tout est ok
						if ($(xml).find('result').text() == '1') {
						
							// On définit qu'on a sauvé
							hasSaved = true;
								
							// On remet les erreurs des formulaires à zéro
							forms = resetFormsValues(forms, 'all');
							
							// On met à jour les boutons
							$('#contentModal').dialog('option', 'buttons', { 'Go back': closeButton });
							
							// On gère le callback si on est en step 2-3-4
							callback = closeButton;
							callbackTime = 2;
							
							// Si c'est la duplication on fait une autre requête AJAX
							if (step == 5 && caller == 'applyToAllKids') {
							
								$.ajax ({
									type: 'POST',
									url: 'ajax/' + userType + '_campkits_step' + step + '_duplicate.ajax.php',
									data: 'idCamper=' + $('#kid_' + accordion + '_form input[type=hidden][name=idCamper]').val(),
									dataType: ($.browser.msie) ? 'text' : 'xml',
	
									// Check if the AJAX request was done successfully
									success: function(data) {
						
										var xml;
	
										// IE corrections for correct XML use
										if (typeof data == 'string') {
											xml = new ActiveXObject ('Microsoft.XMLDOM');
											xml.async = false;
											xml.loadXML (data);
										} else {
											xml = data;
										}
									}
								});
							}
						} else {
							
							// On met à jour les boutons
							$('#contentModal').dialog('option', 'buttons', { 'Go back': closeButton });
						}
						
						// On met à jour les notifications
						updateNotification(xml, 'modalResult', callback, callbackTime);
					}
				});
			};
			
			// On prépare la vérification
			$('#contentModal')
				.dialog({
					title: 'Confirmation',
					width: 525,
					modal: true,
					show: 'blind',
					hide: 'blind',
					draggable: false,
					resizable: false,
					position: defaultContentModalPositions,
					buttons: { 'Go back': closeButton, 'Save': saveButton }
				})
				.append($('<ul></ul>')
					.attr('id', 'confirmationText')
					.addClass('notification noMargin')
					.html($('<li></li>')
						.addClass('help')
						.html(text)
					)
				)
				.dialog('open');
		};
		
		// Gestion particulière des dates pour cette étape
		if (step == 5 && caller != 'applyToAllKids') {
			step5execution();
		} else {
			execution();
		}
		
		// On annule l'effet du lien
		return false;
	});
	
	/*
	 * Gestion du paiement en ligne
	 */
	$('#submitPayment').live('click', function() {
		
		// On va chercher le flash de la galerie
		$.ajax({
			type: 'POST',
			url: 'ajax/payment_check.ajax.php',
			data: $('#paymentForm').serialize(),
			success: function(html) {
			
				// On prépare les boutons
				var submitButton = function() {
				
					// On envoye le formulaire à PostFinance
					$('#finalPaymentForm').submit();
					
					// On ferme la box
					defaultContentModalCloseButton();
				};
			
				// On ajoute le contenu
				$('#contentModal')
					.dialog({
						title: 'Online payment confirmation',
						width: 700,
						modal: true,
						show: 'blind',
						hide: 'blind',
						draggable: false,
						resizable: false,
						closeOnEscape: false,
						position: defaultContentModalPositions
					})
					.append(html);
				
				// On gère le résultat
				if ($('#finalPaymentForm input[type=hidden][name=checkEmptyFields]').val() == 0) {
		
					// On ajoute le texte de confirmation
					$('#contentModal').append($('<ul></ul>')
						.addClass('notification noMargin')
						.html($('<li></li>')
							.addClass('help')
							.html('Are you sure that the information you\'ve entered about this payment are correct ?')
						)
						.append($('<li></li>')
							.addClass('info')
							.html('We will now redirect you to the PostFinance webpage.')
						)
					);
					
					// On ajoute tous les boutons
					$('#contentModal').dialog('option', 'buttons', { 'Go back': defaultContentModalCloseButton, 'Validate payment': submitButton });
					
				} else {
				
					// On affiche une notification d'erreur, et ne met que le bouton d'annulation
					$('#contentModal').append($('<p></p>')
						.addClass('notification error noMargin')
						.html('All the fields should be completed.')
					);
					
					// On ajoute le bouton de fermeture
					$('#contentModal').dialog('option', 'buttons', { 'Go back': defaultContentModalCloseButton });
				}
				
				// On ouvre la box après, à cause de la modification des boutons
				$('#contentModal').dialog('open');
			}
		});
		
		// On annule l'effet du lien
		return false;
	});
	
	/*
	 * Alertes et confirmations
	 */
	$('#noticeKids').live('click', function() {
	
		// Informations diverses
		var link = $(this).attr('href');
		var text = 'Please ensure that on the bank transfer you include the full first and last name of the child(ren) and/or the laundry number. We reserve the right to deduct any amount deducted by the Bank for research.';
		var saveButton = function() {
			
			// On ouvre la fenêtre avec le PDF
			window.open(link, '_blank', 'directories=yes,location=yes,menubar=yes,resizable=no,scrollbars=yes,status=yes,toolbar=yes');
			
			// On ferme la box
			defaultContentModalCloseButton();
		};
		
		// On ajoute le contenu
		$('#contentModal')
			.dialog({
				title: 'Bank transfer information',
				width: 700,
				modal: true,
				show: 'blind',
				hide: 'blind',
				draggable: false,
				resizable: false,
				closeOnEscape: false,
				position: defaultContentModalPositions,
				buttons: { 'Go back': defaultContentModalCloseButton, 'Confirm': saveButton }
			})
			.append($('<p></p>')
				.addClass('icon error')
				.html(text)
			)
			.dialog('open');
		
		// On annule l'effet du lien
		return false;
	});
	/**
	 * Step 1 - Affichage des choix regular/short session
	 */
	
	$('input[id^=augustSessionShort_], input[id^=augustSession_]').live('click', function() {
		
		// Récupération du Numero de l'accordéon
		var idAccordion = $(this).attr('id').split('_')[1]; 
		$('input[id^=augustWeekEnd_]').attr('disabled', !this.checked);
	});
	
	$('input[id^=julySession], input[id^=augustSession]').live('click', function() {
		
		// Récupération du Numero de l'accordéon
		var idAccordion = $(this).attr('id').split('_')[1]; //alert('click');
		
		verifyWEcheckbox(idAccordion, $(this).attr('id').split('Session')[0]);
				
		bothSessionsCheck(idAccordion);
	});
	
	$('input[id^=bothSessions_]').live('click', function() {
		// Récupération du Numero de l'accordéon
		var idAccordion = $(this).attr('id').split('_')[1]; //alert('click'+idAccordion);
		
		if ($(this).is(':checked')) { 
			$('input[id=julySession0_'+idAccordion+']').attr('checked', 'checked');
			$('input[id=augustSession0_'+idAccordion+']').attr('checked', 'checked');
			
			verifyWEcheckbox(idAccordion, 'august');
			verifyWEcheckbox(idAccordion, 'july');
			
			// Activation de la checkbox zermattWeek
			$('input[id^=zermattWeek_'+idAccordion+']').removeAttr('disabled');
			
		} else {
			$('input[id=julySession0_'+idAccordion+']').removeAttr('checked');
			$('input[id=augustSession0_'+idAccordion+']').removeAttr('checked');
			verifyWEcheckbox(idAccordion, 'august');
			verifyWEcheckbox(idAccordion, 'july');
			
			// Desactivation de la checkbox et decochage zermattWeek
			$('input[id^=zermattWeek_'+idAccordion+']').attr('disabled', 'disabled');
			$('input[id^=zermattWeek_'+idAccordion+']').removeAttr('checked');
		}
	});
	
	function verifyWEcheckbox(idAccordion, month) {
		
		// Si on a selectionne la session (regular ou short)
		if ($('input[id^='+month+'Session0_'+idAccordion+']').is(':checked') || $('input[id^='+month+'Session1_'+idAccordion+']').is(':checked')) {
			
			// Activation de la checkbox ZermattWeekEnd
			$('input[id^='+month+'WeekEnd_'+idAccordion+']').removeAttr('disabled');
		} else {
			
			// Desactivation de la checkbox ZermattWeekEnd
			$('input[id^='+month+'WeekEnd_'+idAccordion+']').attr('disabled', 'disabled');
			$('input[id^='+month+'WeekEnd_'+idAccordion+']').removeAttr('checked');
		}
	}
	
	function bothSessionsCheck(idAccordion) {
		// Si les deux session sont selectionnees, on coche la checkbox bothSessions
		if ($('input[id^=julySession0_'+idAccordion+']').is(':checked') && $('input[id^=augustSession0_'+idAccordion+']').is(':checked')) {
			$('input[id=bothSessions_'+idAccordion+']').attr('checked', 'checked');
		} else {
			$('input[id=bothSessions_'+idAccordion+']').removeAttr('checked');
		}
		
		// Gestion de la case de la semaine entre les deux sessions
		if ($('input[id=bothSessions_'+idAccordion+']').is(':checked') || ($('input[id^=julySession_'+idAccordion+']').is(':checked') && $('input[id^=augustSession_'+idAccordion+']').is(':checked')) ) {
			
			// Activation de la checkbox ZermattWeek
			$('input[id^=zermattWeek_'+idAccordion+']').removeAttr('disabled');
			
		} else {
			
			// Desactivation et decochage de la checkbox ZermattWeek
			$('input[id^=zermattWeek_'+idAccordion+']').attr('disabled', 'disabled');
			$('input[id^=zermattWeek_'+idAccordion+']').removeAttr('checked');
		}
	}
	
	
	/**
	 * Step 1 - Zermatt
	 */
	$('.moreInfosZermatt').live('click', function() {
	
		// Informations diverses
		var text = 'At the foot of the impressive Matterhorn, the optional excursion includes skiing or snowboarding lessons, equipment, passes, room and board in a comfortable 2 or 3-bed room in a local 3 star hotel following our high standards of food and service. This trip takes place over three days once every session and over five days between sessions. Please note that beginners are also welcomed to join this fantastic adventure. Our own staff is present on location and on the slopes of course. The Zermatt resort is not far from Flims-Laax and transportation is organized. We recommend choosing the Zermatt trip early as availability is limited.';
		
		var text = '<h3>Summer-skiing and snowboarding in Zermatt</h3><p>During the stay of your children, we are the only camp to offer the amazing possibility to discover the joys of Snow during summer on a Glacier! Take the cable car up to 3800 meters above sea level and learn how to ski next to the famous Matterhorn.</p><p>This trip is perfectly suitable for first-timers, even for those who have never seen the snow!</p><p>This optional trip happens in 2 options, once <u>during</u> each session for a 3 days trip and once at the end of the first session / beginning of the second for 5 days.</p><p>The longer option, for 5 days, will even earn you a certificate from the Swiss Official Ski School!</p><p>This trip is fully organized, supervised and monitored by our staff.</p><p>As usual at JTC, we take pride in offering the highest standard of quality, reason why we are staying at the hotel during this trip offering the same level of food and lodging as in the Camp in Laax.</p><p>This is truly an amazing experience !</p>';
		
		// On ajoute le contenu
		$('#contentModal')
			.dialog({
				title: 'Summer-skiing and snowboarding in Zermatt',
				width: 700,
				modal: true,
				show: 'blind',
				hide: 'blind',
				draggable: false,
				resizable: false,
				closeOnEscape: false,
				position: defaultContentModalPositions,
				buttons: { 'Go back': defaultContentModalCloseButton }
			})
			.append($('<p></p>').html(text));
		
		// On ajoute l'image
		$('#contentModal')
			.append($('<div></div>')
				.addClass('center')
				.html($('<img />')
					.attr({
						src: 'images/visuels_contenus/img_zermatt.jpg',
						width: 286,
						height: 139,
						alt: 'Snowboarding in Zermatt'
					})
				)
			)
			.dialog('open');
		
		// On annule l'effet du lien
		return false;
	});
	
	/**
	 * Step 3 - Mobile Phone
	 */
	$('.moreInfosMobilePhone').live('click', function() {
	
		// Informations diverses
		var text = '<p>It is a JTC Rule that all mobile phones have to be left at the Front Desk upon arrival on the first day. Phones will be available on a daily basis, twice a day for 15 mins.</p><p>We strongly recommend you explain this to your child.</p><p>For Phones that are used as Cameras, we will keep the SIM cards.</p><p>Please note that we are not responsible for loss or damages caused to the phones.</p><p>We strongly recommend you provide an adapter.</p>';
		
		// On ajoute le contenu
		$('#contentModal')
			.dialog({
				title: 'Mobile phone informations',
				width: 700,
				modal: true,
				show: 'blind',
				hide: 'blind',
				draggable: false,
				resizable: false,
				closeOnEscape: false,
				position: defaultContentModalPositions,
				buttons: { 'Accept': defaultContentModalCloseButton }
			})
			.append($('<p></p>').html(text))
			.dialog('open');
		
		// On annule l'effet du lien (seulement si on clique sur le lien)
		if (this.get(0).tagName.toLowerCase() == 'a') return false;
	});
	
	/**
	 * Step 3 - Pocket Money
	 */
	$('.moreInfosPocketMoney').live('click', function() {
		
		// Informations diverses
		var text = '<p>You have here the chance to already send some pocket money for your child, this to avoid giving him / her a lot of money during his / her travel.</p><p>The amount will simply be added to your invoice, and be ready upon arrival.</p><p>Fees will be deducted from the Advance Account and not from the pocket money</p>';
		
		// On ajoute le contenu
		$('#contentModal')
			.dialog({
				title: 'Pocket money informations',
				width: 700,
				modal: true,
				show: 'blind',
				hide: 'blind',
				draggable: false,
				resizable: false,
				closeOnEscape: false,
				position: defaultContentModalPositions,
				buttons: { 'Go back': defaultContentModalCloseButton }
			})
			.append($('<p></p>').html(text))
			.dialog('open');
		
		// On annule l'effet du lien
		return false;
	});
	
	/**
	 * Step 4 - Language course 
	 */
	$('.moreInfosLanguageCourse').live('click', function() {
		
		// Informations diverses
		var text = '<p>We invite you here to choose the language you would like your child to discover or improve. Only 1 language is possible per month.</p><p>Regarding the level, this is only your point of view as we are doing a small placement test at the beginning to create the classes and to ensure a good atmosphere.</p>';
		
		// On ajoute le contenu
		$('#contentModal')
			.dialog({
				title: 'Language course',
				width: 700,
				modal: true,
				show: 'blind',
				hide: 'blind',
				draggable: false,
				resizable: false,
				closeOnEscape: false,
				position: defaultContentModalPositions,
				buttons: { 'Go back': defaultContentModalCloseButton }
			})
			.append($('<p></p>').html(text))
			.dialog('open');
		
		// On annule l'effet du lien
		return false;
	});
	
	/**
	 * Step 5 - UMNR
	 */
	$('input[class*="jqueryAlertUMNR_"]').live('click', function() {
	
		// On récupère la classe de l'input
		var inputClass = $(this).attr('class');
		var inputID = $(this).attr('id');
	
		// On récupère ce qu'il y a après l'underscore
		var particularWord = inputClass.split('_')[1];
	
		// Texte de notification
		if (particularWord == 'assistance') {
			var text = 'By clicking this box, you confirm that your child will travel alone once check-in has been completed and you discharge JTC and the airline of any responsibility. We strongly recommend you check the regulations of minimum age to travel alone with the airline. Should the airline / immigration ask that the child has to be accompanied (UM service), JTC will do its utmost to arrange this but fees might apply.';
		}
		else {
			var text = 'You have indicated that the camper will ' + (particularWord ? particularWord : 'arrive') + ' with the Airline Unaccompanied Service. Please ensure that this properly <strong>pre-booked and pre-paid FOR BOTH WAYS</strong>. Most airlines are refusing last minute UMNR advice. Please give your child a copy of the payment for the return. We reserve the right to charge an admin fee for last minute booking. Thank you for your understanding.';	
		}
		
		
		// On décoche la checkbox
		$(this).removeAttr('checked');
		
		// On prépare les boutons
		var submitButton = function() { $('#' + inputID).attr('checked', 'checked'); defaultContentModalCloseButton(); };
		
		// On ajoute le contenu
		$('#contentModal')
			.dialog({
				title: ((particularWord == 'assistance') ? 'Without airlines assistance' : 'UMNR confirmation'),
				width: 700,
				modal: true,
				show: 'blind',
				hide: 'blind',
				draggable: false,
				resizable: false,
				closeOnEscape: false,
				position: defaultContentModalPositions,
				buttons: { 'Go back': defaultContentModalCloseButton, 'Confirm': submitButton }
			})
			.append($('<p></p>')
				.addClass('icon error')
				.html(text)
			)
			.dialog('open');
	});

});
