/*-----------------------------------------------------------
Project:	Les Portes du Soleil
Author:		C2iS - BBO
Last:		15:55 27/07/2010
-----------------------------------------------------------*/
/**:::::::: FUNCTIONS ::::::::::**/

//Passage en post du pays
function validCountry(id,idInput,action)
{
	if(document.getElementById(idInput))
	{
		document.getElementById(idInput).value = id;
		if(document.getElementById('formChange'))
		{
			document.getElementById('formChange').action = action;
			document.getElementById('formChange').submit();
		}
	}
}

//Passage en post de la saison (toutes les reecritures ne differencient pas la saison)
function validSeason(id,idInput,action)
{
	if(document.getElementById(idInput))
	{
		document.getElementById(idInput).value = id;
		if(document.getElementById('formChange'))
		{
			document.getElementById('formChange').action = action;
			document.getElementById('formChange').submit();
		}
	}
}

//Passage en post de la langue (toutes les reecritures ne differencient pas la saison)
function validLangue(id,idInput,action)
{
	if(document.getElementById(idInput))
	{
		document.getElementById(idInput).value = id;
		if(document.getElementById('formChange'))
		{
			document.getElementById('formChange').action = action;
			document.getElementById('formChange').submit();
		}
	}
}

function VerifFormLoginPresse(idInputLogin,idInputEmail,idInputValidation,valueValidation)
{
	var login = '';
	if(document.getElementById(idInputLogin))
	{
		login = document.getElementById(idInputLogin).value;
	}
	
	var email = '';
	if(document.getElementById(idInputEmail))
	{
		email = document.getElementById(idInputEmail).value;
	}

	if(login != '' && email != '' && document.getElementById(idInputValidation) && document.getElementById('formLoginPresse'))
	{
		document.getElementById(idInputValidation).value = valueValidation;
		document.getElementById('formLoginPresse').submit();
	}
	else
	{
		if(login == '')
		{
			if(document.getElementById('erreurLoginVide') && document.getElementById('erreurLogin'))
			{
				document.getElementById('erreurLogin').innerHTML = document.getElementById('erreurLoginVide').value;
			}
		}
		
		if(email == '')
		{
			if(document.getElementById('erreurEmailVide') && document.getElementById('erreurEmailLogin'))
			{
				document.getElementById('erreurEmailLogin').innerHTML = document.getElementById('erreurEmailVide').value;
			}
		}
	}
}

function getDateFromTimestamp(timestamp)
{
	//Le timestamp est en secondes
	timestamp = timestamp * 1000;

	//Creation d'un objet date
	var newDate = new Date();
	newDate.setTime(timestamp);

	var day = newDate.getDate();

	//Attention, getMonth => 0 pour janvier
	var month = newDate.getMonth() + 1;
	var year = newDate.getFullYear();

	//Ajout des 0 devant le jour et le mois
	(day + '').length == 1 ? day = '0' + day : day = day;
	(month + '').length == 1 ? month = '0' + month : month = month;

	return day+'/'+month+'/'+year;
}

//Retourne le timestamp d'une date au format jj/mm/aaaa
function getTimestampFromDate(selectedDate)
{

	//Creation d'un objet date
	var newDate = new Date(0);
	newDate.setFullYear(selectedDate.substr(6,4));

	//Attention, setMonth => 0 pour janvier
	var substrMonth = selectedDate.substr(3,2);
	newDate.setMonth(substrMonth - 1);
	newDate.setDate(selectedDate.substr(0,2));
	newDate.setHours(0);
	newDate.setMinutes(0);
	newDate.setSeconds(0);
	newDate.setMilliseconds(0);

	//renvoi du timestamp en secondes
	return Math.round(newDate.getTime()/1000.0);

}


function ShowHideStation(obj){
	$("#formStation").val(0);
	$("input[type=checkbox][name=formStationMulti[]][checked]").each(
		function() {
			this.checked=false;
		}
	);

//	if($('#'+obj+' :selected').attr('label') == 1){
	if($('#'+obj+' :selected').attr('id') == 1){
		$('#divStation').css('display','block');
		$('#divStationMulti').css('display','none');
		$('#sujetMulti').val("");
		$('#sujetSimple').val("simple");
	}else if($('#'+obj+' :selected').attr('id') == "multi"){
		$('#divStation').css('display','none');
		$('#divStationMulti').css('display','block');
		$('#sujetMulti').val("multi");
		$('#sujetSimple').val("");
	}else{
		$('#divStation').css('display','none');
		$('#divStationMulti').css('display','none');
		$('#sujetMulti').val("");
		$('#sujetSimple').val("");
	}
}

