
/**
 * Fonctions de chargement des widgets
 *
 * @author      G. JAGUIN
 * @copyright   BleuRoy.com
 * @version     1.2.0
 */

/*
 * Widget 1 : L'offre Internet du jour
 * Widget 2 : Les nouveaux produits Casino
 * Widget 4 : En ce moment en magasin
 * Widget 5 : Mon magasin
 * Widget 6 : Catalogue cadeaux smiles
 * Widget 7 : Casino recrute !
 * Widget 8 : Communiqués de presse
 * Widget 9 : Coaching Nutrition
 */

/* -------------------- Widget 1 : L'offre Internet du jour -------------------- */


//liste des enseignes du widget
var listeEnseignesWidget1 = [	{id: 5, libelle: "Casino Vacances"},
								{id: 6, libelle: "CGéant"},
								{id: 8, libelle: "Banque Casino"},
								{id: 10, libelle: "Mon Super Casino"}];
			
//initialisation de l'objet WidgetParams
var paramsWidget1 = new WidgetParams();

//initialisation du widget
function initWidget1()
{
	new Ajax.Request('/widgets/getWidgetParams',
	{
		method: 'post',
		postBody: 'id=1',
		onSuccess: function(transport, json)
		{
			if (json)
			{
				paramsWidget1.AddParams(json);
			}
			else
			{
				paramsWidget1.AddParam('widget1_enseigne-5', 1);
				paramsWidget1.AddParam('widget1_enseigne-6', 1);
				paramsWidget1.AddParam('widget1_enseigne-8', 1);
				paramsWidget1.AddParam('widget1_enseigne-10', 1);
			}

			var html = '';
			listeEnseignesWidget1.each(function(enseigne) {
				html += '<li><input type="checkbox" id="widget1_enseigne-'+enseigne.id+'" name="widget1_enseigne-'+enseigne.id+'" value="1" ';
				if (paramsWidget1.GetValue('widget1_enseigne-'+enseigne.id)) html += 'checked="checked"';
				html += '/> <label for="widget1_enseigne-'+enseigne.id+'">'+enseigne.libelle+'</label></li>';
			});
			$('widget-1').down('div.blocEditWidget').down('form').down('ul').update(html);

			loadWidget1();
		},
		onFailure: function(){alert("Un problème est survenu lors de la réception des paramètres du widget \"L'offre Internet du jour\".");}
	});
}

//chargement du widget
function loadWidget1()
{
	var enseignesCheckedWidget1 = new Array();
	listeEnseignesWidget1.each( function(enseigne)
	{
		if ($('widget1_enseigne-'+enseigne.id).checked)
			enseignesCheckedWidget1.push(enseigne.id);
	});
	
	new Ajax.Request('/widgets/getWidgetData',
	{
		method: 'post',
		postBody: 'id=1&enseignes='+enseignesCheckedWidget1+'&params='+paramsWidget1.RenderJSON(),
		onSuccess: function(transport, json)
		{
			html = '';
			json.each(function(enseigne, key)
			{
				enseigne.contenus.each( function(data)
				{
					html += '<p><a href="'+data.url+'" class="vert">';
					if (data.image)
						html += '<img src="/uploads/medias/'+data.image+'" alt="'+data.titre+'" width="288" height="99" />';
					else
						html += data.chapo;
					html += '</a></p>';
				});
				html += '<p class="lienFlecheVert"><a href="'+enseigne.url+'">Toutes les offres sur '+enseigne.libelle+'</a></p>';
			});
			if (json.length == 0)
				html = '<br/><p class="textCenter bold"><a href="javascript:void(0);" onclick="$(\'widget-1\').down(\'div.blocEditWidget\').show()">Cliquez ici pour choisir les promotions à afficher</a></p>';
			$('widget-1').down('div.blocContentWidget').update(html);
		},
		onFailure: function(){alert("Un problème est survenu lors de la mise à jour du widget \"L'offre Internet du jour\".")}
	});
}


/* -------------------- Widget 2 : Les nouveaux produits Casino -------------------- */


var jsonWidget2;

//chargement du widget
function loadWidget2()
{
	new Ajax.Request('/widgets/getWidgetData',
	{
		method: 'post',
		postBody: 'id=2',
		onSuccess: function(transport, json)
		{
			jsonWidget2 = json;
			html = '<form action="http://www.produits-casino.fr/spip.php?page=panier-recette" method="post" name="form_produits" id="form_produits"><input type="hidden" value="ajouter_caddie" name="do_action"/><p><input type="hidden" value="'+getIdProduitWidget2(0)+'" name="id_article[]"/><img src="'+getImageProduitWidget2(0)+'" alt="'+jsonWidget2[0].title+'" class="imgLeft" /><a href="'+jsonWidget2[0].link+'"><strong class="grand">'+jsonWidget2[0].title+'</strong></a><br/>'+getTextProduitWidget2(0)+'</p></form>';
			html += '<p class="lienAjouter"><a href="#" onclick="$(\'form_produits\').submit()">Ajouter à ma liste de courses</a></p>';
			html += '<p class="lienFleche"><a href="'+jsonWidget2[0].link+'">Voir le détail du produit</a></p>';
			html += '<div class="blocSliderProduit clear"><a href="#" class="sliderPrec" title="Précédent"></a><div class="masqueProduit"><div class="sliderProduit" id="sliderProduit">';
			for (i=0;i<jsonWidget2.length;i++)
				html += '<a href="javascript:void(0);" onclick="changeProduitWidget2('+i+')"><img src="'+getImageProduitWidget2(i)+'" alt="'+jsonWidget2[i].title+'" width="75" height="54" /></a>';
			html += '</div></div><a href="#" class="sliderSuiv" title="Suivant"></a></div>';
			$('widget-2').down('div.blocContentWidget').update(html);
			initSliderProduits('sliderProduit');
		},
		onFailure: function(){alert("Un problème est survenu lors de la mise à jour du widget \"Les nouveaux produits Casino\".")}
	});
}

