var loadingImg       = _root+'img/load.gif';
var loadingLineImg   = '<img src="'+_root+'img/load_line.gif" alt="Loading..." />';
var notToCheck       = ['radio', 'checkbox', 'submit', 'button'];
var duplicateFields  = ['nom_responsable', 'prenom_responsable', 'adresse_responsable', 'cp_responsable', 'ville_responsable', 'tel_responsable', 'mail_responsable'];
var villes           = new Array();
var sejours          = new Array();
var options          = new Array();
var options_selected = new Array();
var dModalHeight     = '550';

function array_push ( array ) {
    var i, argv = arguments, argc = argv.length;

    for (i=1; i < argc; i++){
        array[array.length++] = argv[i];
    }

    return array.length;
}

function empty(mixed_var) {
    var key;
    
    if (mixed_var === ""
        || mixed_var === 0
        || mixed_var === "0"
        || mixed_var === null
        || mixed_var === false
        || mixed_var === undefined
    ){
        return true;
    }

    if (typeof mixed_var == 'object') {
        for (key in mixed_var) {
            return false;
        }
        return true;
    }

    return false;
}

function explode( delimiter, string, limit ) {
    var emptyArray = { 0: '' };
    
    // third argument is not required
    if ( arguments.length < 2
        || typeof arguments[0] == 'undefined'
        || typeof arguments[1] == 'undefined' )
    {
        return null;
    }
 
    if ( delimiter === ''
        || delimiter === false
        || delimiter === null )
    {
        return false;
    }
 
    if ( typeof delimiter == 'function'
        || typeof delimiter == 'object'
        || typeof string == 'function'
        || typeof string == 'object' )
    {
        return emptyArray;
    }
 
    if ( delimiter === true ) {
        delimiter = '1';
    }
    
    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}

function in_array(needle, haystack, strict) {
    var found = false, key, strict = !!strict;
 
    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = true;
            break;
        }
    }
 
    return found;
}

function floatval(mixed_var) {
	return (parseFloat(mixed_var) || 0);
}
function intval( mixed_var, base ) {
    var tmp;
 
    if( typeof( mixed_var ) == 'string' ){
        tmp = parseInt(mixed_var*1);
        if(isNaN(tmp) || !isFinite(tmp)){
            return 0;
        } else {
            return tmp.toString(base || 10);
        }
    } else if( typeof( mixed_var ) == 'number' && isFinite(mixed_var) ){
        return Math.floor(mixed_var);
    } else{
        return 0;
    }
}

function number_format( number, decimals, dec_point, thousands_sep ) {
    var n = number, prec = decimals, dec = dec_point, sep = thousands_sep;
    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    sep = sep == undefined ? ',' : sep;

    var s = n.toFixed(prec),
        abs = Math.abs(n).toFixed(prec),
        _, i;

    if (abs > 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;

        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');

        s = _.join(dec || '.');
    }

    return s;
}

function str_replace(search, replace, subject) {
    var f = search, r = replace, s = subject;
    var ra = r instanceof Array, sa = s instanceof Array, f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;
 
    while (j = 0, i--) {
        if (s[i]) {
            while (s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
        }
    };
 
    return sa ? s : s[0];
}

function substr(f_string, f_start, f_length) {
	f_string += '';
	
	if(f_start < 0) {
	    f_start += f_string.length;
	}
	
	if(f_length == undefined) {
	    f_length = f_string.length;
	} else if(f_length < 0){
	    f_length += f_string.length;
	} else {
	    f_length += f_start;
	}
	
	if(f_length < f_start) {
	    f_length = f_start;
	}
	
	return f_string.substring(f_start, f_length);
}

function trim(str, charlist) {
    var whitespace, l = 0, i = 0;
    str += '';
    
    if (!charlist) {
        // default list
        whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
    } else {
        // preg_quote custom list
        charlist += '';
        whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\$1');
    }
    
    l = str.length;
    for (i = 0; i < l; i++) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(i);
            break;
        }
    }
    
    l = str.length;
    for (i = l - 1; i >= 0; i--) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    
    return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}

function addResp(Id) {
	$('#registration_'+Id+' #addResponsable').hide();
	$('#responsable2_'+Id).show();
	$('#responsables_'+Id).accordion({
		clearStyle: true,
		autoHeight: false,
		alwaysOpen: false,
		active    : false,
		header    : '> fieldset > :first-child, > :not(fieldset):even'
	});
}