function VerifFormContact(){
	
	if($('#formSujet :selected').val() == 0){
		inlineMsg('formSujet', get_trad_champ('sujet'));
		$('#formSujet').focus();
		return;
	}
	if($('#divStation').css('display') == "block" && $('#formStation :selected').val() == 0){
		inlineMsg('divStation', get_trad_champ('station'));
		$('#formStation').focus();
		return;
	}
	if($('#divStationMulti').css('display') == "block"){
		var ischecked=0;
		$("input[type=checkbox][name=formStationMulti[]][checked]").each(
		    function() {
		      ischecked++
		    }
		  );

		  if(ischecked<=0){
		    inlineMsg('labelMulti', get_trad_champ('station'));
			$('#formStation').focus();
			return;
		  }


	}
	if($('#formNom').val() == ""){
		inlineMsg('formNom', get_trad_champ('nom'));
		$('#formNom').focus();
		return;
	}
	if($('#formPrenom').val() == ""){
		inlineMsg('formPrenom', get_trad_champ('prenom'));
		$('#formPrenom').focus();
		return;
	}
	if($('#formAdresse1').val() == ""){
		inlineMsg('formAdresse1', get_trad_champ('adresse'));
		$('#formAdresse1').focus();
		return;
	}
	if($('#formVille').val() == ""){
		inlineMsg('formVille', get_trad_champ('ville'));
		$('#formVille').focus();
		return;
	}
	if($('#formEmail').val() == "" || !isValidEmail('formEmail')){
		inlineMsg('formEmail', get_trad_champ('email'));
		$('#formEmail').focus();
		return;
	}
	if($('#formMessage').val() == ""){
		inlineMsg('formMessage', get_trad_champ('message'));
		$('#formMessage').focus();
		return;
	}

	$('#formContact').submit();
}

function VerifFormPresse(){

	
	if($('#formNom').val() == ""){
		inlineMsg('formNom', get_trad_champ('nom'));
		$('#formNom').focus();
		return;
	}
	if($('#formPrenom').val() == ""){
		inlineMsg('formPrenom', get_trad_champ('prenom'));
		$('#formPrenom').focus();
		return;
	}
	if($('#formSociete').val() == ""){
		inlineMsg('formSociete', get_trad_champ('societe'));
		$('#formSociete').focus();
		return;
	}
	if($('#formAdresse1').val() == ""){
		inlineMsg('formAdresse1', get_trad_champ('adresse'));
		$('#formAdresse1').focus();
		return;
	}
	
	if($('#formCP').val() == ""){
		inlineMsg('formCP', get_trad_champ('cp'));
		$('#formCP').focus();
		return;
	}
	
	if($('#formVille').val() == ""){
		inlineMsg('formVille', get_trad_champ('ville'));
		$('#formVille').focus();
		return;
	}
	if($('#formTel').val() == ""){
		inlineMsg('formTel', get_trad_champ('tel'));
		$('#formTel').focus();
		return;
	}
	if($('#formEmail').val() == "" || !isValidEmail('formEmail')){
		inlineMsg('formEmail', get_trad_champ('email'));
		$('#formEmail').focus();
		return;
	}
	

	$('#formRegisterPresse').submit();
}


function footerInscriptionNewsletter()
{
	if (isValidEmail('footerEmailNewsletter'))
	{
		$('#footer #newsletter').colorbox({href:"ajax/formInscriptionNewsletter.ajax.php?email="+$('#footerEmailNewsletter').val(), width:"450px",onClosed:function(){document.location.href=document.location.href}});

		//$.post('ajax/inscriptionNewsletter.ajax.php', {mail:$("#footerEmailNewsletter").val(), destination:''}, function (data) {});
		return false;
	} else {
		inlineMsg('newsletter', get_trad_champ('email'));
		return false;
	}
}


function validFormNewsletter(pInscription)
{
	if (pInscription)
	{
		if($('#formNom').val() == ""){
			inlineMsg_popin('formNom', get_trad_champ('nom'));
			$('#formNom').focus();
			return false;
		}
		if($('#formPrenom').val() == ""){
			inlineMsg_popin('formPrenom', get_trad_champ('prenom'));
			$('#formPrenom').focus();
			return false;
		}
		if($('#formEmail').val() == "" || !isValidEmail('formEmail')){
			inlineMsg_popin('formEmail', get_trad_champ('email'));
			$('#formEmail').focus();
			return false;
		}

		//$('#formNewsletter').submit();
		$.post($('#formNewsletter').attr('action'),
				{nom: $('#formNom').val(),
				 prenom: $('#formPrenom').val(),
				 email: $('#formEmail').val(),
				 cp : $('#formCP').val(),
				 pays : $('#formPays').val(),
				 destination: $("#extUrl").val()});


			$("#colorbox").colorbox.close();
	} else {

		$("#colorbox").colorbox.close();
	}
	return true;
}