//changement du produit affiché au clic
function changeProduitWidget2(id)
{
	html = '<input type="hidden" value="'+getIdProduitWidget2(id)+'" name="id_article[]"/><img src="'+getImageProduitWidget2(id)+'" alt="'+jsonWidget2[id].title+'" class="imgLeft" /><a href="'+jsonWidget2[id].link+'"><strong class="grand">'+jsonWidget2[id].title+'</strong></a><br/>'+getTextProduitWidget2(id);
	$('widget-2').down('div.blocContentWidget').down('p', 0).update(html);
	html = '<a href="'+jsonWidget2[id].link+'">Voir le détail du produit</a>';
	$('widget-2').down('div.blocContentWidget').down('p.lienFleche').update(html);
}

//récup de l'identifiant produit
function getIdProduitWidget2(id)
{
	return jsonWidget2[id].author;
}

function getTextProduitWidget2(id)
{
	var text = jsonWidget2[id].content;
	if (text.length > 90) return text.substr(0, 90)+'...';
	else return text;
}

function getImageProduitWidget2(id)
{
	if (jsonWidget2[id].enclosure)
		return jsonWidget2[id].enclosure;
	else
		return 'http://www.casino.fr/images/produit_empty.png';
}


/* -------------------- Widget 4 : En ce moment en magasin -------------------- */


//liste des enseignes du widget
var listeEnseignesWidget4 = [	{id: 1, libelle: "Supermarché Casino"},
                             	{id: 2, libelle: "Géant Casino"},
								{id: 4, libelle: "Casino Cafétéria"},
								{id: 9, libelle: "Petit Casino"}];

//initialisation de l'objet WidgetParams
var paramsWidget4;

//initialisation du widget
function initWidget4()
{
	paramsWidget4 = new WidgetParams();
	new Ajax.Request('/widgets/getWidgetParams',
	{
		method: 'post',
		postBody: 'id=4',
		onSuccess: function(transport, json)
		{
			if (json)
			{
				paramsWidget4.AddParams(json);
			}
			else
			{
				paramsWidget4.AddParam('widget4_enseigne-1', 0);
				paramsWidget4.AddParam('widget4_enseigne-2', 0);
				paramsWidget4.AddParam('widget4_enseigne-4', 0);
				paramsWidget4.AddParam('widget4_enseigne-9', 0);
				paramsWidget4.AddParam('nbTitlesWidget4', 1);
			}
				
			var html = '';
			listeEnseignesWidget4.each(function(enseigne) {
				html += '<li><input type="checkbox" id="widget4_enseigne-'+enseigne.id+'" name="widget4_enseigne-'+enseigne.id+'" value="1" ';
				if (paramsWidget4.GetValue('widget4_enseigne-'+enseigne.id)) html += 'checked="checked"';
				html += '/> <label for="widget4_enseigne-'+enseigne.id+'">'+enseigne.libelle+'</label></li>';
			});
			$('widget-4').down('div.blocEditWidget').down('form').down('ul').update(html);
			
			if (paramsWidget4.GetValue('nbTitlesWidget4') == 99)
				$('nbTitlesWidget4').selectedIndex = 3;
			else
				$('nbTitlesWidget4').selectedIndex = paramsWidget4.GetValue('nbTitlesWidget4')-1;

			loadWidget4();

		},
		onFailure: function(){alert("Un problème est survenu lors de la réception des paramètres du widget \"En ce moment en magasin\".");}
	});
}

//chargement du widget
function loadWidget4()
{
	var enseignesCheckedWidget4 = new Array();

	listeEnseignesWidget4.each( function(enseigne)
	{
		if ($('widget4_enseigne-'+enseigne.id).checked)
			enseignesCheckedWidget4.push(enseigne.id);
	});
	new Ajax.Request('/widgets/getWidgetData',
	{
		method: 'post',
		postBody: 'id=4&enseignes='+enseignesCheckedWidget4+'&limit='+$F('nbTitlesWidget4')+'&params='+paramsWidget4.RenderJSON(),
		onSuccess: function(transport, json)
		{
			html = '';
			json.each(function(enseigne, key)
			{
			  	enseigne.contenus.each( function(data)
				{
					html += '<a href="'+data.url+'"><img src="/uploads/medias/'+data.image+'" alt="'+data.titre+'" width="167" height="107" class="imgRight" /></a>';
					html += '<h4><img src="/uploads/medias/'+enseigne.picto+'" alt="" width="26" height="26" /> '+enseigne.libelle+'</h4>';
					html += '<p><a href="'+data.url+'" class="vert">'+data.chapo+'</a></p>';
					html += '<div class="clear"/>';
				});
			});
			if (json.length == 0)
				html = '<br/><p class="textCenter bold"><a href="javascript:void(0);" onclick="$(\'widget-4\').down(\'div.blocEditWidget\').show()">Cliquez ici pour choisir les promotions à afficher</a></p>';
			else
				html += '<div class="clear"></div>';
			$('widget-4').down('div.blocContentWidget').update(html);
		},
		onFailure: function(){alert("Un problème est survenu lors de la mise à jour du widget \"En ce moment en magasin\".")}
	});
}


/* -------------------- Widget 5 : Mon magasin -------------------- */

var bonsReduction;
var panierBonsReduction;
var panierOn = false;
var jsonWidget5;
var currentDetailReduction = 0;