function openInscr(id) {
	$.get(_root+'index.php?page=sejour&type=ajax&id='+id, function(data) {
		data = trim(data);
		$(data).modal({
			close: false,
			position: ['5%',],
			overlayId: 'modal-overlay',
			containerId: 'modal-container',
			onOpen:  SejourModal.open,
			onShow:  SejourModal.show,
			onClose: SejourModal.close
		});
// setTotalPrice();
	});
}

function getValsToRegister() {
	var returnSerial = '&';
	returnSerial += 'sejour='   + $('li div.ui-accordion-content-active select option:selected').val() + '&';
	returnSerial += 'quantite=' + $('select:visible:last option:selected').val()  + '&';
	var options   = new Array();
	$('input:checkbox:visible:checked').each(function(i) {
		returnSerial += 'options[]=' + $(this).val() + '&';
	});
	returnSerial += 'action=add';

	return returnSerial;
}

function setTotalPrice(elt) {
	if(elt == '' || elt == 'undefined' || !elt) {
		var elt   = $('li div.ui-accordion-content-active select:visible:first option:selected');
	}
	if(!villes[$(elt).attr('value')]) {
		return false;
	}
	
	var quantite  = $('select:visible:last option:selected').val();
	var totalElt  = floatval(villes[$(elt).attr('value')][1]);
	var totalRElt = floatval(villes[$(elt).attr('value')][0]);
	var optsTotal = 0;
	$('input:checkbox:visible:checked').each(function() {
		var optPrice = floatval(str_replace('px_', '', $(this).attr('class')));
		optsTotal += optPrice;
	});
	var total  = (totalElt  + optsTotal) * intval(quantite);
	var totalR = (totalRElt + optsTotal) * intval(quantite);
	$('#total').html(total);
	$('#total_reduit').html(totalR);
	$('#total, #total_reduit').effect('pulsate', { times: 2 }, 200);
}

function checkval(id) {
    $(id).next('span').html(loadingLineImg).css('display', 'inline');
    $.ajax({
        type:    'POST',
        url:     _root+'index.php?page=checkform',
        data:    'name='+$(id).attr('name')+'&value='+$(id).attr('value'),
        success: function(msg) {
    		msg = trim(msg);
            $(id).next('span').fadeOut(1000);
            if(msg == 'ERROR') {
                $(id).removeClass('ok');
                $(id).addClass('error');
            } else {
                $(id).removeClass('error');
                $(id).addClass('ok');
            }
        }
    });
}

function clearPrice(price) {
	return number_format(price, 2, ',', ' ');
}

function delRegistration(id) {
	$.ajax({
		type: 'GET',
		url:  _root+'index.php?page=inscription&action=del&id='+id
	});
	$('#registration_'+id).fadeOut('slow', function() {
		$(this).html(' ');
		if($('ul#inscriptions li:visible').length == 0) {
			$('.modal-content form').html('Pas d\'inscription en cours...');
		} else if($('ul#inscriptions li:visible').length == 1) {
			$('#inscriptions').accordion('activate', 'a:first');
		}
		setTotal();
	});
}

function sendForm(page) {
    $("#result").html(loadingLineImg);
    $.ajax({
        type:    'POST',
        url:     _root+'index.php?page='+page,
        data:    $('#contact').serialize(),
        success: function(msg) {
    		msg = trim(msg);
            $('#result').fadeOut(1000, function() {
            if(msg == 'ERROR') {
                $('#contact input,textarea').each(function(i) {
                    var tinput = '#'+$(this).attr('id');
                    if(in_array($(tinput).attr('type'), notToCheck) == false) {
                        checkval(tinput);
                    }
                });
            } else {
                $('#result').html(msg);
                $('#result').fadeIn(1000);
            }
            });
        }
    });
}