//-------------------------------------
// Verifie la validite d'un email
//-------------------------------------
function isValidEmail ( _fieldId ) {

	var email = document.getElementById(_fieldId).value;
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

	if ( !filter.test(email) )
	{
		return false;
	}
	else
	{
		return true;
	}
}


function envoiMail(ctrl)
{//link="+document.location.href+"&
	$('#fbMail').colorbox({href:"ajax/formEnvoyerMail.ajax.php?email="+ctrl.getAttribute('href').replace('mailto:',''), width:"450px"});
}

function validFormEnvoiMail(pSend)
{
	if (pSend)
	{
		if($('#formNom').val() == ""){
			inlineMsg_popin('formNom', get_trad_champ('nom'));
			$('#formNom').focus();
			return false;
		}

		if($('#formEmail').val() == "" || !isValidEmail('formEmail')){
			inlineMsg_popin('formEmail', get_trad_champ('email'));
			$('#formEmail').focus();
			return false;
		}

		//$('#formNewsletter').submit();
		$.post($('#formMail').attr('action'),
				{nom: $('#formNom').val(),
				 email: $('#formEmail').val(),
				 emailExped: $('#formEmailExped').val(),
				 link:document.location.href,
				 message : $('#formMessage').val()});

			$("#colorbox").colorbox.close();
	} else {

		$("#colorbox").colorbox.close();
	}
	return true;
}

function displayVideoIndex(index)
{
	var contener = document.getElementById('detail_video');
	var divs = contener.childNodes;

	//On met toutes les divs en display none
	var nbDivs = divs.length;
	for(i = 0; i < nbDivs; i++)
	{
		if(divs[i].id && divs[i].id.indexOf('detail_video') != -1)
		{
			divs[i].style.display = 'none';
		}
	}
	document.getElementById('detail_video_' + index).style.display = '';
}

function displayNextVideoIndex(index)
{
	return 	displayVideoIndex(index+1);
}

function displayPreviousVideoIndex(index)
{
	return 	displayVideoIndex(index-1);
}

/*function get_trad_champ(champ)
{
		switch(champ)
		{

        case "tel" :
						return("Vous devez saisir votre numÃ©ro de tÃ©lÃ©phone.");
						break;
        case "station" :
						return("Vous devez selectionner une station");
						break;
        case "sujet" :
						return("Vous devez selectionner un sujet");
						break;
        case "form_cours" :
						return("Vous devez selectionner au moins un critÃ¨re");
						break;
				case "form_equipe" :
						return("Vous devez selectionner au moins un critÃ¨re");
						break;
				case "nom" :
						return("Veuillez indiquer votre nom");
						break;
				case "prenom" :
						return("Veuillez indiquer votre prÃ©nom");
						break;
				case "email" :
						return("L'email que vous avez rentrÃ©e n'est pas valide.\nVeuillez la ressaisir s'il vous plaÃ®t.");
						break;
				case "adresse" :
						return("Veuillez indiquer votre adresse");
						break;
				case "cp" :
						return("Veuillez indiquer votre code postal");
						break;
				case "ville" :
						return("Veuillez indiquer votre ville");
						break;
				case "objet" :
						return("Veuillez sÃ©lectionner l'objet de votre message");
						break;
				case "message" :
						return("Veuillez saisir votre message");
						break;
				case "numeric" :
						return("Ce champ doit Ãªtre numÃ©rique, il ne peut contenir aucun autre type de caratÃ¨res.");
						break;
				default :
						return(champ);
		}
}

function get_trad_lib(lib)
{
		switch(lib)
		{
				case "vide" :
						return("Le champ XX est obligatoire.\nVeuillez le ressaisir s'il vous plaÃ®t.");
						break;
				default :
						return(lib)
		}
}
*/

/** SlideDown evenements **/

