// Initialisation des compteurs de photos
var compteurV;
var compteurH;
var compteurC;
var compteurVH;
// Variables pour le diaporama
var times = 0;
var dureeAffichage = 5000;
var images = new Array();
// Variable pour l'inscription
var nbEnfants = 0;

// Paramètres


// Gestion de l'animatio en page d'accueil
$(document).ready(function() {
	// Initialisation	
	etape = 1;
	nEtapes = 5;
	etapeWidth = 715;

	// On définit la largeur du slide en fonction du nombre d'étapes
	$(".slide").css( { "width": etapeWidth * nEtapes + "px" } );


	// Chaque clic sur un lien du menu

	$(".animationMenu").click ( function () {

		// Sélection du menu
		animationSelectionner( $(this).attr("rel") );
		
		return false;

	});	
		 
	// Change l'icone de chaque menu lors du hover
	$('.menu li').mouseover(function() {
		var obj = $(this).find('span');		
		var laclasse = $(obj).attr('class');
		if(laclasse) {	
			if(laclasse.lastIndexOf('Hover') == -1) {
				$(obj).addClass(laclasse+'Hover');			
				$(obj).removeClass(laclasse);
			}
		}
	});
	
	// Change l'icone de chaque menu lors du out
	$('.menu li').mouseout(function() {
		var obj = $(this).find('span');
		if($(this).find('h3').attr('class').lastIndexOf('on') == -1) {			
			var laclasse = $(obj).attr('class');
			if(laclasse) {
				$(obj).addClass(laclasse.replace('Hover',''));			
				$(obj).removeClass(laclasse);
			}
		}
	});
	
	/** description produit **/	
	// Si l'element messagecarre est présent dans la page, on affiche sa lightbox (si un pack n'est pas complet)
	if($('#messagePack').html()) {		
		showlightbox('messagePack');
	}	
	
	// Change la classe du titre des reportages au survol de la souris
	$('#titreselectionreportage').mouseover(function() {		
		if($('#mesreportages').css('display') == 'none') {
			$(this).addClass('titreselectionreportage_on');			
			$(this).removeClass('titreselectionreportage');
		}
	});
	// Rétablie la classe normale du titre de la liste des reportages
	$('#titreselectionreportage').mouseout(function() {
		if($('#mesreportages').css('display') == 'none') {
			$(this).addClass('titreselectionreportage');		
			$(this).removeClass('titreselectionreportage_on');						
		}
	});
	// au click sur le titre de la selection de reportage
	$('#titreselectionreportage').click(function() {
		toggleSelectionReportage();	
	});
	// au click sur "je modifie" de la liste des reportages
	$('#titreselectionreportage a').click(function() {
		toggleSelectionReportage();	
		return false;
	});
	// au click sur "je modifie" de la selection de photo
	$('#titreselectionphoto a').click(function() {
		toggleSelectionReportage();	
		return false;
	});
	
	// Gestion de la selection	
	// Switch d'un reportage à l'autre
	$('.listereportages a').click(function() {
		var leli = $(this).parents('.listereportages');
		var idreportage = $(this).parents('.listereportages').attr('id').replace('reportage_','');
		$('#listereportages').find('li').each(function(i) {
			$(this).removeClass('selected');
			$('#listephotos_'+$(this).attr('id').replace('reportage_','')).hide();
		});
		$(leli).addClass('selected');
		$('#listephotos_'+idreportage).show();
		return false;
	});
	
	// On stock le nombre de photos verticales et horizontales déjà séléctionnées
	compteurV = parseInt($('#nV').attr('value'));
	compteurH = parseInt($('#nH').attr('value'));
	compteurC = parseInt($('#nC').attr('value'));
	compteurVH = parseInt($('#nVH').attr('value'));
	// Ajout d'une photo à la selection
	$('.listephotos li').click(function() {
		// Indique si l'on change de reportage ou non pour notre selection
		var selectionImage = true;
		var idreportage = $(this).attr('rel');
		var laphoto = this;		
		// On  boucle sur touss les reportages
		$('.selectionphotos').each(function(i) {
			// Test si l'on vient pas de changer de reportage. Si oui on supprime la selection
			if($(this).css('display') == 'block' && $(this).attr('id').replace('selectionphotos_','') != idreportage) {
				// Lightbox de confirmation
				showlightbox('messagereportage');
				selectionImage = false;
				var oldreportage = this;
				// Si on confirme le changement de reportage
				$('.changereportage').click(function() {
					closelightbox();
					// On cache le reportage duquel on vient
					$(oldreportage).hide();
					// Pour chaque photo qui etait selectionnée on l'enleve de la selection et on la ré-affiche sur la liste des photos du reportage
					$(oldreportage).find('li').each(function(i) {
						if($(this).css('display') == 'block') {
							var idphoto = $(this).attr('id').replace('selection_','');
							$('#photo_'+idphoto).show();
						}
						$(this).hide();
					});
					// On affiche le nouveau reportage selectionné
					$('#selectionphotos_'+idreportage).show();
					// On rétablie les compteurs de selection à 0
					compteurV = 0;
					compteurH = 0;
					compteurC = 0;
					compteurVH = 0;
					// On affiche la photo selectionnée
					switchImage(laphoto, idreportage);
					return false;
				});
				
			}
		});
		// Si l'on ne change pas de reportage on affiche la photo selectionnée
		if(selectionImage) {
			switchImage(this, idreportage);
		}
	});
	
	// Retrait d'une photo à la selection
	$('.selectionphotos li').click(function() {
		var idphoto = $(this).attr('id').replace('selection_','');
		var formatphoto = $(this).children('img').attr('rel');
		switch(formatphoto) {
			case 'V':
					compteurV--;
					$('#photo_'+idphoto).fadeIn('slow');
					$(this).fadeOut('slow');
			break;
			case 'H':
					compteurH--;
					$('#photo_'+idphoto).fadeIn('slow');
					$(this).fadeOut('slow');
			break;
		}	
		compteurC--;
		compteurVH--;
		if($('#mesreportages').css('display') == 'none') {
			toggleSelectionReportage();
		}
	});	
	
	$('#ajouteraupanier').click(function() {
		if(parseInt($('#nC').attr('value')) > 0 || (parseInt($('#nVH').attr('value')) > 0 && parseInt($('#nT').attr('value')) == 1)) {
			$('.selectionphotos').each(function(i) {
				if($(this).css('display') == 'block') {
					$(this).find('li').each(function(i) {
						if($(this).css('display') == 'block') {
							// On récupère la finition de la photo							
							var finition = $('#finition').attr('value');
							if(finition == '' || finition == 'undefined') {
								finition = 'C';
							}
							
							var src = $(this).children('img.photo').next('img').attr('rel')+'/'+finition+'/1';
							if(parseInt($('#nC').attr('value')) == 1) {
								showlightbox('messagecarre', src.replace('/90/', '/270/'));							
								$('.valideimagecarree').click(function() {
									closelightbox();
									submitSelection();
									return false;
								});
							}else {
								submitSelection();
							}
						}
					});
				}
			});			
		}else if(parseInt($('#nVH').attr('value')) > 0) {
			submitSelection();
		}else {
			submitSelection();
		}
	});
	
	
	
	/** MES CONTACTS **/
	$('#ajoutercontact').click(function() {
		$('#formAjouterContact').slideToggle();	
		return false;
	});
	$('.suppContact').click(function() {
		var idContact = $(this).attr('rel');
		$('#suppContact_'+idContact).slideToggle();
		return false;
	});
	$('.annulerSuppContact').click(function() {
		var idContact = $(this).attr('rel');
		$('#suppContact_'+idContact).slideUp();
		return false;
	});
	
	
	$('#modifierAdFact').click(function() {
		$('#adresseFacturation').fadeOut(function() {
			$('#modifierAdFact').css('visibility', 'hidden');
			$('#formAdresseFacturation').fadeIn();
		});
		return false;
	});
	
	$('#modifierAdLiv').click(function() {
		$('#adresseLivraison').fadeOut(function() {
			$('#modifierAdLiv').css('visibility', 'hidden');
			$('#formAdresseLivraison').fadeIn();
		});
		return false;
	});
	
	
	$('.voirphotos').click(function() {
		var idreportage = $(this).attr('rel');
		var lebouton = this;
		$('#'+idreportage).slideToggle(function() {
			$(lebouton).addClass('voirphotosOn');
			if($('#'+idreportage).css('display') == 'none') {
				$(lebouton).removeClass('voirphotosOn');
			}
		});
		return false;
	});
	$('.voirphoto').click(function() {
		var idreportage = $(this).attr('rel');
		var lebouton = this;
		$('#'+idreportage).slideToggle(function() {
			$(lebouton).addClass('voirphotosOn');
			if($('#'+idreportage).css('display') == 'none') {
				$(lebouton).removeClass('voirphotosOn');
			}
		});
		return false;
	});
	$('.introAjouterContact').click(function() {		
		var boxajouter = $(this).attr('rel');
		$('#'+boxajouter).slideToggle();
		return false;
	});
	
	$('.voir').click(function() {
		var lienvoir = $(this).attr('rel');
		$('#rep_'+lienvoir).slideToggle();
		return false;
	});
	
	/** INSCRIPTION **/
	$('#inscriptionAjouterEnfant').click(function() {		
		$('#inscriptionListeEnfants').find('ul').each(function(i) {
			if($(this).css('display') == 'block') {
				nbEnfants = i;
			}			
		});
		nbEnfants++;
		$('#Enfant'+nbEnfants).fadeIn();
		return false;
	});
	
	// Finition photos
	$('#finition').change(function() {
		showloading();
		var finition = $(this).attr('value');
		var nbPhotosSelectionnees = $('ul.selectionphotos').find('img.photo').length - 1;
		$('ul.selectionphotos').find('img.photo').each(function(i) {			
			// On récupère la source de l'image originale
			src = $(this).next('img').attr('rel');	
			// On change la source avec la bonne finition
			$(this).attr('src', src+'/'+finition);
			// Si la dernière photo a été chargée, on enlève le loading
			if(nbPhotosSelectionnees >= i) {$(this).load(function() {closeloading();});}
		});				
	});
	
	// Visualisation des photos du panier en tooltip
	if(		$('#listepanier .codearticlePanier a.voirPhotosSelectionnees').length) {
		$('#listepanier .codearticlePanier a.voirPhotosSelectionnees').qtip({
			content: {
				text: '<img src="/img/design/ajax-loader-blue.gif" alt="Chargement des photos" />',
				prerender: true
			},
			show: 'mouseover',
			hide: 'mouseout',
			position: {
				corner: {
					target: 'topLeft',
					tooltip: 'bottomLeft'
				},
				target: 'mouse',			
				adjust: {
					x: -70
				}
			},
			style: {
				border: {
					width: 3,
					radius: 0,
					color: '#ADD9ED'
				},
				title: {
					background: '#D0E9F5',
					color: '#5E99BD'
				},
				background: '#E5F6FE',
				color: '#4D9FBF',
				width: 'auto!important',
				height: 100
			}
		});
		$('#listepanier .codearticlePanier a.voirPhotosSelectionnees').mouseenter(function() {
			var liParent = $(this).parents('li');		
			$(this).qtip("api").updateContent(liParent.find('.photosChoisies').html());
			$(this).qtip("api").updateWidth();
		});
	}	
});