function saveField(elt, value, type) {
	if(type == 'undefined' || type == '' || !type) {
		type = 'inscription';
	}
	if(value == 'undefined' || value == '' || !value) {
		value = $(elt).val();
	}
	if($(elt).attr('type') == 'checkbox') {
		if($('input[name="'+$(elt).attr('name')+'"]:checked').val()) {
			value = 1;
		} else {
			value = 0;
		}
	}
	id_num = explode('_', $(elt).attr('id'));
	if($(id_num).length == 3) {
		champ  = id_num[0] +'_'+ id_num[1];
		id_num = id_num[2];
	} else {
		champ  = id_num[0];
		id_num = id_num[1];
	}

	// Loader
	$('span#load').css('display', 'inline');
	// Duplicate champs
	var addValues = '';
	if(in_array(substr(champ, 0, -1), duplicateFields) && value != '' && value != 'undefined') {
		$('ul#inscriptions li').each(function() {
			var liId = explode('_', this.id);
			if(liId[1] != id_num) {
				var champPaste = 'li#'+ this.id +' input#'+ champ +'_'+ liId[1];
// console.info(champPaste);
				if(empty($(champPaste).val())) {
					$(champPaste).val(value);
					addValues += '&'+ champ +'['+ liId[1] +']='+ value;
					if(substr(champ, -1) == '2') {
						addResp(liId[1]);
					}
				}
			}
		});
	}
	// Ajout champs dans titre
	if(champ == 'nom' || champ == 'prenom') {
		$('li#registration_'+id_num+' a:first span:last').html($('#nom_'+id_num).val()+' '+$('#prenom_'+id_num).val());
	}
	$.ajax({
		type: 'POST',
		url:  _root+'index.php?page=inscription&type='+type,
		data: $(elt).attr('name') +'='+ value + addValues,
		success: function() {
			$('span#load').fadeOut(1000);
		}
	});
	$(elt).removeClass('error');
	$('label[for="'+$(elt).attr('id')+'"]').removeClass('error');
}

function isPromo(Id) {
	var codeSejour      = $('select[id="code_sejour_'+Id+'"]').attr('value');
	var codeSejourVille = $('select[id="code_sejour_ville_'+Id+'"]').attr('value');
	var dateSejourMin   = explode('-', sejours[codeSejour][1]);
	var datePromoMin    = new Date(dateSejourMin[0] - villes[codeSejourVille][2], dateSejourMin[1] - 1, dateSejourMin[2]);
	var dateCurrent     = explode('/', $('#date_naissance_'+Id).val());
	dateCurrent         = new Date(dateCurrent[2], dateCurrent[1] - 1, dateCurrent[0]);
	if(dateCurrent > datePromoMin && (villes[codeSejourVille][1] - villes[codeSejourVille][0]) != 0) {
		return true;
	} else {
		return false;
	}
}

function setAgePromo() {
	$('#inscriptions li').each(function(i) {
		var getId = explode('_', $(this).attr('id'));
		var Id    = getId[1];
		if($('#date_naissance_'+Id).val() == '00/00/0000' || !$('#date_naissance_'+Id).val()) {
			$('#date_naissance_'+Id).val('');
		} else {
			var cSVwOtransp     = $('#code_sejour_ville_'+Id+' option:first').val(); // Code
																						// sejour
																						// ville
																						// without
																						// transport
			var codeSejourVille = $('select[id="code_sejour_ville_'+Id+'"]').attr('value');
			if(isPromo(Id)) {
				$('#promo_'+Id+' span').html(villes[codeSejourVille][0] - villes[cSVwOtransp][0]);
				$('#date_naissance_promo_'+Id+' span').html(villes[codeSejourVille][2]);
				$('#promo_'+Id+', #date_naissance_promo_'+Id).fadeIn('slow');
			} else {
				$('#promo_'+Id+', #date_naissance_promo_'+Id).fadeOut('slow');
				$('#promo_'+Id+' span').html('0');
			}
		}
	});
	setTotal();
}

function setBirthRange(input) {
	var dateBirthMin = explode('-', $('li div.ui-accordion-content-active .dateBirthMin').val());
	dateBirthMin = new Date(dateBirthMin[0], dateBirthMin[1] - 1, dateBirthMin[2]);
	var dateBirthMax = explode('-', $('li div.ui-accordion-content-active .dateBirthMax').val());
	dateBirthMax = new Date(dateBirthMax[0], dateBirthMax[1] - 1, dateBirthMax[2]);
	return {
		minDate: dateBirthMin,
		maxDate: dateBirthMax
	}
}