//li class=eventsShown => display none
//=> si prochain pas eventsShown => 
//si fin et compteur > 3 => on reprend les premiers (si events shown => < 3) on arrete
function slideDown(){
	
	//Compte le nombre d'evenements à montrer
	var compteur = 0;
	
	//Liste des offres (li en dessous de la div eventNav)
	var mainDiv = document.getElementById('eventNav');
	var liste = mainDiv.getElementsByTagName('li');
	var nbOffres = liste.length;
	
	//On reorganise la liste de maniere a demarrer a la prochaine offre non  affichee
	partie_1 = new Array();	//Les offres avant les premieres offres affichees
	partie_2 = new Array();	//Les offres apres les premieres offres affichees
	var avant = true;
	var apres = false;
	for(offreIndex = 0; offreIndex < nbOffres; offreIndex++)
	{
		if(liste[offreIndex].className == 'eventsShown')
		{
			//On a passe la premiere offre affichee
			avant = false;
		}
		else
		{
			//Si on a passe la premiere offre affichee
			if(!avant)
			{
				//Alors on est sur les offres apres les premieres offres affichees
				apres = true;	
			}
		}
		
		if(!apres)
		{
			partie_1.push(liste[offreIndex]);
		}	
		else
		{
			partie_2.push(liste[offreIndex]);
		}
	}
	
	//On combine la partie 2 et la partie 1
	liste=partie_2.concat(partie_1);
	//alert(liste.join(", "));
	
	//Parcours des offres
	for(offreIndex = 0; offreIndex < nbOffres; offreIndex++)
	{
		if(liste[offreIndex].className == 'eventsShown')
		{
			//Si l'offre est affichée, on la cache
			liste[offreIndex].className = '';
			liste[offreIndex].style.display = 'none';	
			
			//On augmente le nombre d'offres à afficher
			compteur++;
		}
		else
		{
			//Si l'offre est cachée et que le compteur d'offres a afficher est positif, on affiche celle-ci
			if(compteur > 0)
			{
				liste[offreIndex].className = 'eventsShown';
				liste[offreIndex].style.display = '';	
				
				//On décrémente le nombre d'offres à afficher
				compteur--;
			}
		}	
	}
	
	//Si il y a encore des offres a afficher on reparcours les offres 
	//Jusqu'a ce que le compteur soit nul ou que toutes les offres soient affichees
	if(compteur > 0)
	{
		for(offreIndex = 0; offreIndex < nbOffres; offreIndex++)
		{
			if(liste[offreIndex].className == 'eventsShown' || compteur == 0)
			{
				//Toutes les offres sont affichees, on arrete
				offreIndex = nbOffres;
			}
			else
			{
				liste[offreIndex].className = 'eventsShown';
				liste[offreIndex].style.display = '';	
				
				//On décrémente le nombre d'offres à afficher
				compteur--;
				
			}	
		}
		
	}
}

function str_replace(a, b, str) {
    return str_replace2(str, a, b);
}
function str_replace2(SRs, SRt, SRu) {
  /*
  **  Replace a token in a string
  **    s  string to be processed
  **    t  token to be found and removed
  **    u  token to be inserted
  **  returns new String
  */
  SRRi = SRs.indexOf(SRt);
  SRRr = '';
  if (SRRi == -1) return SRs;
  SRRr += SRs.substring(0,SRRi) + SRu;
  if ( SRRi + SRt.length < SRs.length)
    SRRr += str_replace2(SRs.substring(SRRi + SRt.length, SRs.length), SRt, SRu);
  return SRRr;
}

function redirectTargetBlank(lien)
{
	lien = str_replace('\'','',lien);
	window.open(lien);	
}

function redirectTargetself(lien)
{
	lien = str_replace('\'','',lien);
	document.location.href = lien;	
}

function display_change_rate(id)
{
	//On cache tous les taux
	document.getElementById('rate1').style.display = 'none';	
	document.getElementById('rate2').style.display = 'none';	
	document.getElementById('rate3').style.display = 'none';	
	document.getElementById('rate4').style.display = 'none';	
	
	//On cache tous les taux
	document.getElementById(id).style.display = '';	
	
}

function updateListeHebergement(pIdStation)
{
  $.ajax({
    url : 'ajax/mpListeHebergements.ajax.php',
    method : 'GET',
    data : "village="+pIdStation,
    success : function (data) {
      $('#listeHebergements').html(data);
    }
  });
}

function affichePrecision(pId)
{
		$('.precisionHebergement').hide();
    $('#precisionHeb'+pId).show();
}

function validRechercheMpSejours()
{
  if ($('input[name=village]:checked').length == 0) {
    alert("Pas de village");
    return false;
  }

  if ($('input[name=type_hebergement]:checked').length == 0) {
    alert("Pas d'hÃ©bergement");
    return false;
  }

  $('#sejour').submit();
  return true;
}

function validRechercheMpActivites()
{
  /*if ($('input[name=village[]]:checked').length == 0) {
    alert("Pas de village");
    return false;
  }

  if ($('input[name=theme[]]:checked').length == 0) {
    alert("Pas de thÃ¨mes");
    return false;
  }
  */
  $('#activite').submit();
  return true;
}