//chargement du widget
function loadWidget5()
{
	new Ajax.Request('/widgets/getWidgetData',
	{
		method: 'post',
		postBody: 'id=5',
		onSuccess: function(transport, json)
		{
			html = '<div id="magasinOnglets" class="ongletMonMagasinOn"><a class="ongletMonMagasin" href="#" onclick="changeTabWidget5(\'ongletMonMagasin\'); return false;">&nbsp;</a><a class="ongletMesReductions" href="#" onclick="changeTabWidget5(\'ongletMesReductions\'); return false;">&nbsp;</a></div>';
			/*html += '<a class="ongletMonMagasin" href="#" onclick="changeTabWidget5(\'ongletMonMagasin\');">&nbsp;</a>';
			html += '<a class="ongletMesReductions" href="#" onclick="changeTabWidget5(\'ongletMesReductions\');">&nbsp;</a>';*/
			html += '</div>';
			
		
			if (json.enseigne)
			{
				jsonWidget5 = json;
				
				/* ---- TEXTE ONGLET REDUCTIONS ---- */
				
				if (jsonWidget5.bons_reduction)
				{
					bonsReduction = json.bons_reduction;
				}
				if (jsonWidget5.panier_bons_reduction)
				{
					panierBonsReduction = json.panier_bons_reduction;
				}
				
				html += '<div id="contentOngletMesReductions" style="display: none;">';
				
				html += '  <h3 class="contentSubTabReductions1">Les réductions en cours dans mon magasin</h3>';
				html += '  <h3 class="contentSubTabReductions2" style="display: none;">Mon panier : <span class="nbBonsReductionPanier"></span></h3>';
				
				/* -- DETAIL BON DE REDUCTION -- */
				
				html += '  <div class="detailBonReduction"></div>';
				html += '  <div class="slider"></div>';
				
				/* -- TEXTE SUBTAB 1 -- */
				
				html += '  <div class="contentSubTabReductions1">';
				html += '    <h4><span class="nbBonsReductionPanier">0 réduction</span> à imprimer <em>(&nbsp;<a href="#" class="infobulle">+ d\'infos<span class="blocBulle">';
				html += '      <span class="haut"></span>';
				html += '      <span class="content">Retrouvez dans votre panier toutes les réductions que vous avez sauvegardées et imprimez-les en une seule fois !</span>';
				html += '      <span class="bas"></span>';
				html += '      </span></a>&nbsp;)</em>';
				html += '    </h4>';		
				html += '    <p class="lienFleche"><a href="#" onclick="changeSubTabReductionsWidget5(); return false;">Voir mon panier de réductions</a></p>';
				if (json.oladesmarques_enseigne_id)
        {
          html += '    <br />';
          html += '    <p>Encore plus de réductions avec la Ola des Marques</p>';
          html += '    <p class="lienFleche"><a href="http://www.oladesmarques.com/spip.php?page=decouvrir&id_secteur='+json.oladesmarques_enseigne_id+'">Découvrir de nouveaux produits</a></p>';
          html += '    <p class="lienFleche"><a href="http://www.oladesmarques.com/spip.php?page=jeu&id_secteur='+json.oladesmarques_enseigne_id+'">Gagner de nombreux cadeaux</a></p>';
        }
				html += '  </div>';
				
				/* -- TEXTE SUBTAB 2 -- */
				
				html += '  <div class="contentSubTabReductions2" style="display: none;">';
				html += '    <p class="lienFleche"><a href="/bons-reduction/reductions.pdf" target="_blank">Tout imprimer !</a></p>';
				html += '    <p><a href="#" onclick="clearCartWidget5();">J\'ai imprimé mes coupons, <strong>vider mon panier</strong></a></p>';
				html += '    <p class="lienFleche"><a href="#" onclick="changeSubTabReductionsWidget5(); return false;">Retour aux réductions</a></p>';
				html += '  </div>';
				
				html += '</div>';
				
				/* ---- TEXTE ONGLET MAGASIN ---- */
				
				html += '<div id="contentOngletMonMagasin">';
				html += '  <table><tr><td width="35"><img src="/uploads/medias/'+jsonWidget5.picto+'" alt="" width="26" height="26" /></td>';
				html += '    <td width="200"><h4>'+jsonWidget5.enseigne+'<br/>'+jsonWidget5.ville+'</h4><p>'+jsonWidget5.adresse1;
				if (jsonWidget5.adresse2) html += '<br/>'+jsonWidget5.adresse2;
				html += '    <br/>'+jsonWidget5.cp+' '+jsonWidget5.ville+'</p>';
				if (jsonWidget5.tel)
				{
					html += '    <p>Tél: '+jsonWidget5.tel+'</p>';
				}
				/*if (jsonWidget5.horaires) html += '<p>Horaires: '+jsonWidget5.horaires+'</p>';*/
				html += '    </td><td><p><a href="/magasins/search?q='+jsonWidget5.cp+'">Plan &raquo;</a></p></td></tr></table>';
				html += '</div>';
				
				$('widget-5').down('div.blocContentWidget').update(html);
				$('widget-5').down('div.blocHautWidget').down('h3').update('Mon magasin '+jsonWidget5.enseigne);
				
				updateSliderWidget5();
				updateCartCountWidget5(panierBonsReduction.size());			
			}
			else
			{
				html += '<div id="contentOngletMonMagasin">';
				html += '  <br/><p class="textCenter bold">Vous n\'avez pas encore choisi votre magasin !</p>';
				html += '  <br/><p class="lienFlecheRose"><a href="javascript:void(0);" onclick="$(\'widget-5\').down(\'div.blocEditWidget\').show()">Faire une recherche</a></p>';
				html += '</div>';
				
				html += '<div id="contentOngletMesReductions" style="display: none;">';
				html += '  <p class="reducChapeau">Découvrez chaque semaine dans ce widget les bons de réduction valables dans votre magasin et imprimez-les directement chez vous !</p>';
				html += '  <p>Pour afficher les réductions, vous devez être inscrit. Si vous êtes déjà inscrit, connectez-vous à votre compte.</p>';
				html += '  <p class="lienFlecheRose"><a href="/creer-espace-personnel-casino.html">Cliquez ici pour vous inscrire</a></p>';
				html += '</div>';
				
				$('widget-5').down('div.blocContentWidget').update(html);
			}
		},
		onFailure: function(){alert("Un problème est survenu lors de la mise à jour du widget \"En ce moment en magasin\".")}
	});
}

/**
 * Changement de rubrique de l'onglet Mes Réductions
 */
function changeSubTabReductionsWidget5()
{
	$('widget-5').down('div#contentOngletMesReductions').down('div.detailBonReduction').update('');
	
	if (panierOn)
	{
		$$('.contentSubTabReductions1').each(function(elem){$(elem).show();});
		$$('.contentSubTabReductions2').each(function(elem){$(elem).hide();});
	}
	else
	{
		$$('.contentSubTabReductions1').each(function(elem){$(elem).hide();});
		$$('.contentSubTabReductions2').each(function(elem){$(elem).show();});
	}
	
	panierOn = !panierOn;
	
	updateSliderWidget5();
	
	return false;
}