function setTotal() {
	var Total = 0;
	$('#inscriptions li').each(function(i) {
		var getId           = explode('_', $(this).attr('id'));
		var Id              = getId[1];
		var codeSejour      = $('select[id="code_sejour_'+Id+'"]').attr('value');
		var codeSejourVille = $('select[id="code_sejour_ville_'+Id+'"]').attr('value');
		if(!villes[codeSejourVille]) {
			var prixSejour  = 0;
		} else {
			if(isPromo(Id)) {
				var prixSejour = villes[codeSejourVille][0];
			} else {
				var prixSejour = villes[codeSejourVille][1];
			}
		}
		var opts            = 0;
		$('#registration_'+Id+' .optTab input:checkbox:checked').each(function(i) {
			var optCfg = explode('_', $(this).attr('id'));
			opts = floatval(options[codeSejour][optCfg[2]][2]) + opts;
		});
// alert('prix:'+prixSejour+'/opts:'+opts+'/promo:'+promo+'/CS:'+codeSejour+'/CSV:'+codeSejourVille);
		var thisTotal = floatval(prixSejour) + opts;
		if($('#registration_'+Id+' input[name^="assurance_annulation"]:checked').val()) {
			thisTotal = thisTotal * 1.02;
		}
		$('#registration_'+Id+' .prix').html(clearPrice(thisTotal));
		Total = thisTotal + floatval(Total);
	});
	$('#prix_total').html(clearPrice(Total));
	$('#prix_total, .prix').effect('pulsate', { times: 2 }, 200);
}

