/*
//Retourne la date en français (mar. 09 sept. 2008)
Date.prototype.getFr = function() {
	var aJours = new Array('dim.', 'lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.');
	var aMois = new Array('jan.', 'fév.', 'mars', 'avr.', 'mai', 'juin', 'juil.', 'août', 'sept.', 'oct.', 'nov.', 'déc.');
	return aJours[this.getDay()] + ' ' + this.getDate() + ' ' + aMois[this.getMonth()] + ' ' + this.getFullYear();
}

//Retourne la date au format 'JJ/MM/AAAA'
Date.prototype.getJJMMAAAA = function() {
	var jj = new String(this.getDate());
	if (jj.length==1) jj = '0'+jj;
	var mm = new String(this.getMonth()+1);
	if (mm.length==1) mm = '0'+mm;
	var yyyy = this.getFullYear();
	return jj+'/'+mm+'/'+yyyy;
}

//Ajoute ou retranche X jours d'un object Date()
Date.prototype.addDays = function(day) {
	this.setTime(this.getTime() + day*24*60*60*1000);
}

//Affecte la date 'JJ/MM/AAAA' d'un object Date()
// var d = new Date();
// d.setJJMMAAA('03/12/1981');
Date.prototype.setJJMMAAAA = function(jjmmaaaa) {
	if(jjmmaaaa.search('^([0-9]{2}/[0-9]{2}/[0-9]{4})$')==-1) return false;
	var t = jjmmaaaa.split('/');
	this.setDate(t[0]);
	this.setMonth(t[1]-1);
	this.setFullYear(t[2]);
}
*/

/*
$(".bons-cadeaux-tooltip").each(function() {
				var self = $(this);
				var href = self.attr('href');
				var exp = new RegExp('^#tooltip-[a-z\-]+-[0-9]+$', 'g');
				if(href.match(exp)) {
					var tab = href.split('-');
				
					self.jHelperTip({
						 trigger: "hover",
						 source: "ajax",
						 type: "GET", 
						 url: "/application/ajax/bons-cadeaux/load-tooltip-detail.php",
						 data: "from=personnalisation&type="+tab[1]+"&id="+tab[2],
						 loadingImg: "/public/images/ajax-loader.gif",
						 loadingText: "Chargement...",
						 autoClose: true, 
						 opacity: 0.9
					});
				}
			}); 
 */