/**
 * Ajout d'un bon de réduction au panier de bons de réduction
 */
function removeBonReductionFromCartWidget5(id)
{
	var messageToUpdate = $('widget-5').down('div#contentOngletMesReductions').down('a.supprimerReduction'+id);
	$(messageToUpdate).update('<img src="/images/widget-loader-vert.gif" alt="" />');
	
	new Ajax.Request('/widgets/addOrRemoveBonReductionCart',
	{
		method: 'post',
		postBody: 'id='+id+'&do=remove',
		onSuccess: function(transport, json)
		{
			updateCartWidget5();
			if (id == currentDetailReduction)
			{
				$('widget-5').down('div.blocContentWidget').down('div#contentOngletMesReductions').down('div.detailBonReduction').update('');
			}
			updateCartCountWidget5(json.nbBonsReduction);
		},
		onFailure: function(){alert("Un problème est survenu lors du retrait du bon de réduction du panier de réductions.")}
	});
	
	return false;
}

/**
 * Ajout d'un bon de réduction au panier de bons de réduction
 */
function addBonReductionToCartWidget5(id)
{
	var messageToUpdate = $('widget-5').down('div#contentOngletMesReductions').down('div.detailBonReduction').down('p', 2);
	$(messageToUpdate).update('<a href="#"><img src="/images/widget-loader-rose.gif" alt="" /></a>');
	
	new Ajax.Request('/widgets/addOrRemoveBonReductionCart',
	{
		method: 'post',
		postBody: 'id='+id+'&do=add',
		onSuccess: function(transport, json)
		{
			$(messageToUpdate).update('Le bon de réduction a bien été enregistré');
			updateCartCountWidget5(json.nbBonsReduction);
			updateCartWidget5();
		},
		onFailure: function(){alert("Un problème est survenu lors de l'ajout du bon de réduction au panier de réductions.")}
	});
	
	return false;
}

/**
 * Ajout d'un bon de réduction au panier de bons de réduction
 */
function clearCartWidget5()
{
	var messageToUpdate = $('widget-5').down('div#contentOngletMesReductions').down('div.contentSubTabReductions2').down('p', 1);
	$(messageToUpdate).insert('&nbsp;<img src="/images/widget-loader-rose.gif" alt="" />', {position: 'after'});
	
	new Ajax.Request('/widgets/clearCart',
	{
		method: 'post',
		onSuccess: function(transport, json)
		{
			updateCartWidget5();
			$('widget-5').down('div.blocContentWidget').down('div#contentOngletMesReductions').down('div.detailBonReduction').update('');
			updateCartCountWidget5(json.nbBonsReduction);
			$(messageToUpdate).update('<a href="#" onclick="clearCartWidget5(); return false;">J\'ai imprimé mes coupons, <strong>vider mon panier</strong></a>');
		},
		onFailure: function(){alert("Un problème est survenu lors de la suppression des éléments du panier de réductions.")}
	});
	
	return false;
}

/**
 * Mise à jour du panier de bons de réductions
 */
function updateCartWidget5()
{
	new Ajax.Request('/widgets/getWidgetData',
	{
		method: 'post',
		postBody: 'id=5',
		onSuccess: function(transport, json)
		{
			if (json.enseigne)
			{
				if (json.panier_bons_reduction)
				{
					panierBonsReduction = json.panier_bons_reduction;
					if (panierOn)
					{
						updateSliderWidget5();
					}
				}
			}
		},
		onFailure: function(){alert("Un problème est survenu lors de la mise à jour du widget \"En ce moment en magasin\".")}
	});
}

/**
 * Mise à jour du nombre de bons de réduction dans le panier de bons de réductions
 */
function updateCartCountWidget5(nbBonsReduction)
{
	html = nbBonsReduction+' r&eacute;duction';
	
	if (nbBonsReduction > 1)
	{
		html += 's';
	}
	
	$$('.nbBonsReductionPanier').each( function(element, key)
	{
		$(element).update(html)
	});
	
	if (nbBonsReduction == 0)
	{
		$('widget-5').down('div#contentOngletMesReductions').down('div.contentSubTabReductions2').down('p', 0).hide();
		$('widget-5').down('div#contentOngletMesReductions').down('div.contentSubTabReductions2').down('p', 1).hide();
	}
	else
	{
		$('widget-5').down('div#contentOngletMesReductions').down('div.contentSubTabReductions2').down('p', 0).show();
		$('widget-5').down('div#contentOngletMesReductions').down('div.contentSubTabReductions2').down('p', 1).show();
	}
}

/**
 * Mise à jour du caroussel des bons de réductions
 */