function toggleSelectionPhotos() {
	var idreportage = $(this).attr('rel');
	$('#mesphotos').slideToggle(function() {
		if($('#mesphotos').css('display') == 'none') {
			$('#voirphotos').addClass('voirphotosOn');
			$('#voirphotos').removeClass('voirphotos');
			$('#'+idreportage).children('li').show();			
		} else {
			$('#voirphotos').addClass('voirphotos');
			$('#voirphotos').removeClass('voirphotosOn');
			$('#'+idreportage).children('li').show();
		}
	});
}
// Affiche ou non la liste des reportages disponibles pour un produit
function toggleSelectionReportage() {
	$('#mesreportages').slideToggle('slow', function() {
		if($('#mesreportages').css('display') == 'none') {	
			$('#titreselectionreportage').addClass('titreselectionreportage');		
			$('#titreselectionreportage').removeClass('titreselectionreportage_on');
			$('#titreselectionreportage').children('a').text('Je modifie');
			$('#titreselectionphoto').children('a').text('Je modifie');
		}else {
			$('#titreselectionreportage').children('a').text('');
			$('#titreselectionphoto').children('a').text('');
		}
	});
}

function submitSelection() {
	var actionPanier = $('#actionPanier').attr('value');
	var photos = new Array();
	var j = 0;
	showloading();
	$('.selectionphotos').each(function(i) {
		if($(this).css('display') == 'block') {
			$(this).find('li').each(function(i) {
				if($(this).css('display') == 'block') {
					photos[j] = $(this).attr('id').replace('selection_','');
					idreportage = $(this).attr('rel');
					j++;
				}
			});
		}
	});
	if(photos.length == parseInt($('#nT').attr('value'))) {
		var lesphotos = '';
		var idProduit = $('#idProduit').attr('value');
		var idCommandeProduit = $('#idCommandeProduit').attr('value');
		var finition = $('#finition').attr('value');
		for(photo in photos) {
			lesphotos += photos[photo]+'-';
		}
		$.ajax({
			type: "POST",
			url: site_url+controller+"/"+actionPanier,
			data: "idProduit="+idProduit+"&idReportage="+idreportage+"&photos="+lesphotos+"&idCommandeProduit="+idCommandeProduit+"&finition="+finition,
			success: function(msg){
				closeloading();
				showlightbox('messageconfirmationpanier');
			},
			error: function(msg) {
				alert('Erreur : '+msg);
			}
		});
	}else {
		closeloading();
		alert('Vous n\'avez pas sélectionné assez de photos.');
	}
}