var SejourModal = {
	message: null,
	open: function(dialog) {
		var title = $('#modal-container .modal-title').html();
		$('#modal-container .modal-title').html('Loading...');
		dialog.overlay.fadeIn(200, function() {
			dialog.container.fadeIn(200, function() {
				dialog.data.fadeIn(200, function() {
					$('#modal-container .modal-content').animate({
						height: dModalHeight
					}, function() {
						$('#modal-container .modal-title').html(title);
						$('#modal-container form').fadeIn(200);
						setTotalPrice();
					});
				});
			});
		});
	},
	show: function(dialog) {
		$('form')[0].reset();
		var activeTab = intval($('#villeActivate').html());
		$('#villes_sejour').accordion({
			clearStyle: true,
			autoHeight: false,
			alwaysOpen: false,
			active    : false
		}).accordion('activate', 'a:eq('+activeTab+')');
		$('#villes_sejour option, #participants option').click(function() {
			setTotalPrice();
		});
		$('#villes_sejour li a').click(function() {
			// console.info($(this).next().find(":selected").attr('class'));
			setTotalPrice($(this).next().find(':selected'));
		});	
		$('#villes_sejour input').click(function() {
			if($(this).attr('type') == 'checkbox') {
				setTotalPrice();
			}
		});
		$('#inscriptions').accordion({
			clearStyle: true,
			autoHeight: false,
			alwaysOpen: false,
			active    : false
		});
		if($('ul#inscriptions li').length == 1) {
			$('#inscriptions').accordion('activate', 'a:first');
		}
		$('.datepicker').datepicker({ beforeShow: setBirthRange, onClose: function(date) {
			saveField(this, date);
			setAgePromo();
		} });
		
	    $('#inscriptions input, #inscriptions select').change(function() {
	    	if(!$(this).hasClass('nosubmit')) {
	    		saveField(this);
	    	}
	    });
	    $('input#nextStep').click(function() {
	    	SejourModal.showAdhesion();
	    });

		$('#modal-container #link_inscription').click(function(e) {
			e.preventDefault();
			var adds = getValsToRegister();
			// validate form
			$('#modal-container .modal-message').fadeOut(function() {
				$('#modal-container .modal-message').removeClass('modal-error').empty();
			});
			$('#modal-container .modal-title').html('INSCRIPTION');
			$('#modal-container form').fadeOut(200);
			$('#modal-container .modal-content').animate({
				height: '80px'
			}, function() {
				$('#modal-container .modal-loading').fadeIn(200, function() {
					$.get(_root+'index.php?page=inscription&core=false'+adds, function(data) {
						data = trim(data);
						$('#modal-container .modal-loading').fadeOut(200, function() {
							$('#modal-container .modal-content').animate({
								height: dModalHeight
							}, function() {
								$('#modal-container form').html(data).fadeIn(200);
								$('#inscriptions').accordion({
									clearStyle: true,
									autoHeight: false,
									alwaysOpen: false,
									active    : false
								});
								if($('ul#inscriptions li').length == 1) {
									$('#inscriptions').accordion('activate', 'a:first');
								}
								setTotal();
								$('.datepicker').datepicker({ beforeShow: setBirthRange, onClose: function(date) {
									saveField(this, date);
									setAgePromo();
								} });
							    $('#inscriptions input, #inscriptions select').change(function() {
							    	if(!$(this).hasClass('nosubmit')) {
							    		saveField(this);
							    	}
							    });
								showOptions();
							    $('input#nextStep').click(function() {
							    	SejourModal.showAdhesion();
							    });
							});
						});
					});
				});
			});
		});
	},
	close: function(dialog) {
		$('#modal-container .modal-message').fadeOut();
		$('#modal-container .modal-title').html('Enregistrement...');
		$('#modal-container form').fadeOut(200);
		$('#modal-container .modal-content').animate({
			height: 40
		}, function() {
			dialog.data.fadeOut(200, function() {
				dialog.container.fadeOut(200, function() {
					dialog.overlay.fadeOut(200, function() {
						$.modal.close();
					});
				});
			});
		});
	},
	login: function() {
		$('#modal-container .modal-message').fadeOut(function() {
			$('#modal-container .modal-message').removeClass('modal-error').empty();
		});
		$('#modal-container form').fadeOut(200);
		$('#modal-container .modal-content').animate({
			height: '80px'
		}, function() {
			$('#modal-container .modal-loading').fadeIn(200, function() {
				$.ajax({
					type:    'POST',
					url:     _root+'index.php?page=identification_parents&action=checkLoginAjax',
					data:    'login='+$('.adherent_true #identifiant').val()+'&pass='+$('.adherent_true #pass').val(),
					success: function(data) {
						data = trim(data);
						if(data == 'FALSE') {
							SejourModal.showAdhesion(true);
						} else {
							$('#identification').html(data);
							SejourModal.showRecap();
						}
					}
				});
			});
		});
	},
	sendIdent: function() {
		$('#modal-container .modal-message').fadeOut(function() {
			$('#modal-container .modal-message').removeClass('modal-error').empty();
		});
		$('#modal-container form').fadeOut(200);
		$('#modal-container .modal-content').animate({
			height: '80px'
		}, function() {
			$('#modal-container .modal-loading').fadeIn(200, function() {
				$.ajax({
					type:    'POST',
					url:     _root+'index.php?page=inscription&action=sendident',
					data:    'nom='+$('.adherent_dunno #nom_dunno').attr('value')
							+'&code_postal='+$('.adherent_dunno #code_postal_dunno').attr('value')
							+'&email='+$('.adherent_dunno #email_dunno').attr('value'),
					success: function(data) {
						data = trim(data);
						if(data == 'FALSE') {
							SejourModal.showAdhesion(true, 'Erreur - Adhérent inconnu, veuillez contacter le service clients.');
						} else {
							$('#identification').html(data);
							SejourModal.showRecap();
						}
					}
				});
			});
		});
	},
	newAdhesion: function() {
		var error = false;
		$('.adherent_false input[type="text"]').each(function(i) {
			if(!$(this).attr('value') && !$(this).hasClass('nocheck')) {
				$(this).addClass('error');
				$('label[for="'+$(this).attr('id')+'"]').addClass('error');
				error = true;
				SejourModal.message = 'Des champs obligatoires sont restés vides. Ceux-ci ont été surlignés.';
			}
		});
		if($('.adherent_false #mot_passe').attr('value') != $('.adherent_false #mot_passe_confirm').attr('value')) {
			$('#mot_passe, #mot_passe_confirm').addClass('error');
			$('label[for="mot_passe"], label[for="mot_passe_confirm"]').addClass('error');
			SejourModal.message = 'Erreur sur la confirmation du mot de passe.';
			error = true;
		}
		if(error) {
			SejourModal.showError();
			return;
		}
		$('#modal-container .modal-message').fadeOut(function() {
			$('#modal-container .modal-message').removeClass('modal-error').empty();
		});
		$('#modal-container form').fadeOut(200);
		$('#modal-container .modal-content').animate({
			height: '80px'
		}, function() {
			$('#modal-container .modal-loading').fadeIn(200, function() {
				$.ajax({
					type:    'POST',
					url:     _root+'index.php?page=inscription&action=newAdhesion',
					data:    'pass='+$('.adherent_false #mot_passe').attr('value'),
					success: function(data) {
						data = trim(data);
						if(data == 'FALSE') {
							SejourModal.showAdhesion(true, 'Erreur lors de l\'inscription');
						} else if(data == 'EXISTS') {
							SejourModal.showAdhesion(true, 'Erreur - Vous devez déjà posséder un compte. Veuillez utiliser l\'outil de récupéraiton d\'identifiant.');
						} else {
							$('#identification').html(data);
							SejourModal.showRecap();
						}
					}
				});
			});
		});
	},
	showAdhesion: function(loginError, errorTxt) {
		var error = false;
		$('#inscriptions input[type="text"]').each(function(i) {
			if(!$(this).attr('value') && !$(this).hasClass('nocheck')) {
				$(this).addClass('error');
				$('label[for="'+$(this).attr('id')+'"]').addClass('error');
				SejourModal.message = 'Des champs obligatoires sont restés vides. Ceux-ci ont été surlignés.';
				error = true;
			}
		});
		if(error) {
			SejourModal.showError();
			return;
		}
		$('#modal-container .modal-message').fadeOut(function() {
			$('#modal-container .modal-message').removeClass('modal-error').empty();
		});
		$('#modal-container form').fadeOut(200);
		$('#modal-container .modal-content').animate({
			height: '80px'
		}, function() {
			$('#modal-container .modal-loading').fadeIn(200, function() {
				$.get(_root+'index.php?page=inscription&action=adhesion&core=false', function(data) {
					data = trim(data);
					$('#modal-container .modal-loading').fadeOut(200, function() {
						$('#modal-container .modal-content').animate({
							height: dModalHeight
						}, function() {
							if(data == 'FALSE') {
								$('#modal-container form').html('Identification en cours...').fadeIn(200);
								SejourModal.showRecap();
							} else {
								$('#modal-container form').html(data).fadeIn(200);
								if(loginError) {
									if(errorTxt) {
										SejourModal.message = errorTxt;
									} else {
										SejourModal.message = 'Mauvais identifiant / mot de passe.';
									}
									SejourModal.showError();
								}
								$('form input[name="adherent"]').change(function() {
									$('#formIdentification div').slideUp('slow');
									$('.'+$('form input[name="adherent"]:checked').attr('id')).slideDown('slow');
								});
							    $('.adherent_false input, .adherent_false select').change(function() {
							    	if(!$(this).hasClass('nosubmit')) {
							    		saveField(this, '', 'adhesion');
							    	}
							    });
							    $('.adherent_false #adherer').click(function() {
							    	SejourModal.newAdhesion();
							    });
							    $('.adherent_dunno #envoyer').click(function() {
							    	SejourModal.sendIdent();
							    });
							    $('.adherent_true #identifier').click(function() {
							    	SejourModal.login();
							    });
							}
						});
					});
				});
			});
		});
	},
	showError: function() {
		$('#modal-container .modal-message').html($('<div class="modal-error">').append(SejourModal.message)).fadeIn(200);
	},
	showRecap: function() {
		$('#modal-container .modal-message').fadeOut(function() {
			$('#modal-container .modal-message').removeClass('modal-error').empty();
		});
		$('#modal-container form').fadeOut(200);
		$('#modal-container .modal-content').animate({
			height: '80px'
		}, function() {
			$('#modal-container .modal-loading').fadeIn(200, function() {
				$.get(_root+'index.php?page=inscription&action=recap&core=false', function(data) {
					data = trim(data);
					$('#modal-container .modal-loading').fadeOut(200, function() {
						$('#modal-container .modal-content').animate({
							height: dModalHeight
						}, function() {
							$('#modal-container form').html(data).fadeIn(200);
						    $('#nextStep').click(function() {
						    	if($('input#accept_cgv:checked').length) {
						    		SejourModal.showPayment();
						    	} else {
						    		SejourModal.message = 'Erreur : Vous n\'avez pas accepté les CGV !';
						    		SejourModal.showError();
						    	}
						    });
						});
					});
				});
			});
		});
	},
	showPayment: function() {
		$('#modal-container .modal-message').fadeOut(function() {
			$('#modal-container .modal-message').removeClass('modal-error').empty();
		});
		$('#modal-container form').fadeOut(200);
		$('#modal-container .modal-content').animate({
			height: '80px'
		}, function() {
			$('#modal-container .modal-loading').fadeIn(200, function() {
				$.get(_root+'index.php?page=inscription&action=payment&core=false', function(data) {
					data = trim(data);
					$('#modal-container .modal-loading').fadeOut(200, function() {
						$('#modal-container .modal-content').animate({
							height: dModalHeight
						}, function() {
							$('#modal-container form').html(data).fadeIn(200);
							//
						});
					});
				});
			});
		});
	}
};