function updateSliderWidget5()
{
	var slider = $('widget-5').down('div#contentOngletMesReductions').down('div.slider');
	
	if (panierOn)
	{
		tabBonsReduction = panierBonsReduction; 
	}
	else
	{
		tabBonsReduction = bonsReduction;
	}
	
	if ((bonsReduction.size() > 0) || ((panierBonsReduction.size() > 0)  && panierOn))
	{
		if (tabBonsReduction.size() > 0)
		{
			html = '  <div class="blocSliderProduit clear">';
			if (tabBonsReduction.size() > 3)
			{
				html += '    <a title="Précédent" class="sliderPrec" href="#"></a>';
			}
			html += '    <div class="masqueProduit">';
			html += '      <div class="sliderProduit" id="sliderBonsReduction">';
			
			tabBonsReduction.each( function(data, key)
			{
				if (panierOn)
				{
					html += '<div class="blocItem">';
					html += '  <a href="#" class="showDetailBonReduction'+key+'" onclick="showDetailBonReductionWidget5('+key+'); return false;">'+data.montant+'&euro;<br /><img alt="'+data.marque+'" src="'+data.image_produit_mini+'"/></a>';
					html += '  <div class="options">';
					html += '    <a href="#" onclick="removeBonReductionFromCartWidget5('+data.id+');" class="supprimerReduction'+data.id+'">Supprimer</a>';
					html += '    <a href="#" onclick="showDetailBonReductionWidget5('+key+');">Voir le détail</a>';
					html += '  </div>';
					html += '</div>';
				}
				else
				{
					html += '<a href="#" class="showDetailBonReduction'+key+'" onclick="showDetailBonReductionWidget5('+key+'); return false;">'+data.montant+'&euro;<br /><img alt="'+data.marque+'" src="'+data.image_produit_mini+'"/></a>';
				}
			});
			
			html += '      </div>';
			html += '    </div>';
			if (tabBonsReduction.size() > 3)
			{
				html += '    <a title="Suivant" class="sliderSuiv" href="#"></a>';
			}
			html += '  </div>';
			
			$(slider).update(html);
			
			if (tabBonsReduction.size() > 3)
			{
				initSliderProduits('sliderBonsReduction');
			}
		}
		else
		{
			$(slider).update('');
		}
	}
	else
	{
		if (panierBonsReduction.size() == 0)
		{
			$('widget-5').down('div.contentSubTabReductions1').update('');
		}
		
		html = "<p>Aucun bon de réduction à imprimer n'est disponible actuellement pour votre magasin "+jsonWidget5.enseigne+".</p>";
		$(slider).update(html);
	}
	
	if (!panierOn && (bonsReduction.size() > 0))
	{
		showDetailBonReductionWidget5(0);
	}
}

/**
 * Affichage du détail d'un bon de réduction
 */
function showDetailBonReductionWidget5(id)
{
	var current;
	if (current = $('widget-5').down('div#contentOngletMesReductions').down('div.slider').down('.current'))
	{
		$('widget-5').down('div#contentOngletMesReductions').down('div.slider').down('.current').removeClassName('current');
	}
	$('widget-5').down('div#contentOngletMesReductions').down('div.slider').down('.showDetailBonReduction'+id).addClassName('current');
	
	if (panierOn)
	{
		var tabBonsReduction = panierBonsReduction;
	}
	else
	{
		var tabBonsReduction = bonsReduction;
	}
	
	currentDetailReduction = tabBonsReduction[id].id;
	
	html = '<table><tr><td>';
    html += '<img alt="'+tabBonsReduction[id].marque+'" src="'+tabBonsReduction[id].image_produit+'"/>';
    html += '</td><td>&nbsp;&nbsp;<td>';
    html += '</td><td>';
    html += '<p>Bénéficiez d\'une réduction de <strong class="important prix">'+tabBonsReduction[id].montant+'€</strong> sur ce produit <strong class="important">'+tabBonsReduction[id].marque+'</strong><br />';
    html += 'Bon de réduction valable jusqu\'au <strong class="important">'+tabBonsReduction[id].date_fin_validite+'</strong></p>';
	
	if (!panierOn)
	{
		html += '<p class="lienFleche"><a href="/bons-reduction/'+tabBonsReduction[id].id+'/reduction-'+tabBonsReduction[id].marque_slug+'.pdf" target="_blank">Imprimer votre coupon de réduction</a></p>';
		html += '<p class="lienFleche"><a href="#" onclick="addBonReductionToCartWidget5('+tabBonsReduction[id].id+'); return false;">Enregistrer pour imprimer plus tard</a></p>';
	}
	
	html += '</td></tr><table>';
	
	$('widget-5').down('div.blocContentWidget').down('div#contentOngletMesReductions').down('div.detailBonReduction').update(html);
	
	return false;
}

/**
 * Changement d'onglet
 */
function changeTabWidget5(tabName)
{
	$('magasinOnglets').addClassName(tabName+'On');
	if (tabName == 'ongletMonMagasin')
	{
		$('magasinOnglets').removeClassName('ongletMesReductionsOn');
		$('contentOngletMesReductions').hide();
		$('contentOngletMonMagasin').show();
	}
	else
	{
		$('magasinOnglets').removeClassName('ongletMonMagasinOn');
		$('contentOngletMesReductions').show();
		$('contentOngletMonMagasin').hide();
	}
	return false;
}


/* -------------------- Widget 6 : Catalogue cadeaux smiles -------------------- */


//chargement du widget
function loadWidget6()
{
	new Ajax.Request('/widgets/getWidgetData',
	{
		method: 'post',
		postBody: 'id=6',
		onSuccess: function(transport, json)
		{
			if (json.authenticated == 'true')
		    {
				if (json.solde_points >= 0)
				{
					$('widget-6').down('div.blocContentWidget').down('p', 0).update("Mon solde de points :");
					$('widget-6').down('div.blocContentWidget').down('p', 1).update(json.solde_points+" S'Miles");
					$('widget-6').down('div.blocContentWidget').down('a', 0).href = json.url_espace_carte_smiles;
				}
				else
				{
					$('widget-6').down('div.blocContentWidget').down('p', 0).update("<strong>Vous devez saisir votre</strong>");
					$('widget-6').down('div.blocContentWidget').down('p', 1).update("numéro de carte");
					$('widget-6').down('div.blocContentWidget').down('p', 2).update("Pour consulter votre solde de points S'Miles, vous devez saisir votre num&eacute;ro de carte sur <a href=\"/mon-profil.html\">votre Profil Casino.fr</a>.");
					$('widget-6').down('div.blocContentWidget').down('p', 3).update('<a href="/mon-profil.html">Editer mon profil</a>');
				}
		    }
		    else
		    {
		    	html = '<p class="textCenter"><img src="/images/carte_casino_smiles.jpg" alt=""><p>';
		    	html += '<p>Pour <strong>consulter votre solde de points S\'Miles</strong>, vous devez <a href="/creer-espace-personnel-casino.html" class="bold">vous inscrire sur Casino.fr</a> et renseigner votre numéro de carte.</p>';
		    	html += '<p class="lienFlecheRose"><a href="/creer-espace-personnel-casino.html">Créer mon profil</a></p>';
		    	$('widget-6').down('div.blocContentWidget').update(html);
		    }
		},
		onFailure: function(){alert("Un problème est survenu lors de la mise à jour du widget \"Mon compte S'Miles\".")}
	});
}