function switchImage(obj, idreportage) {	
	var idphoto = $(obj).attr('id').replace('photo_','');
	// Test si on a pas atteint le nombre maximum de photos
	if(parseInt($('#nC').attr('value')) == 0 && parseInt($('#nVH').attr('value')) == 0) {
		if((parseInt(compteurV)+parseInt(compteurH)) < parseInt($('#nT').attr('value'))) {
			var formatphoto = $(obj).children('img').attr('rel');
			switch(formatphoto) {
				case 'V':
					// Test si on a pas atteint le nombre maximum de photos verticales
					if(compteurV < parseInt($('#nV').attr('value'))) {
						compteurV++;
						$('#selection_'+idphoto).fadeIn('slow');
						$(obj).fadeOut('slow');
					}else {
						alert('Nombre de photos verticales maximum atteint');
					}
				break;
				case 'H':
					// Test si on a pas atteint le nombre maximum de photos horizontales
					if(compteurH < parseInt($('#nH').attr('value'))) {
						compteurH++;
						$('#selection_'+idphoto).fadeIn('slow');
						$(obj).fadeOut('slow');
					}else {
						alert('Nombre de photos horizontales maximum atteint');
					}
				break;
			}
		}else {
			alert("Nombre maximum de photos atteint.\nPour retirer une photo cliquez dessus.");
		}
	}else if(parseInt($('#nC').attr('value')) > 0 && parseInt(compteurC) < parseInt($('#nT').attr('value'))) {
		compteurC++;
		$('#selection_'+idphoto).fadeIn('slow');
		$(obj).fadeOut('slow');
	}else if(parseInt($('#nVH').attr('value')) > 0 && parseInt(compteurVH) < parseInt($('#nT').attr('value'))) {
		compteurVH++;
		$('#selection_'+idphoto).fadeIn('slow');
		$(obj).fadeOut('slow');
	}else {
		alert("Nombre maximum de photos atteint.\nPour retirer une photo cliquez dessus.");
	}
}

function animationSelectionner (i)
{
    // Calcul du déplacement
    var deplacement = (1 - i) * etapeWidth;
	
    // Enregistrement de l'étape
    etape = i;

    // Déplacement
    $(".slide").animate( { "left": deplacement }, 1000 );

    // Sélection du menu
	 $('.menudefil').find('li.on').each(function(i) {
		$(this).removeClass('on');
	 });
    $("#menu" + i).addClass("on");


    clearTimeout(animation);
    animation = setTimeout( animationSuivant, 5000);

}

function animationSuivant()
{
   animationSelectionner( (etape % nEtapes) + 1  );
}

animation = setTimeout( animationSuivant, 5000);

// Popunder
function popunder(adresse){
   var windowParam ="width=800,height=510,scrollbars=1,resizable=1,toolbar=1,location=1,menubar=1,status=1,directories=0";
   win2=window.open(adresse, "", windowParam);
   win2.blur();
   window.focus();
}