function showOptions() {
	$('#inscriptions li').each(function(i) {
		var getId      = explode('_', $(this).attr('id'));
		var Id         = getId[1];
		var codeSejour = $('select[id="code_sejour_'+Id+'"]').attr('value');
		if($('#options_'+Id).html()) {
			$('#options_'+Id).fadeOut('fast', function() {
				$('#options_'+Id).html('');
			});
		}
		$('#options_'+Id).html('').hide();
		if(!options[codeSejour]) {
			return;
		}
		$(options[codeSejour]).each(function(i) {
			var checked = '';
			if(in_array(options[codeSejour][i][0], options_selected[Id][codeSejour])) {
				checked = ' checked="checked"';
			}
			$('#options_'+Id).append(
				'<div class="optTab"><label for="opt_'+Id+'_'+i+'_'+options[codeSejour][i][0]+'">'+options[codeSejour][i][1]+
				'</label><br />'+options[codeSejour][i][2]+'&euro; <input type="checkbox" name="options['+Id+
				']['+options[codeSejour][i][0]+']" id="opt_'+Id+'_'+i+'_'+options[codeSejour][i][0]+'" value="1"'+checked+' /></div>'
			).fadeIn('slow');
		});
	});

	$('div[id^="options_"] input:checkbox').change(function() {
		var optCfg = explode('_', $(this).attr('id'));
		if($('#'+$(this).attr('id')+':checked').val()) {
			array_push(options_selected[optCfg[1]][$('#code_sejour_'+optCfg[1]).val()], optCfg[3]);
		} else {
			$(options_selected[optCfg[1]][$('#code_sejour_'+optCfg[1]).val()]).each(function(i) {
				if(this == optCfg[3]) {
					delete options_selected[optCfg[1]][$('#code_sejour_'+optCfg[1]).val()][i];
				}
			});
		}
		saveField(this);
		setTotal();
	})
}