(function($){ 
	$.fn.accordionMenu = function() {

		return this.each(function() {
			var menu = $(this);
			
			$("> li.selected", menu).find(".sous-menu").slideToggle('medium');
			$(".sous-menu li.selected", menu).parents(".sous-menu").slideToggle('medium');
			$("> li > * > a", menu).click(function() {
				var ul = $(this).parents('li').find("ul:first");
				if(ul.length>0) {
					if(!ul.is(':visible')) ul.parents('.menu').find('ul:visible').slideUp('medium');
					ul.slideToggle('medium');
				}

				return !$(this).hasClass('disabled');
			});
			
		});
	};

	$.fn.fastNav = function(options) {
		
		var defaults = {selector:"body"};
		var options = $.extend(defaults, options);

		return this.each(function() {
			var self = $(this);
			var selector = $(options.selector);
			var content = "<ul>";
			
			selector.prepend('<a name="top"></a>');
			
			$(".hr", selector).each(function() {
				$(this).before('<div class="top-anchor-link"><a href="#top">Haut de page</a></div>');
			});
			
			$("h3", selector).each(function() {
				var a = $(this).find("a[name]");
				if (a.length==1) content += "<li><a href=\"#"+a.attr("name")+"\">"+$(this).text()+"</a></li>";
			});
			
			content += "</ul>";
			
			self.append(content);
			
		});
	};

	$.fn.imgNotes = function() {

		return this.each(function() {
			var img = $(this);
			var alt = img.attr('alt');

			img.wrap('<div class="img-notes-conteneur"></div>');
			img.parents('.img-notes-conteneur').append('<div class="img-notes-label">'+alt+'</div>');
		});
	};

	$.fn.tooltipBc = function() {

		return this.each(function() {
			var self = $(this);
			var href = self.attr('href').split('#');
			href = href[1];

			var exp = new RegExp('^tooltip-[a-z\-]+-[0-9]+$', 'g');
			
			if(href.match(exp)) {
				var tab = href.split('-');
				self.removeAttr("title").css("cursor", "help").jHelperTip({
					 trigger: "hover",
					 source: "ajax",
					 type: "get", 
					 url: "/application/ajax/bons-cadeaux/load-tooltip-detail.php",
					 data: "from=personnalisation&type="+tab[1]+"&id="+tab[2],
					 loadingImg: "/public/images/ajax-loader.gif",
					 loadingText: "Chargement...",
					 autoClose: true, 
					 opacity: 0.9
				});
			}
		});
	};

	$.fn.prettyRadio = function() {

		return this.each(function() {
			var self = $(this);
			var options = $(".option", self);
			var form = self.parents('form');
			
			options.each(function() {
				$(this).click(function(e) {
					e.preventDefault();
					options.removeClass("checked");
					$(this).addClass("checked").prev("input:radio").attr("checked", "checked");
					form.submit();
					return false;
				});
			});
		});
	};
 
	$.fn.creationBC = function(options) {
		
		return this.each(function() {
			
			var self 		= $(this);
			var form 		= self.parents("form");
			var initRadio 	= $(".init input:radio", self);
			var container	= $(".container", self);
			var prix		= $("#prix span", self);
			
			var main		= function() {
				ajax("&bon-cadeau[etape]=1");
				prix.html("- &euro;");
			};
			
			initRadio.click(main);
			self.find(".reinitialiser").click(main);
			
			var buttonClick = function() {
				var button	= $(this);
				var divAjax = button.parents(".ajax");
				
				button.attr("disabled", "disabled").parent().hide();
				
				if(divAjax.attr("id")=="heb") {
					ajax("&bon-cadeau[etape]=2");
				} else if(divAjax.attr("id")=="rest") {
					ajax("&bon-cadeau[etape]=3");
				} else if(divAjax.attr("id")=="tha") {
					ajax("&bon-cadeau[etape]=4");
				}
				
				divAjax.find('input:radio').each(function() {
					if ($(this).attr('checked')) $(this).hide().parent().prepend('<img src="/public/images/bon-cadeau/selected-box.gif" />');
					else $(this).hide().parent().prepend('<img src="/public/images/bon-cadeau/unselected-box.gif" />');
				});
				divAjax.find('select').each(function() {
					$(this).hide().parent().append('<b>'+$(this).val()+'</b>');
				});
				
			}
			
			var radioClick 	= function() {
				var radio 	= $(this);
				var ul 		= radio.parents(".sans-puce");
				if(radio.val()==0) $(".select", ul).hide(); else $(".select", ul).show();
			}
			
			var ajax		= function(data) {
				$.ajax({
					type	: "post",
					url		: "/application/ajax/bons-cadeaux/creation.php",
					async	: true,
					data	: form.serialize()+data,
					success : ajaxResponse
				});
			};
			
			var ajaxResponse = function(data) {
				var data 	= $(data).hide();
				var radios 	= $("input:radio", data);
				var button	= $("input[class!='reinitialiser']:button", data);
				
				//Sélection du prix
				prix.html($(".montant-total-formule:last", data).html());
				
				//Suppression des éléments div.ajax
				if(data.attr("id")=="heb") container.empty();
				
				//Insertion de l'html
				container.append(data.fadeIn(3000));
				
				//Pour chaque élément ul.sans-puce rencontré
				$(".sans-puce", data).each(function(i) {
					//Si aucune radio n'est sélectionnée on sélectionne la 1ère
					if ($("input:radio:checked", this).length==0) $("input:radio:first", this).attr("checked", "checked");
					//Si la valeur de la radio sélectionnée est égale à 0 on masque l'élément div.select
					if ($("input:radio:checked", this).val()==0) $(".select", this).hide();
				});
				
				//Actions sur les éléments du formulaire
				radios.bind("click", radioClick);
				button.bind("click", buttonClick);
				$("input[class='reinitialiser']:button", data).bind("click", main);
				
				$(".bons-cadeaux-tooltip", data).tooltipBc();
			};

			main();
		});
		
	};
	
	$.fn.slideshow = function(options) {
		
		var defaults = [];
		var options = $.extend(defaults, options);

		return this.each(function() {
			var self = $(this);
			
			jQuery.each(options, function(k, v) {
				var i = new Image();
				i.width = v.w==undefined ? 900 : v.w;
				i.height = v.h==undefined ? 138 : v.h;
				i.src = v.src;
				self.append(i);
			});
			
			var slideSwitch = function() {
				var active = $('img.active', self);
				
				if(active.length==0) active = $('img:last', self);
				var next = active.next().length>0 ? active.next() : $('img:first', self);

				active.addClass('last-active');

				next.css({opacity: 0.0})
				    .addClass('active')
				    .animate({opacity: 1.0}, 1000, function() {active.removeClass('active last-active');});
			};
			
			if($('img', self).length>1) {
				$('img:first', self).addClass('active');
				setInterval(slideSwitch, 5000);
			}
		});
	};
	
	$.fn.actu = function(options) {
		
		var defaults = {selector:'.actu'};
		var options = $.extend(defaults, options);

		return this.each(function() {
			var self = $(this);
			var actus = $(options.selector);
			var interval = null;
			
			$('a.prev', self).click(function () {
				slideSwitch('prev');
				slideStart();
				return false;
			});
			
			$('a.next', self).click(function () {
				slideSwitch('next');
				slideStart();
				return false;
			});
			
			var slideStart = function() {
				clearInterval(interval);
				interval = setInterval(slideSwitch, 10000, 'next');
			};
			
			var slideSwitch = function(action) {
				var active = $(options.selector+':visible', self);
				
				switch(action) {
					case 'prev':
						var next = active.prev().length>0 ? active.prev() : $(options.selector+':last', self);
						break;
					default:
						var next = active.next().length>0 ? active.next() : $(options.selector+':first', self);
				}
				active.hide();
				next.fadeIn('slow');
				navSwitch(actus.index($(options.selector+':visible', self)));
			};
			
			var navSwitch = function(index) {
				var index = parseInt(index)+1;
				$('.nav .counter', self).html(index+'/'+actus.length);
			}
			
			if(actus.length>1) {
				navSwitch(actus.index($(options.selector+':visible', self)));
				slideStart();
			} else {
				$('.nav', self).hide();
			}
		});
	};  
})(jQuery);