/* -------------------- Widget 7 : Casino recrute ! -------------------- */


//initialisation de l'objet WidgetParams
var paramsWidget7;

//initialisation du widget
function initWidget7()
{
	paramsWidget7 = new WidgetParams();
	
	new Ajax.Request('/widgets/getWidgetParams',
	{
		method: 'post',
		postBody: 'id=7',
		onSuccess: function(transport, json)
		{
			if (json)
				paramsWidget7.AddParams(json);
			else
				paramsWidget7.AddParam('nbTitlesWidget7', 3);
			
			$('nbTitlesWidget7').selectedIndex = paramsWidget7.GetValue('nbTitlesWidget7')-1;

			loadWidget7();
		},
		onFailure: function(){alert("Un problème est survenu lors de la réception des paramètres du widget \"Casino recrute !\".");}
	});
}

//chargement du widget
function loadWidget7()
{
	new Ajax.Request('/widgets/getWidgetData',
	{
		method: 'post',
		postBody: 'id=7&params='+paramsWidget7.RenderJSON(),
		onSuccess: function(transport, json)
		{		
			var html = '';
			var nbTitles = $F('nbTitlesWidget7');
			if (nbTitles > json.length) nbTitles = json.length;
			
			for (i=0;i<nbTitles;i++)
			{	
				html += '<p class="offre"><span>'+json[i]['pubDate']+'</span> <a href="'+json[i]['link']+'">'+json[i]['title']+'</a></p>';
			}
			html += '<p class="lienFlecheRose textRight"><a href="http://www.groupe-casino.fr/fr/Toutes-les-offres,706.html">Toutes les offres</a></p>';
			$('widget-7').down('div.blocContentWidget').update(html);
		},
		onFailure: function(){alert("Un problème est survenu lors de la mise à jour du widget \"Casino recrute !\".")}
	});
}


/* -------------------- Widget 8 : Communiqués de presse -------------------- */


//initialisation de l'objet WidgetParams
var paramsWidget8;

//initialisation du widget
function initWidget8()
{
	paramsWidget8 = new WidgetParams();
	
	new Ajax.Request('/widgets/getWidgetParams',
	{
		method: 'post',
		postBody: 'id=8',
		onSuccess: function(transport, json)
		{
			if (json)
				paramsWidget8.AddParams(json);
			else
				paramsWidget8.AddParam('nbTitlesWidget8', 3);
				
			$('nbTitlesWidget8').selectedIndex = paramsWidget8.GetValue('nbTitlesWidget8')-1;

			loadWidget8();
		},
		onFailure: function(){alert("Un problème est survenu lors de la réception des paramètres du widget \"Communiqués de presse\".");}
	});
}

//chargement du widget
function loadWidget8()
{
	new Ajax.Request('/widgets/getWidgetData',
	{
		method: 'post',
		postBody: 'id=8&params='+paramsWidget8.RenderJSON(),
		onSuccess: function(transport, json)
		{	
			var html = '';
			var nbTitles = $F('nbTitlesWidget8');
			if (nbTitles > json.length) nbTitles = json.length;
			
			for (i=0;i<nbTitles;i++)
				html += '<p class="offre"><span>'+json[i]['pubDate']+'</span> <a href="'+json[i]['link']+'">'+json[i]['title']+'</a></p>';
			html += '<p class="lienFlecheRose textRight"><a href="http://www.groupe-casino.fr/fr/Tous-les-communiques.html">Tous nos communiqués</a></p>';
			$('widget-8').down('div.blocContentWidget').update(html);
		},
		onFailure: function(){alert("Un problème est survenu lors de la mise à jour du widget \"Communiqués de presse\".")}
	});
}


/******************************************************************************
 *
 *  WIDGET 9 : COACHING NUTRITION
 *
 ******************************************************************************/


var themesWidget9;
var currentThemeWidget9 = 'fruits';
var quizWidget9;
var bilanQuizWidget9;
var coachingsWidget9 = new Array();
var loadingWidget9 = '<div class="textCenter" style="margin: 10px;"><img alt="" src="/images/widget-loader-rose.gif"/></div>';

//chargement du widget
function loadWidget9()
{
  // loader
  $('widget-9').down('div.blocContentWidget').down('div.content').update(loadingWidget9);
  
	new Ajax.Request('/widgets/getWidgetData',
	{
		method: 'post',
		postBody: 'id=9&text=1',
		onSuccess: function(transport)
		{
      json = transport.responseText.evalJSON();

			themesWidget9 = json.themes;

      if (json.coachings)
      {
        coachingsWidget9 = json.coachings;
      }

      if (json.bilan)
      {
        bilanQuizWidget9 = json.bilan;
        currentThemeWidget9 = bilanQuizWidget9['theme']['slug'];
        showBilanQuizWidget9();
      }
      else
      {
        showIntroWidget9(currentThemeWidget9);
      }
      
      // evenements click sur les themes du menu
      jQuery('#widget-9 div.blocContentWidget div.menu a').click( function(){
        var href = $(this).href;
        showIntroWidget9(href.substr(href.lastIndexOf('#')+1));
        return false;
      });

		},
		onFailure: function(){alert("Un problème est survenu lors de la mise à jour du widget \"Coaching Nutrition\".")}
	});
}

/**
 * Affichage de l'intro correspondant au thème
 */