function nos_partenaires(){
	
	var page = _root+"nos_partenaires";
    window.open(page,"Nos partenaires","menubar=no, status=no, scrollbars=no, menubar=no, width=400, height=500");	
}
$(document).ready(function() {
    $('#contact input,textarea').blur(function() {
        var tinput = '#'+$(this).attr('id');
        if(in_array($(tinput).attr('type'), notToCheck) == false && $(tinput).attr('class') != 'nocheck') {
            checkval(tinput);
        }
    });
    
    $('#filtre_age').change(function() {
    	var buttonId = this;
    	$('#sejours_liste').fadeOut('fast', function() {
    		$('#sejours_liste').html($('<center />').html($('<img />').attr({'src':loadingImg, 'alt':'loading'}))).fadeIn('fast');
    		var saison = $('span#saison').html();
    		saison = '&saison=' + saison;
    		
			$.get(_root+'index.php?page=sejours&type=ajax&pagetype=saison'+ saison + '&age='+ $('#filtre_age').val(), { },
			function(data) {
				data = trim(data);
				$('#sejours_liste').fadeOut('fast', function() {
					$('#sejours_liste').html(data).fadeIn('fast');
				});
			});
    	});
    })
    
    $('fieldset input:checkbox').click(function() {
    	var buttonId = this;
    	$('#sejours_liste').fadeOut('fast', function() {
    		$('#sejours_liste').html($('<center />').html($('<img />').attr({'src':loadingImg, 'alt':'loading'}))).fadeIn('fast');
    		var checkboxes = $('fieldset input:checkbox').serialize();
    		if(checkboxes != '') {
    			checkboxes = '&' + checkboxes;
    		}
			$.get(_root+'index.php?page=sejours&type=ajax&pagetype=age'+ checkboxes + '&age='+ $('#age').val(), { },
			function(data) {
				data = trim(data);
				$('#sejours_liste').fadeOut('fast', function() {
					$('#sejours_liste').html(data).fadeIn('fast');
				});
			});
    	});
    })
    
    $("#nos_partenaires").click(function() {
    	$.get(_root+'nos_partenaires', { }, function(data) {
			data = trim(data);
			// $('#sejours_liste').fadeOut('fast', function() {
				$('#nosPartenairesDialogWindow').html(data);
				$('#nosPartenairesDialogWindow').dialog('open');
		    	$('#nosPartenairesDialogWindow').dialog({ modal: true, buttons: { "X": function() { $(this).dialog("close"); } } });
		    	$('#nosPartenairesDialogWindow').dialog('option', 'modal', true);
		    	$('#nosPartenairesDialogWindow').dialog('option', 'buttons', { "X": function() { $(this).dialog("close"); } });
		    	$('#nosPartenairesDialogWindow').dialog('option', 'title', 'Nos Partenaires');
		    	$('#nosPartenairesDialogWindow').dialog('option', 'width', '400px');
		    	$('#nosPartenairesDialogWindow').dialog('option', 'height', '300px');
			// });
		});
    });
    
    $('form#f_identification_parents').submit(function() {
    	var code = $('#password').val();
    	if(empty($('#login').val()) && !empty(code)) {
        	$.get(_root, { page:'blog', code:code }, function(data) {
        		
				$('#codeDialog').html(data);
				$('#codeDialog').dialog('open');
		    	$('#codeDialog').dialog({ modal: true, buttons: { "X": function() { $(this).dialog("close"); } } });
		    	$('#codeDialog').dialog('option', 'modal', true);
		    	$('#codeDialog').dialog('option', 'draggable', false);
		    	$('#codeDialog').dialog('option', 'buttons', { "X": function() { $(this).dialog("close"); } });
		    	$('#codeDialog').dialog('option', 'width', '960px').dialog( "option", "position", 'center' );
		    	
		    	// lien pour affichage du formulaire
		    	$('#contact_enfant_button').click(function() {
		    		
		    		$('#codeDialog').html($('#contact_enfant_container').html());
		    		
		    		// fonction formulaire contact enfant
			    	$('form#contact_enfant').submit(function() {
			    		var datas = $('form#contact_enfant input, form#contact_enfant textarea');
			    		var error = false;
			    		$.each(datas, function(i, val) {
			    			if(empty($(val).val())) {
			    				error = true;
			    			}
			    		});
			    		if(error) {
			    			alert('Erreur : TOUS les champs doivent être remplis !');
			    			return false;
			    		}
			    		$('#codeDialog form#contact_enfant').html('<center>'+loadingLineImg+'</center>');
			    		$.post(_root+'?page=blog&code='+code, datas, function(data) {
			    			if(data == 'ok') {
			    				$('#codeDialog form#contact_enfant').html('Votre message a bien &eacute;t&eacute; envoy&eacute; !');
			    			} else {
			    				$('#codeDialog form#contact_enfant').html('Une erreur est survenue, veuillez contacter Vacances Energie !');
			    			}
			    		}, 'json');
			    		return false;
			    	});
			    	
		    		return false;
		    	});
		    	
		    	$('#contact_ve_button').click(function() {
		    		
		    		$('#codeDialog').html($('#contact_ve_container').html());
		    		
		    		// fonction formulaire contact VE
			    	$('form#contact_ve').submit(function() {
			    		var datas = $('form#contact_ve input, form#contact_ve textarea');
			    		var error = false;
			    		$.each(datas, function(i, val) {
			    			if(empty($(val).val())) {
			    				error = true;
			    			}
			    		});
			    		if(error) {
			    			alert('Erreur : TOUS les champs doivent être remplis !');
			    			return false;
			    		}
			    		$('#codeDialog form#contact_ve').html('<center>'+loadingLineImg+'</center>');
			    		
			    		$.post(_root+'?page=contact&rResult=json', datas, function(data) {
			    			if(data == 'ok') {
			    				$('#codeDialog form#contact_ve').html('Votre message a bien &eacute;t&eacute; envoy&eacute; !');
			    			} else {
			    				$('#codeDialog form#contact_ve').html('Une erreur est survenue, veuillez contacter Vacances Energie !');
			    			}
			    		}, 'json');
			    		return false;
			    	});
			    	
			    	return false;
		    	});

	    	});
        	return false;
    	}
    });
    
    if($.browser.msie && $.browser.version < 7) {
    	$('#maincontainer').html(
    		'<div id="ie6msg"><h3>Savez-vous que votre navigateur est obsolète ?</h3>'+
    		'<p>Pour naviguer de la manière la plus satisfaisante sur notre site, nous recommandons que vous procédiez à une mise à jour de votre navigateur. '+
    		'La version actuelle est <a href="www.microsoft.com/france/windows/ie/">Internet Explorer 8</a>. '+
    		'La mise à jour est gratuite. Si vous utilisez un PC au travail, veuillez contacter votre service informatique.</p>'+
    		'<p>Si vous le souhaitez, vous pouvez aussi essayer d\'autres navigateurs Web populaires comme par exemple <a href="http://mozilla.com">Firefox</a>, '+
    		'<a href="http://www.apple.com/safari/download/">Safari</a>, <a href="http://www.google.fr/chrome">Chrome</a> ou '+
    		'<a href="http://www.opera.com">Opera</a></p></div>'
    	);
    	$('#footer').hide();
    }
});