//Affichage d'une offre vente privée
viewOffreVP = function(id) {
	$('.offres').hide();
	$('.offre-'+id).show();
	window.location.hash = '#offre-'+id;
}

$(document).ready(function() {
	var flashvars = {};
	var params = {wmode:"transparent", menu:"false"};
	var attributes = {};
	var uniqueId = new Date();
	uniqueId = uniqueId.getFullYear().toString()+uniqueId.getDate().toString()+uniqueId.getMonth().toString();

	//SWF sur la page bons cadeaux
	if($("#bon-cadeau-thalasso-swf").length==1) swfobject.embedSWF("../public/swf/bons-cadeaux/bon-cadeau-thalasso.swf", "bon-cadeau-thalasso-swf", "215", "75", "6.0.0", false, flashvars, params, attributes);
	if($("#bon-cadeau-hotel-swf").length==1) swfobject.embedSWF("../public/swf/bons-cadeaux/bon-cadeau-hotel.swf", "bon-cadeau-hotel-swf", "220", "65", "6.0.0", false, flashvars, params, attributes);
	if($("#webcam-swf").length==1) swfobject.embedSWF("../public/swf/cam.swf", "webcam-swf", "680", "480", "9.0.0", false, flashvars, params, attributes);
	if($("#widgets-swf").length==1) swfobject.embedSWF("../public/swf/index/widgets.swf", "widgets-swf", "440", "195", "9.0.0", false, flashvars, params, attributes);
	
	//SWF sur la page ventes privees
	if ($("#vente-privee-1").length==1) {
		if($("#logo-swf").length==1) swfobject.embedSWF("../public/swf/ventes-privees/1/logo.swf", "logo-swf", "321", "426", "8.0.0", false, flashvars, params, attributes);
		if($("#offres-swf").length==1) {
			$("#offres-swf var").each(function(k,v) {
				flashvars[$(v).attr('class')] = $.trim($(v).text());
			});
			swfobject.embedSWF("../public/swf/ventes-privees/1/offres.swf", "offres-swf", "637", "691", "8.0.0", false, flashvars, params, attributes);
			flashvars = {};
		}
	}
	
	//slideshow sur l'header
	$("#header #slideshow").slideshow([
	    {src:'/public/images/header/bandeau_2.jpg'},
		{src:'/public/images/header/bandeau_3.jpg'},
		{src:'/public/images/header/bandeau_4.jpg'},
		{src:'/public/images/header/bandeau_5.jpg'}
	]);
	
	//Devis radio
	$('#index #devis #radio a').click(function() {
		$(this).parents('#radio').find('a').removeClass().addClass('off');
		var val = $(this).removeClass().addClass('on').attr('name');
		$("input[name='devis[redirection]']").val(val);
		return false;
	});
	
	//slideshow sur les actus & les promos
	$("#actualite").actu({selector:'.actu'});
	$("#promotion").actu({selector:'.promo'});
	
	$('#common-layout .img-notes img').imgNotes();
	$('#common-layout .accordion-menu').accordionMenu();
	
	$("#header a[href$='newsletter']").click(function() {
		$("#newsletter").toggle();
		return false;
	});

	$("#newsletter input[name='newsletter[submit]']").click(function() {
		var email = jQuery.trim($("#newsletter input[name='newsletter[email]']").val());
		$("#newsletter .reponse").html('');
		if(email!='') $("#newsletter .reponse").load('/application/ajax/newsletter.php', {'newsletter[action]':1, 'newsletter[email]':email});
		return false;
	});
	
	$('#common-layout a.soin-anchor').each(function() {
		var self = $(this);
		var href = self.attr('href').split('#');
		var link = href[0];
		var anchor = href[1];
		self.click(function() {return link.length>0;});
		self.jHelperTip({trigger:"hover",dC:"."+anchor});
	});
	
	$('#common-layout #fast-nav').fastNav({selector:"#common-layout .main"});
	
	$("#mes-informations a[href$='etape-suivante']").click(function() {
		var erreur = jQuery('<div />').addClass('erreur').css("display", "none");
		
		$("#mes-informations").find('.erreur').remove();
			
		var id = new Array('mes_informations[nom]', 'mes_informations[prenom]', 'mes_informations[adresse]', 'mes_informations[ville]');
		jQuery.each(id, function(k, v) {
			if(jQuery.trim($("*[@name='"+v+"']").val()).length==0) erreur.clone().html('&raquo; Champ obligatoire.').insertAfter($("*[@name='"+v+"']")).fadeIn("slow");
		});
		
		if($("*[@name='mes_informations[jour_naissance]']").val()=='00' || $("*[@name='mes_informations[mois_naissance]']").val()=='00' || $("*[@name='mes_informations[annee_naissance]']").val()=='0000') {
			erreur.clone().html('&raquo; Date de naissance incorrecte.').insertAfter($("*[@name='mes_informations[annee_naissance]']")).fadeIn("slow");
		}
		
		var v = 'mes_informations[cp]';
		if(!/^[0-9]{5}$/.test($("*[@name='"+v+"']").val())) {
			erreur.clone().html('&raquo; Syntaxe incorrecte.').insertAfter($("*[@name='"+v+"']")).fadeIn("slow");
		}
		
		if($("input[@name='mes_informations[typepaiement]'][@checked]").length!=1) {
			//$("#mes-informations #mode-livraison-alert").show();
			erreur.clone().html('&raquo; Veuillez choisir un mode de livraison.').insertAfter($(".livraison")).fadeIn("slow");
		}
		
		var v = 'mes_informations[port]';
		if(jQuery.trim($("*[@name='"+v+"']").val()).length!=10 && jQuery.trim($("*[@name='mes_informations[tel]']").val()).length!=10) {
			erreur.clone().html('&raquo; Un n&deg; obligatoire.').insertAfter($("*[@name='"+v+"']")).fadeIn("slow");
		}
		
		var v = 'mes_informations[email]';
		if(!/\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test($("*[@name='"+v+"']").val())) {
			erreur.clone().html('&raquo; Syntaxe incorrecte.').insertAfter($("*[@name='"+v+"']")).fadeIn("slow");
		}
		
		var v = 'mes_informations[email_confirm]';
		if(jQuery.trim($("*[@name='"+v+"']").val())!=jQuery.trim($("*[@name='mes_informations[email]']").val())) {
			erreur.clone().html('&raquo; Confirmation incorrecte.').insertAfter($("*[@name='"+v+"']")).fadeIn("slow");
		}
		
		if ($("#mes-informations").find('.erreur').length==0) $("#mes-informations form[name='mes_informations[form]']").submit();
		
		return false;
	});
});