function showIntroWidget9(themeSlug)
{
  currentThemeWidget9 = themeSlug;

  // modification du menu
  jQuery('#widget-9 div.blocContentWidget div.menu a.current').removeClass('current');
  jQuery('#widget-9 div.blocContentWidget div.menu a.'+currentThemeWidget9).addClass('current');

  //suppression des paragraphes
  jQuery('#widget-9 div.blocContentWidget p').remove();
  jQuery('#widget-9 div.blocContentWidget .coachingIntro').remove();
  jQuery('#widget-9 div.blocContentWidget .coachingTexte').remove();


  if (coachingsWidget9[currentThemeWidget9])
  {
    return showCoachingWidget9();
  }

  // intro widget
  var html = '<p class="bold">Nutrition, Casino vous accompagne</p>';
  html += '<p>Avec nos coachings ciblés selon vos besoins, vous découvrirez rapidement combien manger équilibré au quotidien, c\'est finalement facile !</p>';
  html += '<p class="bold"><img src="/images/picto-fleche-vert-on.png" alt=""/>&nbsp;&nbsp;Choisissez un thème !</p>';
  $('widget-9').down('div.blocContentWidget').down('div.menu').insert({'before': html});
  
  // intro theme
  html = '<h4><img src="/images/wg-nutrition/'+themesWidget9[currentThemeWidget9]['image']+'.png" alt="'+themesWidget9[currentThemeWidget9]['libelle']+'" /></h4>';
  html += '<p class="grand">Vous souhaitez en savoir plus sur le thème <strong>'+themesWidget9[currentThemeWidget9]['libelle']+'</strong> ?</p>';
  html += '<p>Pas de problème ! Inscrivez-vous vite à notre <strong>coaching personnalisé entièrement gratuit</strong> !<br />Pour que nos conseils soient bien adaptés à vos besoins, vous devez nous éclairer sur vos habitudes alimentaires en ce domaine. C\'est simple et rapide. Vous avez juste à répondre à 5 questions.</p>';
  $('widget-9').down('div.blocContentWidget').down('div.content').update(html).insert({'after': '<p class="lienFleche startQuiz"><a href="#"><strong>Faire le quizz !</strong></a></p>'});

  // evenement
  jQuery('#widget-9 div.blocContentWidget .startQuiz').click( function(){startQuizWidget9();return false;});
}

/**
 * Lancement du Quiz
 */
function startQuizWidget9()
{
  // suppression éléments
  jQuery('#widget-9 div.blocContentWidget p').remove();

  // loader
  $('widget-9').down('div.blocContentWidget').down('div.content').update(loadingWidget9);

  // recup questions/reponses ajax
  new Ajax.Request('/widgets/getWidgetData',
	{
		method: 'post',
		postBody: 'id=9&type=quiz&theme='+currentThemeWidget9,
		onSuccess: function(transport, json)
		{
			quizWidget9 = json;
      showQuestionsQuizWidget9();
    },
		onFailure: function(){alert("Un problème est survenu lors du téléchargement du Quizz \""+themesWidget9[currentThemeWidget9]['libelle']+"\" du widget \"Coaching Nutrition\".")}
  });
}

/**
 * Affichage des questions/réponses
 */
function showQuestionsQuizWidget9()
{
  var html = '<h4><img src="/images/wg-nutrition/'+themesWidget9[currentThemeWidget9]['image']+'-quizz.png" alt="'+themesWidget9[currentThemeWidget9]['libelle']+'" /></h4>';
  html += '<form method="post" action="" id="quiz">';
  quizWidget9['questions'].each(function(question, questionKey)
	{
    html += '<div id="Q'+question['id']+'" class="blocQuiz">';
    html += '  <p class="grand">';
    html += '    <strong>Question '+(questionKey+1)+'/5</strong><br />';
    html += '    <em>'+question['libelle']+'</em>';
    html += '  </p>';
    quizWidget9['reponses'][question['id']].each(function(reponse, reponseKey)
    {
      html += '  <p class="question"><input type="radio" name="reponses['+question['id']+']" id="Q'+question['id']+'R'+reponseKey+'" class="case" value="'+reponse['id']+'" /> <label for="Q'+question['id']+'R'+reponseKey+'">'+reponse['libelle']+'</label></p>';
    });
    html += '  <p class="clear"><br /></p>';
    if (questionKey < 4)
    {
      html += '  <p class="lienFleche JShidden"><a href="#" class="1"><strong>Valider et passer à la question suivante</strong></a></p>';
    }
    else
    {
      html += '  <p class="lienFleche btEnvoiQuiz"><a href="#"><strong>Valider le quiz</strong></a></p>';
    }
    html += '</div>';
  });
  html += '</form>';
  $('widget-9').down('div.blocContentWidget').down('div.content').update(html);
  jQuery('#widget-9 div.blocContentWidget div.content .btEnvoiQuiz a').click( function(){sendResultsQuizWidget9();return false;});
  initQuizz();
}

/**
 * Envoi des résultats du quiz
 */
function sendResultsQuizWidget9()
{
  var formSerialized = jQuery('#widget-9 div.blocContentWidget div.content form').serialize();
  
  // loader
  $('widget-9').down('div.blocContentWidget').down('div.content').update(loadingWidget9);
  
  new Ajax.Request('/widgets/getWidgetData',
	{
		method: 'post',
		postBody: 'id=9&type=bilan&'+formSerialized,
		onSuccess: function(transport, json)
		{
      if (json)
      {
        bilanQuizWidget9 = json;
        showBilanQuizWidget9();
      }
      else
      {
        alert('Vous n\'avez pas rempli le quiz correctement.');
        startQuizWidget9();
      }
    },
		onFailure: function(){alert("Un problème est survenu lors de l'envoi des résultats du Quizz \""+themesWidget9[currentThemeWidget9]['libelle']+"\" du widget \"Coaching Nutrition\".")}
  });
}

/**
 * Affichage du bilan du quiz
 */
function showBilanQuizWidget9()
{
  jQuery('#widget-9 div.blocContentWidget .startQuiz').remove();
  
  var html = '<h4><img src="/images/wg-nutrition/'+themesWidget9[currentThemeWidget9]['image']+'-quizz.png" alt="'+themesWidget9[currentThemeWidget9]['libelle']+'" /></h4>';
  html += '<p><strong class="grand">Résutat '+bilanQuizWidget9['theme']['libelle']+' : '+bilanQuizWidget9['profil']['libelle']+'</strong><br />'+bilanQuizWidget9['bilan']+'</p>';
  $('widget-9').down('div.blocContentWidget').down('div.content').update(html);
  
  if (bilanQuizWidget9['authenticated'] == 'true')
  {
    $('widget-9').down('div.blocContentWidget').down('div.content').insert({'after': '<p class="lienFleche btInscriptionCoaching"><a href="#"><strong>S\'inscrire au coaching !</strong> (entièrement gratuit)</a></p>'});
    jQuery('#widget-9 div.blocContentWidget .btInscriptionCoaching a').click( function(){subscribeToCoachingWidget9();return false;} );
  }
  else
  {
    html = '<p class="grand vert">Pour suivre le coaching vous devez être inscrit sur Casino.fr (inscription entièrement gratuite)</p>';
    html += '<p class="lienFleche"><a href="/creer-espace-personnel-casino.html"><strong>Créer un compte Casino.fr</strong></a></p>';
    $('widget-9').down('div.blocContentWidget').down('div.content').insert({'after': html});
  }
  
}

/**
 * Inscription au coaching
 */
function subscribeToCoachingWidget9()
{
  // suppression paragraphes
  jQuery('#widget-9 div.blocContentWidget p').remove();

  // loader
  $('widget-9').down('div.blocContentWidget').down('div.content').update(loadingWidget9);

  new Ajax.Request('/widgets/getWidgetData',
	{
		method: 'post',
		postBody: 'id=9&type=subscribe&theme='+bilanQuizWidget9['theme']['slug']+'&profil='+bilanQuizWidget9['profil']['slug']+'&text=1',
		onSuccess: function(transport)
		{
      json = transport.responseText.evalJSON();
      
      if (json.coachings)
      {
        coachingsWidget9 = json.coachings;

        var html = '<h4><img src="/images/wg-nutrition/'+themesWidget9[currentThemeWidget9]['image']+'-coaching.png" alt="'+themesWidget9[currentThemeWidget9]['libelle']+'" /></h4>';
        html += '<p>Votre inscription au coaching '+bilanQuizWidget9['theme']['libelle']+' a bien été prise en compte. Dès à présent vous pouvez trouver les derniers conseils de Casino.fr dans votre widget coaching.</p>';
        html += '<p class="grand">N\'hésitez pas à faire les tests et à vous inscrire aux coachings pour nos autres thèmes.</p>';
        $('widget-9').down('div.blocContentWidget').down('div.content').update(html);

        html = '<p class="lienFleche btVoirCoaching"><a href="#"><strong>Découvrir les premiers conseils</strong></a></p>';
        if ($H(coachingsWidget9).size() < 6)
        {
          html += '<p class="lienFleche btNextQuizz"><a href="#"><strong>Accéder au test suivant</strong></a></p>';
        }
        $('widget-9').down('div.blocContentWidget').down('div.content').insert({'after': html});

        jQuery('#widget-9 div.blocContentWidget .btVoirCoaching a').click( function(){showIntroWidget9(currentThemeWidget9);return false;} );
        jQuery('#widget-9 div.blocContentWidget .btNextQuizz a').click( function(){nextQuizzWidget9();return false;} );
      }
      else
      {
        alert("Impossible de finaliser votre inscription au coaching \""+bilanQuizWidget9['theme']['libelle']+"\".");
        showIntroWidget9(bilanQuizWidget9['theme']['slug']);
      }
    },
		onFailure: function(){alert("Un problème est survenu lors de l'envoi des résultats du Quizz \""+themesWidget9[currentThemeWidget9]['libelle']+"\" du widget \"Coaching Nutrition\".")}
  });
}

/**
 * Affichage d'un coaching
 */
function showCoachingWidget9()
{
  var length = coachingsWidget9[currentThemeWidget9].length;

  $('widget-9').down('div.blocContentWidget').down('div.content').update('<h4><img src="/images/wg-nutrition/'+themesWidget9[currentThemeWidget9]['image']+'-coaching.png" alt="'+themesWidget9[currentThemeWidget9]['libelle']+'" /></h4>');

  for(i = 0; i < length; i++)
  {
    html = '<p class="titreCoaching"><a href="#'+i+'">Mon coaching : semaine '+coachingsWidget9[currentThemeWidget9][i]['niveau']+'</a></p>';
    html += '<div class="coachingIntro'+i+' coachingIntro content" style="display: none;">';
    html += coachingsWidget9[currentThemeWidget9][i]['intro'];
    html += '<p class="grand">N\'hésitez pas à faire les tests et à vous inscrire aux coachings pour nos autres thèmes.</p>';
    html += '</div>';
    html += '<div class="coachingTexte'+i+' coachingTexte" style="display: none;">';
    html += coachingsWidget9[currentThemeWidget9][i]['texte'];
    html += '</div>';
    $('widget-9').down('div.blocContentWidget').insert({'bottom': html});
  }

  if (length < 6)
  {
    jQuery('#widget-9 div.blocContentWidget div.coachingIntro0').show();
    jQuery('#widget-9 div.blocContentWidget div.coachingTexte0').show();
  }

  jQuery('#widget-9 div.blocContentWidget p.titreCoaching a').click(function()
  {
    var lastIndex = jQuery(this).attr('href').lastIndexOf('#');
    var coachingToShow = jQuery(this).attr('href').substring(lastIndex+1);
    var showCoaching = !jQuery('#widget-9 div.blocContentWidget div.coachingIntro'+coachingToShow).is(':visible');
    
    jQuery('#widget-9 div.blocContentWidget div.coachingIntro').hide();
    jQuery('#widget-9 div.blocContentWidget div.coachingTexte').hide();
    if (showCoaching)
    {
      jQuery('#widget-9 div.blocContentWidget div.coachingIntro'+coachingToShow).show();
      jQuery('#widget-9 div.blocContentWidget div.coachingTexte'+coachingToShow).show();
    }
  });

  initCoach();
}

/**
 * Faire le quizz suivant
 */
function nextQuizzWidget9()
{
  for (themeSlug in themesWidget9)
  {
    if (!coachingsWidget9[themeSlug])
    {
      showIntroWidget9(themeSlug);
    }
  }
}