var editMode      = false;
var isCurrentUser = false;
//*************************************************//
//*************************************************//
Event.observe(window, 'load', function() {
		
	if($('concours_logged_in')) {
		concoursLoggedIn();
	}

	if($('questionnaire_end')) {
		new Ajax.Request('/vodkaster/questionnaire_end', {
  							onSuccess	: 	function(transport) {
												$('questionnaire_end_loader').hide();
                                                $('questionnaire_end').update(transport.responseText);
                                                $('questionnaire_end').show();
						 						new Effect.Opacity('questionnaire_end', { from: 0, to: 1, duration: 2.0 });
												
                                               	updateRateUser();

                                               $$('.bookmark_button').each(function(i) {
                                                       var extraitNodeID = i.readAttribute('id').sub('selection_', '').sub('bookmark_', '');
                                                       var bookmark_type = i.hasClassName('large') ? 'bookmark_large' : (i.hasClassName('quiz') ? 'bookmark_quiz' : 'bookmark');
                                                       var url = '/layout/set/empty/content/view/attribute/' + extraitNodeID + '/(type)/' + bookmark_type;
                                                       new Ajax.Request(url, { onSuccess: function(transport) {
                                                               i.update(transport.responseText);
                                                               var elemID = i.down('img').identify();
                                                               // Get actual dom element
                                                               var e = $(elemID);
                                                               var src = e.readAttribute('src');
                                                               // Check if the item is selected
                                                               if(e.hasClassName('selected'))
                                                               {
                                                                       e.writeAttribute('src', src.sub('.png', '_on.png'));
                                                               }
                                                               else
                                                               {
                                                					e.observe('mouseover', function() {this.writeAttribute('src', src.sub('.png', '_hover.png'));});
                                                                    e.observe('mouseout', function() {this.writeAttribute('src', src.sub('_on.png', '.png'));});
																	e.observe('click', function() {addBookmark(extraitNodeID, elemID);});
                                                               }
                                                          }
                                                 });
                                               });

											   	$$('.hoverButton').each(function(i) {

													var src = i.readAttribute('src');

													i.observe('mouseover', function() {
														this.writeAttribute('src', src.sub('.png', '_hover.png'));
													});

													i.observe('mouseout', function() {
														this.writeAttribute('src', src.sub('_on.png', '.png'));
													});
												});
												
												$$('.watch-rating-div').each(function(j) {
													var childElements = j.childElements();
													
													j.observe('mouseover', function() {
														childElements[0].hide();
														childElements[1].show();
													});
													
													j.observe('mouseout', function() {
														childElements[0].show();
														childElements[1].hide();
													});
												});

						 			  		}
						});
	}
	
	if($('javascript_redirect')) {
		url = $('javascript_redirect').readAttribute('url');
		document.location.href = url ;		
	}
	
	// put synopsis
	if($('editSynopsis')) {
		new Ajax.Request('/vodkaster/get', {
  							parameters	: 	{contentObjectID: contentObjectID, attributeIdentifier: 'synopsis'},
						 	onSuccess	: 	function(transport) {
						 						if(transport.responseText != "")
						 							$('editSynopsis').update(transport.responseText);
						 						$('editSynopsis').show();
						 			  		}
						});
	}
	
	// put biography
	if($('editBiographie')) {
		new Ajax.Request('/vodkaster/get', {
  							parameters	: 	{contentObjectID: contentObjectID, attributeIdentifier: 'biographie'},
						 	onSuccess	: 	function(transport) {
						 						if(transport.responseText != "")
						 							$('editBiographie').update(transport.responseText);
						 						$('editBiographie').show();
						 			  		}
						});
	}
	
	// put wiki links
	$$('.wiki-link').each(function(i) {
  		url = i.readAttribute('url');
  		label = i.readAttribute('label');
  		i.insert('<a href="' + url + '" target="_blank">' + label + '</a>');
	});
	
	// refresh quiz leaderboard on quiz completion
	if($('end_quiz')) {
  		fetchQuizTop();
	}
	
	if($('quiz_all')) {
  		fetchQuizTop();
	}
	
	// empties extract name on extract creation
	$$('.ezcca-extrait_nom').each(function(i) {
  		i.value = "";
		i.select();
	});

	// focus on search box in search page
	if($('newSearchBox')) {
		$('newSearchBox').focus();
	}
	
	// get Fans of the movie
	if($('fans_film')) {
		fetchFansFilm();
	}
	
	//get playlist extrait list
	if($('playlist_extrait')) {
		fetchPlaylistsExtrait();
	}
	
	// get fans of the clip
	$$('.fans_extrait').each(function(i) {
		limit   = i.readAttribute('limit');
		node_id = i.readAttribute('id').split(' ').first().split('_').first();
		display = i.readAttribute('display');
		fetchFansExtrait(node_id,limit,display);
	});
	
	// get fans of the artist (left block and tab display)
	$$('.fans_artiste').each(function(i) {
		limit   = i.readAttribute('limit');
		node_id = i.readAttribute('id').split(' ').first().split('_').first();
		display = i.readAttribute('display'); // display the block fans ?
		if (display != 0) display = 1;
		fetchFansArtiste(node_id,limit,display);
	});
	
	// get fans of the artist (full list)
	$$('.fans_artiste_full').each(function(i) {
		$('tab_fans_artiste').show();
		limit   = i.readAttribute('limit');
		offset   = i.readAttribute('offset');
		node_id = i.readAttribute('id').split(' ').first().split('_').first();
		fetchFansArtisteFull(node_id,limit,offset);
	});
	
	// get fans of the film (full list)
	$$('.fans_film_full').each(function(i) {
		$('tab_fans_film').show();
		limit   = i.readAttribute('limit');
		offset   = i.readAttribute('offset');
		fetchFansFilmFull(contentObjectID,limit,offset);
	});
	
	$$('.moviemix_bookmark_button').each(function(i) {
		var moviemixNodeID = i.readAttribute('id').sub('bookmark_', '');
		var url = '/layout/set/empty/content/view/attribute/' + moviemixNodeID;
		
		new Ajax.Request(url, { onSuccess: function(transport) {
							i.update(transport.responseText);
							var elemID = i.down('img').identify();
							var e = $(elemID);
							var src = e.readAttribute('src');
							if(e.hasClassName('selected'))
							{
								e.writeAttribute('src', src.sub('.png', '_ok.png'));
							}
							else
							{
								e.observe('mouseover', function() {
									this.writeAttribute('src', src.sub('.png', '_hover.png'));
								});

								e.observe('mouseout', function() {
									this.writeAttribute('src', src.sub('_on.png', '.png'));
								});

								e.observe('click', function() {
									addMoviemixBookmark(moviemixNodeID, elemID);
								});
							}
						   }
				      });

	});

	$$('.moviemix_votes').each(function(i) {
		var moviemixNodeID = i.readAttribute('id').sub('moviemix_', '');
		var url = '/vodkaster/moviemix/nb_vote/' + moviemixNodeID;
		new Ajax.Request(url, { onSuccess: function(transport) {
						i.update(transport.responseText);
									}
			 });
	});
	
	if($('permalink')) {
		$('permalink').observe('click', function(event) {
			$('permalink').select();
		});
	}
	
	if($('moviemix_redirect')) {
		newMovieMix();
	}
	
	if($('top_moviemix')) {
		fetchMovieMixTop();
	}
		
	$$('.artiste_bookmark_button').each(function(i) {
		var artisteNodeID = i.readAttribute('id').sub('bookmark_', '');
		var url = '/layout/set/empty/content/view/attribute/' + artisteNodeID + '/(type)/bookmark';
		
		new Ajax.Request(url, { onSuccess: function(transport) {
							
							i.update(transport.responseText);
							
							var elemID = i.down('img').identify();
							var e = $(elemID);
							
							var src = e.readAttribute('src');
							
							if(e.hasClassName('selected'))
							{
							
								e.writeAttribute('src', src.sub('.png', '_ok.png'));
							
							}
							else
							{
							
								e.observe('mouseover', function() {
									this.writeAttribute('src', src.sub('.png', '_hover.png'));
								});

								e.observe('mouseout', function() {
									this.writeAttribute('src', src.sub('_on.png', '.png'));
								});

								e.observe('click', function() {
									addArtisteBookmark(artisteNodeID, '');
								});
							
							}
							
						   }
						   
				      });
			
	});
	
	if($('first_view_extrait_top')) {

		suscribeNotificationExtrait();
		
		if(navigator.appName != 'Microsoft Internet Explorer') {
			shareExtract(1);
		}
	}
	
	// set focus for lost password
	if($('UserEmail')) {
		$('UserEmail').focus();
	}
	
	//*************************************************//
	//      REGISTER MESSAGE WHEN MOUSE OVER RATE      //
	//*************************************************//
	if ($('watch-rating-div')) {
		$('watch-rating-div').observe('mouseover', function() {
			$('rating-stars').hide();
			$('rating-message').show();
		});

		$('watch-rating-div').observe('mouseout', function() {
			$('rating-message').hide();
			$('rating-stars').show();
		});
	}
	//*************************************************//
	//       	MANAGE TOP MENU STATES		   //
	//*************************************************//
	$$('.menu').each(function(i) {

		var src = i.readAttribute('src');

		// Check if the item is selected
		if(i.hasClassName('selected'))
		{
			i.writeAttribute('src', src.sub('.png', '_on.png'));
		}
		else
		{
			i.observe('mouseover', function() {
				this.writeAttribute('src', src.sub('.png', '_hover.png'));
			});

			i.observe('mouseout', function() {
				this.writeAttribute('src', src.sub('_on.png', '.png'));
			});
		}
	});
	//*************************************************//
	//        ALL BUTTON THAT NEED A HOVER STATE       //
	//*************************************************//
	$$('.hoverButton').each(function(i) {

		var src = i.readAttribute('src');

		i.observe('mouseover', function() {
			this.writeAttribute('src', src.sub('.png', '_hover.png'));
		});

		i.observe('mouseout', function() {
			this.writeAttribute('src', src.sub('_on.png', '.png'));
		});
	});
	//*************************************************//
	//        ALL BUTTON THAT NEED A HOVER STATE       //
	//*************************************************//
	$$('.bookmark_button').each(function(i) {

		var extraitNodeID = i.readAttribute('id').sub('selection_', '').sub('bookmark_', '');

		var bookmark_type = i.hasClassName('large') ? 'bookmark_large' : (i.hasClassName('quiz') ? 'bookmark_quiz' : 'bookmark');

		var url = '/layout/set/empty/content/view/attribute/' + extraitNodeID + '/(type)/' + bookmark_type;

		new Ajax.Request(url, { onSuccess: function(transport) {

			i.update(transport.responseText);

			// Identify div.bookmark children
			var elemID = i.down('img').identify();

			// Get actual dom element
			var e = $(elemID);

			var src = e.readAttribute('src');

			// Check if the item is selected
			if(e.hasClassName('selected'))
			{
				e.writeAttribute('src', src.sub('.png', '_on.png'));
			}
			else
			{
				e.observe('mouseover', function() {
					this.writeAttribute('src', src.sub('.png', '_hover.png'));
				});

				e.observe('mouseout', function() {
					this.writeAttribute('src', src.sub('_on.png', '.png'));
				});

				e.observe('click', function() {
					addBookmark(extraitNodeID, elemID);
				});
			}
		   }
      });
	});
	//*************************************************//
	//        ALL BUTTON THAT NEED A HOVER STATE       //
	//*************************************************//
	if(is_logged_in == true)
	{
		updateRateUser();
	}
	//*************************************************//
	//       	IF EDITION FIELD EXISTS		   //
	//*************************************************//
	if(is_logged_in == true)
	{
		$$('.editButton').each(function(i) {
			i.show();
		});
	}
	//*************************************************//
	//       DECLARE AND FIRE LIGHTVIEW ON LOGIN       //
	//*************************************************//
	if($('actors_list'))
	{
		//fetchActorsList();
		//makeSortable();
	}
	//*************************************************//
	//       DECLARE AND FIRE LIGHTVIEW ON LOGIN       //
	//*************************************************//
	if($('playlists_list'))
	{
		fetchPlaylists(0);
	}
	//*************************************************//
	//  IF CURRENT PAGE HAS A BOOKMARK LIST THEN FETCH //
	//*************************************************//
	if($('bookmark_list'))
	{
		fetchBookmarks(0);
	}
	//*************************************************//
	//  IF CURRENT PAGE HAS A FAVORITE MOVIE LIST THEN FETCH //
	//*************************************************//
	if($('favorite_movies_list'))
	{
		fetchFavoriteMovies(0);
	}
	//**********************************************************//
	//           IF FAVORITE ARTISTS PAGE THEN FETCH            //
	//**********************************************************//
	if($('favorite_artists_list'))
	{
		fetchFavoriteArtists(0);
	}
	//*************************************************//
	//       DECLARE AND FIRE LIGHTVIEW ON LOGIN       //
	//*************************************************//
	if($('playlist_list'))
	{
		fetchPlaylist(0);
	}
	//*************************************************//
	//       DECLARE AND FIRE LIGHTVIEW ON LOGIN       //
	//*************************************************//
//	if($('amazon_list'))
//	{
//		fetchAmazonList();
//	}
	//*************************************************//
	//       DECLARE AND FIRE LIGHTVIEW ON LOGIN       //
	//*************************************************//
	if($('fnac_list'))
	{
		fetchFnacList();
	}
	if($('vod_list'))
	{
		fetchVODList();
	}
	//*************************************************//
	//  Homepage : periodical update on notifications  //
	//*************************************************//
	if($('notifications_list'))
	{
		var limit = $('notifications_list').readAttribute('limit');
		var url = '/vodkaster/children/2/notification/' + isCurrentUser + '/false/related/' + limit + '/0/' + 'published,false/false/false';

		new Ajax.PeriodicalUpdater('notifications_list', url,
		{
			method: 'get',
			frequency: 20,
		    decay: 2
		});
	}
	//*************************************************//
	//       DECLARE AND FIRE LIGHTVIEW ON LOGIN       //
	//*************************************************//
	if($('comments_list'))
	{
		fetchComments(0);
	}
	if($('retro_comments_list'))
	{
		fetchRetroComments(0);
	}
	//*************************************************//
	//       DECLARE AND FIRE LIGHTVIEW ON LOGIN       //
	//*************************************************//
	if($('movie_links_header'))
	{
		countExtraitsList();
	}
	//*************************************************//
	//        ALL BUTTON THAT NEED A HOVER STATE       //
	//*************************************************//
	$$('.playlist_form').each(function(i) {

		i.observe('click', function(event) {

			event.stop();

			Lightview.show({
				href: '/layout/set/empty/content/view/user/' + contentNodeID,
				rel: 'ajax',
				options: {
					autosize: true,
					closeButton: false,
					ajax: {
						parameters: $('newPlaylist').serialize(true),
						method: 'post',
						onComplete: function(transport) {
								    $('ajaxSubmit').observe('click', submitAjaxCreate);
									$$('.hoverButton').each(function(i) {

										var src = i.readAttribute('src');

										i.observe('mouseover', function() {
											this.writeAttribute('src', src.sub('.png', '_hover.png'));
										});

										i.observe('mouseout', function() {
											this.writeAttribute('src', src.sub('_on.png', '.png'));
										});
									});
							    },
						onFailure: function( transport ) {
							showLogin();
						}
					}
				}
			});
		});
	});
	//*************************************************//
	//        ALL BUTTON THAT NEED A HOVER STATE       //
	//*************************************************//
	$$('.comment_button').each(function(i) {

		i.observe('click', function(event) {

			// In case error is displayed from a previous action
			$('message_error').hide();

			// Retrieve mandatory fields from class value cooking
			var parentNodeID = i.readAttribute('class').split(' ').last().split('_').last();
			var parentClassIdentifier = i.readAttribute('class').split(' ').last().split('_').first();
			var classIdentifier = 'comment';

			var input_comment = $F('message_' + parentNodeID).replace(/^\s\s*/, '').replace(/\s\s*$/, '');
			
			if(parentClassIdentifier == 'extrait')
				suscribeNotificationExtrait();
			
			if(input_comment != '')
			{
				// Vodkaster custom url used to create content
				var url = '/vodkaster/create/' + classIdentifier + '/' + parentNodeID;
	
				// Request to the module's view
				new Ajax.Request(url, { method: 'post',
							parameters: { message: input_comment},
							onSuccess: function(transport) {
									if(parentClassIdentifier == 'article')
										fetchRetroComments(0);
									else										
										fetchComments(0);
									$('message_' + parentNodeID).clear();
								   },
							onFailure: function(transport) {
									$('message_error').update(transport.responseText).show();
								   }
						      });
			}
		});
	});
	//*************************************************//
	//       DECLARE AND FIRE LIGHTVIEW ON LOGIN       //
	//*************************************************//
	/*
	$$('.add_to_playlist').each(function(i) {

		i.observe('change', function(event) {

			var extraitObjectID = i.readAttribute('name');

			extraitObjectID = extraitObjectID.sub('extrait_', '');

			var url = '/vodkaster/addlocation/' + extraitObjectID + '/' + $F(i.identify());

			new Ajax.Request(url, { onSuccess: function() {
								   fetchPlaylists(0);
							   },
					       onFailure: function() {
							  }
					      });
		});
	});
	*/
	//*************************************************//
	//       DECLARE AND FIRE LIGHTVIEW ON LOGIN       //
	//*************************************************//
	$$('.remove_playlist').each(function(i) {

		i.observe('click', function(event) {

			var url = '/vodkaster/delete/' + contentNodeID;

			new Ajax.Request(url, { onSuccess: function(transport) {
											fetchPlaylists(0);
										},
						onFailure: function() {
								      }
						      });

		});
	});
	//*************************************************//
	//       DECLARE AND FIRE LIGHTVIEW ON LOGIN       //
	//*************************************************//
	if($('create_playlist'))
	{
		$('create_playlist').observe('click', function(event) {
			event.stop();

			Lightview.show({
				href: '/layout/set/empty/content/action',
				rel: 'ajax',
				options: {
					autosize: true,
					closeButton: false,
					ajax: {
						parameters: $('newPlaylist').serialize(true),
						method: 'post',
						onComplete: function(transport) {
								    $('ajaxSubmit').observe('click', submitAjaxCreate);
							    }
					}
				}
			});
		});
	};
	//*************************************************//
	//       DECLARE AND FIRE LIGHTVIEW ON BUG SUBMIT  //
	//*************************************************//
	if($('create_bug'))
	{
		$('create_bug').observe('click', function(event) {

			event.stop();

			if(window.contentNodeID == undefined) {
				contentNodeID = $('create_bug').readAttribute('node_id');
			}

			if(is_logged_in == true)
			{
				Lightview.show({
					href: '/layout/set/empty/content/view/full/16959816/(node_id)/' + contentNodeID,
					rel: 'ajax',
					options: {
						autosize: true,
						closeButton: false,
						ajax: {
							onComplete: function(transport) {
									    $('ajaxSubmit').observe('click', submitAjaxCollect);
								    }
						}
					}
				});
			}
			else
			{
				showLogin();
			}
					
		});
	};
	//*************************************************//
	//             ADD BOOKMARK FUNCTION               //
	//*************************************************//
	if($('taste'))
	{
		//new UI.Ajax.Carousel('taste', { url:'/vodkaster/taste' });
		new UI.Carousel('taste', { direction:'horizontal' });
	}
	//*************************************************//
	//       DECLARE AND FIRE LIGHTVIEW ON LOGIN       //
	//*************************************************//
	if($('percent-view'))
	{
		updateRatingRatio();
	}
	//*************************************************//
	//        GET COMPATIBILITY ON USER PAGE           //
	//*************************************************//
	if($('compatibility-percent-view')) {
	
		var i = $('compatibility-percent-view');
		var current_user_id   = i.readAttribute('current');
		var user_id   = i.readAttribute('user');
		getCompatibility (current_user_id, user_id);
		
	}
	//*************************************************//
	//       DECLARE AND FIRE LIGHTVIEW ON LOGIN       //
	//*************************************************//
	if($('edit_actors'))
	{
		$('edit_actors').observe('click', function() {

			editMode = true;

			this.toggleClassName('on');

			$('actors_form').toggle();

			// Now fetch default actors list
			fetchDefaultActorsList();

			$$('.remove_actor').each(function(i) {
				i.toggle();
			});
		});

		$('actors_search_cancel').observe('click', function() {

			$('actors_search').clear();

			fetchDefaultActorsList();
		});
	}
	//*************************************************//
	//       Toggle keyword list / form                //
	//*************************************************//
	if($('edit_keywords') != undefined)
	{
		$('edit_keywords').observe('click', function() {

			this.toggleClassName('on');

			$('keyword_list').toggle();
			$('keyword_form').toggle();

			// Refetch keyword list via ajax
			loadKeywords();
		});
	}
	//*************************************************//
	//       	MANAGE TOP MENU STATES		   //
	//*************************************************//
	if($('actors_search'))
	{
		$('actors_search').observe('focus', function() {

			$('actors_search').clear();
		});

		new Ajax.Autocompleter("actors_search", "actors_form_list", "/vodkaster/search", {
							 paramName: "value",
							 afterUpdateElement:function(text, li) {
								 updateAttributeRelated('actors', li.readAttribute('id').split('_').last(), 'add');
							 },
							 indicator: "actors_form_loader",
							 frequency: 0.6,
							 minChars: 3,
							 parameters: "&classIdentifiers[]=artiste&attributeIdentifiers[]=nom&attributeIdentifiers[]=prenom&view=ajax&prefix=actorformlist&list_id=actors_scrollable&list_class=scrollable",
							 onShow: function(element, update) {

								 // Position autocompleter list
								 update.writeAttribute({position:false});
								 update.show();

								 // Update the list
								 formatActionFormList();
							 },
							 onHide: function() {
								 return false;
							 }
		 });
	}
	//*************************************************//
	//             ADD BOOKMARK FUNCTION               //
	//*************************************************//
	if($('add_extrait'))
	{
		$('add_extrait').observe('click', function() {

			fetchExtraitsList();

			$('add_extrait').toggleClassName('on');
			$('extraits_form').toggle();

			// Force display of tab 3
			toggleTab(3, 3, false, false);
		});

		$('extraits_search').observe('focus', function() {
			$('extraits_search').clear();

			makeScrollbar('extraits_scrollable', 'extraits_scrollbar', 'extraits_scrollbar_track', 'extraits_scrollbar_handle');
		});

		new Ajax.Autocompleter("extraits_search", "extraits_search_list", "/vodkaster/search", {
							 paramName: "value",
							 afterUpdateElement:function(text, li) {
								 updateAttributeRelated('extraits', li.readAttribute('id').split('_').last(), 'add');
							 },
							 indicator:"extraits_form_loader",
							 frequency: 0.6,
							 minChars: 3,
							 parameters:"&classIdentifiers[]=film&attributeIdentifiers[]=titre&prefix=extraitformlist&list_id=extraits_scrollable&list_class=scrollable",
							 onShow: function(element, update) {

								 // Position elements
								 update.writeAttribute({position:false});
								 update.show();

							 },
							 onHide: function() {
								 return false;
							 }
				     });
	}
	//*************************************************//
	//       	IF EDITION FIELD EXISTS		   //
	//*************************************************//
	if($('editNom') && is_logged_in == true)
	{
		new Ajax.InPlaceEditor('editNom', '/vodkaster/edit', { okControl : false,
									okText : okText,
									cancelText : cancelText,
									savingText : savingText,
									clickToEditText: clickToEditText,
									submitOnBlur: true,
									cancelControl: false,
									highlightcolor: '#EAF3FF',
									highlightendcolor: '#D9D9D9',
									callback: function(form, value) {
										return 'value='+encodeURIComponent(value)+'&contentObjectID='+contentObjectID+'&language='+language+'&attributeIdentifier=nom';
									}
								     });
	}
	if($('editContexte') && is_logged_in == true)
	{
		new Ajax.InPlaceEditor('editContexte', '/vodkaster/edit', { rows: 2,
									    okControl : 'link',
									    okText : okText,
									    cancelText : cancelText,
									    savingText : savingText,
									    clickToEditText: clickToEditText,
									    highlightcolor: '#EAF3FF',
									    highlightendcolor: '#FFFFFF',
									    callback: function(form, value) {
										    return 'value='+encodeURIComponent(value)+'&contentObjectID='+contentObjectID+'&language='+language+'&attributeIdentifier=contexte';
									 }
								       });
		// Start counting words
		//makeItCount('editSynopsis', 300, false);
	}
	/*if($('editBiographie'))
	{
		new Ajax.InPlaceEditor('editBiographie', '/vodkaster/edit', { rows: 2,
											  okControl : 'link',
											  okText : okText,
											  cancelText : cancelText,
											  savingText : savingText,
											  highlightcolor: '#EAF3FF',
											  highlightendcolor: '#FFFFFF',
											  clickToEditText: clickToEditText,
											  callback: function(form, value) {
												  return 'value='+encodeURIComponent(value)+'&contentObjectID='+contentObjectID+'&language='+language+'&attributeIdentifier=biographie';
											  }
										   });
	}
	if($('editSynopsis'))
	{
		new Ajax.InPlaceEditor('editSynopsis', '/vodkaster/edit', { rows: 2,
									    okControl : 'link',
									    okText : okText,
									    cancelText : cancelText,
									    savingText : savingText,
									    highlightcolor: '#EAF3FF',
									    highlightendcolor: '#FFFFFF',
									    clickToEditText: clickToEditText,
									    callback: function(form, value) {
										    return 'value='+encodeURIComponent(value)+'&contentObjectID='+contentObjectID+'&language='+language+'&attributeIdentifier=synopsis';
									    }
									   });
	}*/
	//*************************************************//
	//             PLAYLIST INPLACE EDITION            //
	//*************************************************//
	if($('editPlaylistNom'))
	{
		new Ajax.InPlaceEditor('editPlaylistNom', '/vodkaster/edit', { okControl : false,
										formClassName: 'playlisteditor-form',
										okText : okText,
										cancelText : cancelText,
										savingText : savingText,
										clickToEditText: clickToEditText,
										submitOnBlur: true,
										cancelControl: false,
										highlightcolor: '#333333',
										callback: function(form, value) {
											return 'value='+encodeURIComponent(value)+'&contentObjectID='+contentObjectID+'&language='+language+'&attributeIdentifier=nom';
										}
									     });
	}
	if($('editPlaylistDescription'))
	{
		new Ajax.InPlaceEditor('editPlaylistDescription', '/vodkaster/edit', { rows: 2,
											formClassName: 'playlisteditor-form',
											okControl : 'link',
											okText : okText,
											cancelText : cancelText,
											savingText : savingText,
											highlightcolor: '',
											clickToEditText: clickToEditText,
											callback: function(form, value) {
												return 'value='+encodeURIComponent(value)+'&contentObjectID='+contentObjectID+'&language='+language+'&attributeIdentifier=description';
											}
										     });
	}
	//*************************************************//
	//             ADD YOUTUBE                         //
	//*************************************************//
	$$('#buttonYouTube').each(function(e) {
		e.observe('click',function(i){
			onAddYouTube();
		});
	});
	
	$$('#boxYouTube').each(function(i) {
		i.observe('keypress', function(e) {
			if(e.keyCode == Event.KEY_RETURN) {
				onAddYouTube();
			}
		});
	});
	//**************************************************//
	//       	      Tags Management		            //
	//**************************************************//
	$$('.select_question').each(function(i) {
		i.observe('change', function() {
			$$('.ezkeyword').each(function(e) {
				// find the question that was not hidden before hiding all the others
				var e_style = e.getStyle('display');
				if(e_style != 'none') {
					validateTag(e.identify(), 0);
				}
				e.hide();
			});
			var questionDiv = $F(i);
			$(questionDiv).show();
			// focus on the text area
			var txtArea = $(questionDiv+'_current');
			txtArea.focus();
			// TODO [SAFARI] for some reason, createTextRange returns nothing
			if (txtArea.createTextRange) {
				  var range = txtArea.createTextRange();
				  range.collapse(true);
				  range.moveStart('character', (txtArea.value.length));
				  range.select();
			}
		});
	});

	$$('#keyword_form textarea').each(function(i) {
		i.observe('keypress', function(e) {
			if(e.keyCode == Event.KEY_RETURN) {
				validateTag($(i.identify()).up('.ezkeyword').identify(), 1);
			}
		});
	});

	$$('.next_keyword').each(function(i) {
		i.observe('click', function() {
			$$('.ezkeyword').each(function(e) {
				// find the current question
				var e_style = e.getStyle('display');
				if(e_style != 'none') {
					currentQuestionId = e.identify();
				}
			});
			// validate the question and move to the next
			validateTag(currentQuestionId, 1);
		});
	});
	
	$$('.buttonInfo').each(function(i) {
		i.observe('click', function(event) {
			var shareSrc = $('tabButtonShare').firstDescendant().readAttribute('src');
			if (shareSrc.endsWith('hover.png')) {
				$('tabShare').hide();
				$('tabInfo').show();
				$('tabButtonShare').firstDescendant().writeAttribute('src', shareSrc.sub('_hover.png', '.png'));
				var infoSrc = $('tabButtonInfo').firstDescendant().readAttribute('src');
				$('tabButtonInfo').firstDescendant().writeAttribute('src', infoSrc.sub('.png', '_hover.png'));
			}
		});
	});

	$$('.buttonShare').each(function(i) {
		i.observe('click', function(event) {
			var infoSrc = $('tabButtonInfo').firstDescendant().readAttribute('src');
			if (infoSrc.endsWith('hover.png')) {
				$('tabInfo').hide();
				$('tabShare').show();
				$('tabButtonInfo').firstDescendant().writeAttribute('src', infoSrc.sub('_hover.png', '.png'));
				var shareSrc = $('tabButtonShare').firstDescendant().readAttribute('src');
				$('tabButtonShare').firstDescendant().writeAttribute('src', shareSrc.sub('.png', '_hover.png'));
			}
		});
	});
			
	$('facebookShareExtrait').observe('click', function(event) {
		var current_url = this.getAttribute("current_url");
		var current_title = this.getAttribute("current_title");
		fb_url='http://www.facebook.com/sharer.php?u='+encodeURIComponent(current_url)+'&t='+encodeURIComponent(current_title);
		window.open(fb_url,'sharer','toolbar=0,status=0,width=626,height=436');
		return;
	});

	$('twitterShareExtrait').observe('click', function(event) {
		var movie   = this.getAttribute('movie');
		var current_url = this.getAttribute('url');
		var extrait = this.getAttribute('extrait');
		//var message = extrait+' extrait de '+movie+' : '+vdk_url;
		//tw_url='http://twitter.com/home/?status='+encodeURIComponent(message);
		//window.open(tw_url);
		//return;

		var tw_url = '';
		
		BitlyCB.alertResponse = function(data) {
            var first_result;
            // Results are keyed by longUrl, so we need to grab the first one.
            for(var r in data.results){
                first_result = data.results[r]; 
                break;
            }
            
            var url_bitly = first_result['shortUrl'].toString();
            var message = extrait+' - extrait de '+movie+' : '+url_bitly;
            tw_url='http://twitter.com/home/?status='+encodeURIComponent(message);
            window.open(tw_url);
			return;    
		}
		
		BitlyClient.call('shorten', {'longUrl': current_url}, 'BitlyCB.alertResponse');
		return; 
	});

	$('emailShareExtrait').observe('click', function(event) {
		var current_url = this.getAttribute("current_url");
		var current_title = this.getAttribute("current_title");
		em_url='mailto://?subject='+encodeURIComponent(current_title)+'&body='+encodeURIComponent(current_url);
		window.open(em_url);
		return;
	});
});
//**********************************************************//
//                   Tags Management                        //
//**********************************************************//
//**********************************************************//
// FUNCTION : validateTag 		   		   		            //
// Param 1  : id of the tag  (question_0, question_1 ....)  //
// Param 2 	: boolean => goes to next question or not ?     //
//**********************************************************//
function validateTag(attributeId, bNext)
{
	// if tag is being stored, mov to next question
	if($(attributeId + '_current').disabled == true) {
		if(bNext){
			nextQuestion(attributeId);
		}
		return;
	}
	
	var current_value = $F(attributeId + '_current').replace(/\r|\n|\r\n/g, "");
	var previous_value = $F(attributeId + '_previous');
	
	//console.log("IN validateTag (question : " + attributeId + ") : previous = _" + previous_value + "_ / current = _" + current_value + "_");
	
	// tags have changed, disable text area while value is being stored
	if(current_value != previous_value)
	{
		// disable text and store value in previous
		$(attributeId + '_previous').value = current_value;
		$(attributeId + '_current').value = savingText;
		$(attributeId + '_current').setStyle({color: '#AAAAAA'});
		$(attributeId + '_current').disabled = true;

		new Ajax.Request('/vodkaster/edit', { 	parameters: { contentObjectID: contentObjectID,
								    language: language,
								    attributeIdentifier: attributeId,
								    value: current_value
								  },
												onSuccess: function(transport) {
									  				onTagValidated(attributeId);
									  				
								  				}
						  });
	}
	
	if (bNext){
		nextQuestion(attributeId);
	}
	
}

//**********************************************************//
// FUNCTION : onTagValidated    		   		            //
//**********************************************************//
function onTagValidated(newAttributeId)
{
	var current_value = $F(newAttributeId + '_current').replace(/\r|\n|\r\n/g, "");
	var previous_value = $F(newAttributeId + '_previous');
	//console.log("IN onTagValidated (question : " + newAttributeId + ") : previous = _" + previous_value + "_ / current = _" + current_value + "_");
	
	// OK, value has been stored in DB, put it the box and enable it
	$(newAttributeId+'_current').value = previous_value;
	$(newAttributeId + '_current').setStyle({color: '#008089'});
	$(newAttributeId + '_current').disabled = false;
}

//**********************************************************//
// FUNCTION : nextQuestion       		   		            //
//**********************************************************//
function nextQuestion(attributeId)
{
	// Hide all question forms
	$$('.ezkeyword').invoke('hide');

	// find the next question to show and then show it
	var nextAttributeId;
	if($(attributeId).next('.ezkeyword')) {
		nextAttributeId = $(attributeId).next('.ezkeyword').identify();
	} else 	{
		nextAttributeId = 'question_0';
	}
	$(nextAttributeId).show();

	// select the corresponding item on the drop-down list
	$('select_test').value = nextAttributeId;
	
	// focus on the text area
	var txtArea = $(nextAttributeId+'_current');
	txtArea.focus();
	// TODO [SAFARI] for some reason, createTextRange returns nothing
	if (txtArea.createTextRange) {
		  var range = txtArea.createTextRange();
		  range.collapse(true);
		  range.moveStart('character', (txtArea.value.length));
		  range.select();
	}
}

//**********************************************************//
// FUNCTION : loadKeywords       		   		            //
//**********************************************************//
function loadKeywords() {

	var url = '/layout/set/empty/content/view/attribute/' + contentNodeID + '/(type)/keywords';

	new Ajax.Request(url, { onComplete: function(transport) {
						    $('keyword_list').update(transport.responseText);
					    }
			});
}

//*************************************************//
//		UPDATE ATTRIBUTE FUNCTION          //
//*************************************************//
function onAddYouTube() {
	
	// hide previous error msg, hide OK button & show loader
	$('add_error').hide();
	$('buttonYouTube').hide();
	$('loaderYouTube').show();
	
	// Inputs
	var contentNodeID = $('contentNodeID').getValue();
	var contentObjectID = $('contentObjectID').getValue();
	var YouTubeUrl = $('boxYouTube').getValue();
	
	/* post youtubeURL contentNodeID */
	url = '/vodkaster/add_youtube';

	new Ajax.Request(url,{ encoding: 'UTF-8',
			      parameters: { contentObjectID: contentObjectID,
				      			contentNodeID: contentNodeID,
				      			YouTubeUrl: YouTubeUrl
			      },
			      onSuccess: function(transport) {
					$('add_error').hide();
					var message = transport.getHeader('Message');
					var redirection = transport.getHeader('Redirection');

					window.location.replace(redirection);
			      },
			      onFailure: function(transport) {
					var newerror = transport.getHeader('Error');
					$('add_error').show();
					$('add_error').update(newerror);
					$('loaderYouTube').hide();
					$('buttonYouTube').show();
			      }
	});
}

//*************************************************//
//		UPDATE ATTRIBUTE FUNCTION          //
//*************************************************//
function updateRatingRatio() {

	var i = $('percent-view');
	
	var current_ratio = parseInt(i.innerHTML.sub('%', ''));

	var url = '/layout/set/empty/content/view/attribute/' + contentNodeID;

	new Ajax.Request(url, { onSuccess: function(transport) {

						  var rating_ratio = transport.responseText;

						  if(rating_ratio)
						  {
							  var effect_duration = Math.abs(rating_ratio - current_ratio) * 0.04;
							  new Effect.Tween('percent-view', current_ratio, rating_ratio, { duration: effect_duration }, function(p) { this.update(p.round()+'%') });
						  }
					   }
			      });
}

//*************************************************//
//		    ACTORS FUNCTIONS          	           //
//*************************************************//
function fetchActorsList ()
{
	new Ajax.Request('/vodkaster/related', { parameters: { contentObjectID: contentObjectID,
							       classIdentifier: 'extrait',
							       prefix: 'actorlist',
							       attributeIdentifier: 'interpretes'
							     },
						 onLoading: function() {
								//$('actors_loader').show();

								new Effect.Opacity('actors_list', { from: 1, to: 0.2, duration: 0.2 });
							    },
						 onSuccess: function(transport) {
								$('actors_loader').hide();

								new Effect.Opacity('actors_list', { from: 0.2, to: 1, duration: 0.2 });

								$('actors_list').update( transport.responseText );

								// Make sortable
								makeSortable();

								// Show delete button
								if (editMode)
								{
									$$('.remove_actor').each(function(i) {
										i.show();
									});
								}
							    }
			});
}
// Fetch all actors in the movie
function fetchDefaultActorsList ()
{
	new Ajax.Request('/vodkaster/related', { parameters: { contentObjectID: parentContentObjectID,
							       classIdentifier: 'film',
							       attributeIdentifier: 'casting',
							       prefix: 'actorformlist',
							       list_id: 'actors_scrollable',
							       list_class: 'scrollable',
							       view: 'ajax'
							     },
						onLoading: function() {
							      $('actors_form_loader').show();
							    },
						onSuccess: function(transport) {
							      $('actors_form_loader').hide();

							      $('actors_form_list').update( transport.responseText );

							      makeScrollbar('actors_scrollable', 'actors_scrollbar', 'actors_scrollbar_track', 'actors_scrollbar_handle');
							      // Update the list
							      formatActionFormList();
							}
			});
}

// Remove from default artistes whom are already added
function formatActionFormList()
{
	// Assign the add element function when element is clicked
	$$('#actors_form_list > ul > li').each(function(i) {

		i.observe('click', function() {
			updateAttributeRelated('actors', this.readAttribute('id').split('_').last(), 'add');
		});
	});
	// Remove from the actors form list element already added
	$$('#actors_list > ul > li').each(function(i) {

		var removeObjectID = i.readAttribute('id').sub('actorlist_', 'actorformlist_');

		$( removeObjectID ).remove();
	});
}
//*************************************************//
//		    ACTORS FUNCTIONS          	   //
//*************************************************//
function makeScrollbar(scrollable, scrollbar, scrollbar_track, scrollbar_handle)
{
	// vertical slider control
	var slider = new Control.Slider(scrollbar_handle, scrollbar_track, { axis: 'vertical',
							     onSlide: function(v) { scrollVertical(v, $(scrollable), slider); },
							     onChange: function(v) { scrollVertical(v, $(scrollable), slider); }
							   });

	// disable vertical scrolling if text doesn't overflow the div
	if ($(scrollable).scrollHeight <= $(scrollable).offsetHeight)
	{
		slider.setDisabled();

		//$(scrollbar).hide();
	}
}
// scroll the element vertically based on its width and the slider maximum value
function scrollVertical(value, element, slider)
{
	element.scrollTop = Math.round(value/slider.maximum*(element.scrollHeight-element.offsetHeight));
}
//*************************************************//
//		    ACTORS FUNCTIONS          	   //
//*************************************************//
function fetchNotificationsList ()
{
	//var limit = $('notifications_list').readAttribute('class').split('_').last();
	var limit = 15;
	var offset = 0;
	var url = '/vodkaster/children/2/notification/' + isCurrentUser + '/false/related/' + limit + '/' + offset + '/' + 'published,false/false/false';

	new Ajax.Request(url, { onLoading: function() {
						//$('notifications_loader').show();
						//new Effect.Opacity('notifications_list', { from: 1, to: 0.2, duration: 0.2 });
					    },
				 onSuccess: function(transport) {
						$('notifications_loader').hide();

						$('notifications_buttons').show();

						$('notifications_list').show();

						//new Effect.Opacity('notifications_list', { from: 0.2, to: 1, duration: 0.2 });

						$('notifications_list').update( transport.responseText );
					    }
			});
}
//*************************************************//
//		    ACTORS FUNCTIONS          	   //
//*************************************************//
function fetchComments (offset)
{
	var limit = $('comments_list').readAttribute('class').split('_').last();
	var url = '/vodkaster/children/' + contentMainNodeID + '/comment/' + isCurrentUser + '/comment/ajax/' + limit + '/' + offset + '/published,false/false';

	new Ajax.Request(url, { onLoading: function() {
						new Effect.Opacity('comments_list', { from: 1, to: 0.2, duration: 0.2 });
					    },
				 onSuccess: function(transport) {
						$('comments_loader').hide();

						new Effect.Opacity('comments_list', { from: 0.2, to: 1, duration: 0.2 });

						$('comments_list').update( transport.responseText );

						// Paginate
						PaginateComments();
					    }
			});
}
//*************************************************//
//ACTORS FUNCTIONS          	   //
//*************************************************//
function fetchAmazonList ()
{
	var keyword = $('amazon_list').readAttribute('title');
	
	var url = '/vodkaster/amazon/' + keyword;
	
	new Ajax.Request(url, { onLoading: function() {
				new Effect.Opacity('amazon_list', { from: 1, to: 0.2, duration: 0.2 });
			    },
		 onSuccess: function(transport) {
				$('amazon_loader').hide();
	
				new Effect.Opacity('amazon_list', { from: 0.2, to: 1, duration: 0.2 });
	
				$('amazon_list').update( transport.responseText );
			    }
	});
}
//*************************************************//
//  FUNCTIONS FNAC XML PARTENER              	   //
//*************************************************//
function fetchFnacList ()
{
	var contentobject_id = $('fnac_list').readAttribute('contentobject_id');
	var url = '/vodkaster/fnac/' + contentobject_id;
	new Ajax.Request(url, { onLoading: function() {
				new Effect.Opacity('fnac_list', { from: 1, to: 0.2, duration: 0.2 });
			    },
		 onSuccess: function(transport) {

				if (transport.getHeader('count') > 0) {
					$('get_more_loader').hide();
					$('fnac_list').update( transport.responseText );
					$$('.hoverButton').each(function(i) {
						var src = i.readAttribute('src');
						i.observe('mouseover', function() {
							this.writeAttribute('src', src.sub('.png', '_hover.png'));
						});
						i.observe('mouseout', function() {
							this.writeAttribute('src', src.sub('_on.png', '.png'));
						});
					});
				} else {
					if ($('fnac_vod_no_results').innerHTML==1) {
						$('get_more_loader').hide();
						$('fnac_list').update(transport.responseText);
					}
					else $('fnac_vod_no_results').update(1);
				}
				new Effect.Opacity('fnac_list', { from: 0.2, to: 1, duration: 0.8 });
			}
	});
}

function fetchVODList ()
{
	var node_id = $('vod_list').readAttribute('node_id');
	var url = '/vodkaster/vod/' + node_id;
	new Ajax.Request(url, { onLoading: function() {
				new Effect.Opacity('vod_list', { from: 1, to: 0.2, duration: 0.2 });
			    },
		 onSuccess: function(transport) {

				if (transport.getHeader('count') > 0) {
					$('get_more_loader').hide();
					$('vod_list').update( transport.responseText );
				} else {
					if ($('fnac_vod_no_results').innerHTML==1) {
						$('get_more_loader').hide();
						$('vod_list').update(transport.responseText);
					}
					else $('fnac_vod_no_results').update(1);
				}
				new Effect.Opacity('vod_list', { from: 0.2, to: 1, duration: 0.8 });
			}
	});
}
//*************************************************//
//		UPDATE ATTRIBUTE FUNCTION          //
//*************************************************//
function updateAttributeRelated ( type, objectID, action )
{
	// Start action
	var objectIDS =  new Array();

	// Depending on context we identify two possible list to manipulate
	var listElementID = ( type == 'actors' ) ? '#actors_list' : '#extraits_list';

	// Loop actors list to record their ids
	$$(listElementID + ' > ul > li').each(function(i) {

		// Test in case the interpretes list is empty
		if( i.readAttribute('id') )
		{
			objectIDS[objectIDS.length] = i.readAttribute('id').split('_').last();
		}
	});

	// Read current element id // Split it in two chuncks // Take the last chunck as object ID
	if (objectID != '')
	{
		// Add current element objectid to existing list
		if( action == 'add' )
		{
			objectIDS[objectIDS.length] = objectID;
		}
		// Remove current element objectid from existing list
		else if( action == 'remove' )
		{
			objectIDS = objectIDS.without(objectID);
		}
	}

	// Clean array of non unique values then join
	// to match ezp objectrelation format
	var value = objectIDS.uniq().join('-');

	// Depend on what we update we change ajax request function
	if( type == 'actors' )
	{
		new Ajax.Request('/vodkaster/edit', { parameters: { contentObjectID: contentObjectID,
								    language: language,
								    attributeIdentifier: 'interpretes',
								    value: value
								  },
							onSuccess: function(transport) {
									  fetchActorsList();
								  }
				});
	}
	// Remove current element objectid from existing list
	else if( type == 'extraits' )
	{
		new Ajax.Request('/vodkaster/edit', { parameters: { contentObjectID: contentObjectID,
								    language: language,
								    attributeIdentifier: 'liens_cinephiles',
								    value: value
								  },
						      onSuccess: function(transport) {
									  fetchExtraitsList();
								  }
				});
	}
}

function makeSortable()
{
	var listID = $$('#actors_list > ul').first().identify();

	Sortable.create(listID, { onUpdate: function() {
						      updateAttributeRelated('actors', false, false);
					    }
			});
}
//*************************************************//
//		EXTRAITS FUNCTIONS	           //
//*************************************************//
function fetchExtraitsList ()
{
	$('extraits_loader').show();

	new Ajax.Request('/vodkaster/related', { parameters: { contentObjectID: contentObjectID,
							       classIdentifier: 'extrait',
							       prefix: 'extraitlist',
							       includeReverseRelated: true,
							       attributeIdentifier: 'liens_cinephiles'
							     },
						onLoading: function() {
							      new Effect.Opacity('extraits_list', { from: 1, to: 0.2, duration: 0.2 });
							    },
						onSuccess: function(transport) {
							      $('extraits_loader').hide();

							      new Effect.Opacity('extraits_list', { from: 0.2, to: 1, duration: 0.2 });

							      $('extraits_list').update( transport.responseText );
							    }
			});
}

function countExtraitsList ()
{
	new Ajax.Request('/vodkaster/related', { parameters: { contentObjectID: contentObjectID,
							       classIdentifier: 'extrait',
							       prefix: 'extraitlist',
							       includeReverseRelated: true,
							       attributeIdentifier: 'liens_cinephiles',
							       countMovieLinks: true
							     },
						onSuccess: function(transport) {
							      var nb_extraits = transport.getHeader('count_movie_links');
							      var oldValue = $('movie_links_header').innerHTML;
							      var newValue = oldValue + ' (' + nb_extraits + ')';
							      $('movie_links_header').innerHTML = newValue;
							    }
			});
}



function fetchExtraitsSimilaireList ()
{
	// First we check that a type is defined
	if($$('.type') && $A($$('.type')).last())
	{
		// If its defined then we have our first element
		var type = $A($$('.type')).last().readAttribute('title');
		
		// Check if the list has already been set
		if($('extraits_similaire_list').innerHTML == '')
		{
			new Ajax.Request('/vodkaster/search', { parameters: "&nodeId="+contentNodeID+"&view=related&classIdentifiers[]=extrait&attributeIdentifiers[]=attributs&limit=5&prefix=extraitlistsimilaire&value="+encodeURIComponent(type),
								onSuccess: function(transport) {
									      $('extraits_similaire_loader').hide();

									      $('extraits_similaire_list').update( transport.responseText );
									  }
					});
		}
	}
}
//*************************************************//
//		BOOKMARK FUNCTIONS	           //
//*************************************************//
function addToPlaylist ( contentObjectID )
{
	// For extraits homepage there can be duplicate node_id so we add 'selection_' to first list
	// to avoid duplicate ids. So we need to remove it either to get true node_id
	var value = $F($( 'addtoplaylist_' + contentObjectID ).identify());
	
	if( value != '' )
	{
		if( value == 'create' )
		{
			event.stop();

			Lightview.show({
				href: '/layout/set/empty/content/action',
				rel: 'ajax',
				options: {
					autosize: true,
					closeButton: false,
					ajax: {
						parameters: $('newPlaylist').serialize(true),
						method: 'post',
						onComplete: function(transport) {
								    $('ajaxSubmit').observe('click', submitAjaxCreate);
							    }
					}
				}
			});
		}
		else
		{
			var url = '/vodkaster/addlocation/' + contentObjectID + '/' + value;
			
			new Ajax.Request(url, { onSuccess: function() {
			
						   if($('playlist_extrait')) {
							   fetchPlaylistsExtrait();
						   }
							
						   if($('playlists_list'))
						   {
							   fetchPlaylists(0);
						   }

						   if($('bookmark_list'))
						   {
							   fetchBookmarks(0);
						   }

                           Lightview.hide();

						   if( $('warning') )
						   {
							   warn('Extrait ajout&eacute; a la playlist.');
						   }
						 },
						 onFailure: function() {

						   if( $('warning') )
						   {
							   warn('Cet extrait existe d&eacute;j&agrave; dans cette playlist.');
						   }
						 }
			});
		}
	}
}
//*************************************************//
//		BOOKMARK FUNCTIONS	           //
//*************************************************//
function addMoviemixBookmark (contentNodeID, elemID)
{
	var url = '/vodkaster/bookmark_add/' + contentNodeID;
	new Ajax.Request( url, {
				onSuccess: function() {
						var src = $(elemID).readAttribute('src');
						if(src.search('_hover.png') == -1)
							$(elemID).writeAttribute('src', src.sub('.png', '_ok.png'));
						else
							$(elemID).writeAttribute('src', src.sub('_hover.png', '_ok.png'));
						$(elemID).stopObserving();
						
						url = '/vodkaster/moviemix/nb_vote/' + contentNodeID;
						new Ajax.Request(url, { onSuccess: function(transport) {
						$('moviemix_'+contentNodeID).update(transport.responseText);}
						});
						
				},
				onFailure: function( transport ) {
					showLogin();
				}
			});
}

function addArtisteBookmark (contentNodeID, currentPage)
{
	var url = '/vodkaster/bookmark_add/' + contentNodeID;
	new Ajax.Request( url, {
				onSuccess: function() {
					if (currentPage == 'favoriteArtists') {
						fetchFavoriteArtists(0);
					} else {
						refreshArtistBookmarkButton();
					}
				},
				onFailure: function( transport ) {
					showLogin();
				}
			});
}

function addBookmark (contentNodeID, elemID)
{
	var url = '/vodkaster/bookmark_add/' + contentNodeID;

	new Ajax.Request( url, { 
				onSuccess: function() {
					var src = $(elemID).readAttribute('src');
					if(src.search('_hover.png') == -1)
						$(elemID).writeAttribute('src', src.sub('.png', '_on.png'));
					else
						$(elemID).writeAttribute('src', src.sub('_hover.png', '_on.png'));
					$(elemID).stopObserving();

					var limit   = $(contentNodeID+'_fans_extrait').readAttribute('limit');
					var node_id = $(contentNodeID+'_fans_extrait').readAttribute('id').split(' ').first().split('_').first();
					 
					if( $('collapse_'+contentNodeID) ){
						var src = $('collapse_'+contentNodeID).getAttribute('src');
						$('collapse_'+contentNodeID).writeAttribute('src', src.sub('right_on.png', 'bottom_off.png'));
					}
					fetchFansExtrait(node_id,limit,'refresh');
				},
				onFailure: function( transport ) {
					showLogin();
				}
			});
}

function fetchBookmarks (offset)
{
	var userID = contentObjectID;
	var limit = $('bookmark_list').readAttribute('class').split(' ').last().split('_').last();
	var url = '/vodkaster/bookmark/' + userID + '/' + isCurrentUser + '/bookmark/' + limit + '/' + offset;

	new Ajax.Request(url, { onLoading: function() {
						new Effect.Opacity('bookmark_list', { from: 1, to: 0.2, duration: 0.2 });
					    },
				 onSuccess: function(transport) {
						$('bookmark_loader').hide();

						new Effect.Opacity('bookmark_list', { from: 0.2, to: 1, duration: 0.2 });

						$('bookmark_list').update( transport.responseText );
						
						$$('.hoverButton').each(function(i) {
							var src = i.readAttribute('src');
							i.observe('mouseover', function() {
								this.writeAttribute('src', src.sub('.png', '_hover.png'));
							});
							i.observe('mouseout', function() {
								this.writeAttribute('src', src.sub('_on.png', '.png'));
							});
						});


						// Paginate
						PaginateBookmark();

						$$('.playlist_form').each(function(i) {

							var extraitMainNodeID = i.readAttribute('class').split(' ').first().split('_').last();

							i.observe('click', function(event) {

								event.stop();

								Lightview.show({
									href: '/layout/set/empty/content/view/user/' + extraitMainNodeID,
									rel: 'ajax',
									options: {
										autosize: true,
										closeButton: false,
										ajax: {
											parameters: $('newPlaylist').serialize(true),
											method: 'post',
											onComplete: function(transport) {
													    $('ajaxSubmit').observe('click', submitAjaxCreate);
													    $$('.hoverButton').each(function(i) {

															var src = i.readAttribute('src');
				
															i.observe('mouseover', function() {
																this.writeAttribute('src', src.sub('.png', '_hover.png'));
															});
					
															i.observe('mouseout', function() {
																this.writeAttribute('src', src.sub('_on.png', '.png'));
															});
														});
												    },
											onFailure: function( transport ) {
												showLogin();
											}
										}
									}
								});
							});
						});
					    }
			});
}


function getCompatibility (current_user_id, user_id)
{
	var i = $('compatibility-percent-view');
	var current_ratio = 0;
	var url = '/vodkaster/get_compatibility/' + current_user_id + '/' + user_id; 

	new Ajax.Request(url, { onSuccess: function(transport) {

						  var compatibility = transport.responseText;
						  var minPosition = -191;
						  
						  if(compatibility)
						  {
							  var position = minPosition * (1 - compatibility / 100);
							  var effect_duration = Math.abs(compatibility - current_ratio) * 0.04;
							  new Effect.Tween('compatibility-percent-view', current_ratio, compatibility, { duration: effect_duration }, function(p) { this.update(p.round()+'%') });
							  new Effect.Tween('compatibility-bar', minPosition, position, { duration: effect_duration }, function(p) { this.update("<div class='colorbar' style='left:"+p.round()+"px;'></div>") });
						  }
					   }
			      });
}

function fetchFavoriteMovies (offset)
{
	var userID = contentObjectID;
	var limit = $('favorite_movies_list').readAttribute('class').split(' ').last().split('_').last();
	var url = '/vodkaster/favorite_movies/' + userID + '/' + isCurrentUser + '/favorite_movies/' + limit + '/' + offset;

	new Ajax.Request(url, { 
				 onLoading: function() {
						new Effect.Opacity('favorite_movies_list', { from: 1, to: 0.2, duration: 0.2 });
				 },
				 onSuccess: function(transport) {
						$('favorite_movies_loader').hide();

						new Effect.Opacity('favorite_movies_list', { from: 0.2, to: 1, duration: 0.2 });

						$('favorite_movies_list').update( transport.responseText );
						
						$$('.hoverButton').each(function(i) {
							var src = i.readAttribute('src');
							i.observe('mouseover', function() {
								this.writeAttribute('src', src.sub('.png', '_hover.png'));
							});
							i.observe('mouseout', function() {
								this.writeAttribute('src', src.sub('_on.png', '.png'));
							});
						});
						
						updateRateUser();

						// Paginate
						PaginateFavoriteMovies();

						$$('.playlist_form').each(function(i) {

							var extraitMainNodeID = i.readAttribute('class').split(' ').first().split('_').last();

							i.observe('click', function(event) {

								event.stop();

								Lightview.show({
									href: '/layout/set/empty/content/view/user/' + extraitMainNodeID,
									rel: 'ajax',
									options: {
										autosize: true,
										closeButton: false,
										ajax: {
											parameters: $('newPlaylist').serialize(true),
											method: 'post',
											onComplete: function(transport) {
													    $('ajaxSubmit').observe('click', submitAjaxCreate);
													    $$('.hoverButton').each(function(i) {

															var src = i.readAttribute('src');
				
															i.observe('mouseover', function() {
																this.writeAttribute('src', src.sub('.png', '_hover.png'));
															});
					
															i.observe('mouseout', function() {
																this.writeAttribute('src', src.sub('_on.png', '.png'));
															});
														});
												    },
											onFailure: function( transport ) {
												showLogin();
											}
										}
									}
								});
							});
						});
					 }
			});
}

function fetchFavoriteArtists (offset)
{
	var userID = contentObjectID;
	var limit = $('favorite_artists_list').readAttribute('class').split(' ').last().split('_').last();
	var url = '/vodkaster/favorite_artists/' + userID + '/' + isCurrentUser + '/favorite_artists/' + limit + '/' + offset;

	new Ajax.Request(url, { 
				 onLoading: function() {
						new Effect.Opacity('favorite_artists_list', { from: 1, to: 0.2, duration: 0.2 });
				 },
				 onSuccess: function(transport) {
						$('favorite_artists_loader').hide();

						new Effect.Opacity('favorite_artists_list', { from: 0.2, to: 1, duration: 0.2 });

						$('favorite_artists_list').update( transport.responseText );
						
						$$('.hoverButton').each(function(i) {
							var src = i.readAttribute('src');
							i.observe('mouseover', function() {
								this.writeAttribute('src', src.sub('.png', '_hover.png'));
							});
							i.observe('mouseout', function() {
								this.writeAttribute('src', src.sub('_on.png', '.png'));
							});
						});
					
						// Paginate
						PaginateFavoriteArtists();

					 }
			});
}


function fetchFavoriteArtists (offset)
{
	var userID = contentObjectID;
	var limit = $('favorite_artists_list').readAttribute('class').split(' ').last().split('_').last();
	var url = '/vodkaster/favorite_artists/' + userID + '/' + isCurrentUser + '/favorite_artists/' + limit + '/' + offset;

	new Ajax.Request(url, { 
				 onLoading: function() {
						new Effect.Opacity('favorite_artists_list', { from: 1, to: 0.2, duration: 0.2 });
				 },
				 onSuccess: function(transport) {
						$('favorite_artists_loader').hide();

						new Effect.Opacity('favorite_artists_list', { from: 0.2, to: 1, duration: 0.2 });

						$('favorite_artists_list').update( transport.responseText );
						
						$$('.hoverButton').each(function(i) {
							var src = i.readAttribute('src');
							i.observe('mouseover', function() {
								this.writeAttribute('src', src.sub('.png', '_hover.png'));
							});
							i.observe('mouseout', function() {
								this.writeAttribute('src', src.sub('_on.png', '.png'));
							});
						});
					
						// Paginate
						PaginateFavoriteArtists();

					 }
			});
}

function removeBookmark (bookmarkID)
{
	Lightview.show({
		href: '#confirm',
		options: {
			width: 300,
			height: 90,
			topclose: false,
			closeButton: false
		}
	});

	$('accept').observe('click', function(event) {

		Lightview.hide();

		var url = '/vodkaster/bookmark_delete/' + bookmarkID;

		new Ajax.Request(url, { onSuccess: function(transport) {
							    fetchBookmarks(0);
							    warn('L\'extrait a &eacute;t&eacute; supprim&eacute;e de votre vodkath&egrave;que');
						    }
				});
	});

	$('cancel').observe('click', function(event) {
		Lightview.hide();
	});
}

// remove bookmark and refresh the button (artist page) or the list of favorite artists (user page)
function removeBookmarkOnArtist (bookmarkID, refreshList)
{
		var url = '/vodkaster/bookmark_delete/' + bookmarkID;
		new Ajax.Request(url, { onSuccess: function(transport) {
							    if (refreshList)
									fetchFavoriteArtists(0);
								else
									refreshArtistBookmarkButton();
									
							    warn('L\'artiste a &eacute;t&eacute; supprim&eacute;e de votre liste');
						    }
				});

}

// refresh bookmark and artist fans list
function refreshArtistBookmarkButton()
{	
	// refresh the fan list (fans page)
	$$('.fans_artiste_full').each(function(i) {
		limit   = i.readAttribute('limit');
		offset   = i.readAttribute('offset');
		node_id = i.readAttribute('id').split(' ').first().split('_').first();
		fetchFansArtisteFull(node_id,limit,offset);
	});
	
	// refresh the left fans block and the tab
	$$('.fans_artiste').each(function(i) {
		limit   = i.readAttribute('limit');
		node_id = i.readAttribute('id').split(' ').first().split('_').first();
		display = i.readAttribute('display'); // display the left block ? 
		if (display != 0) display = 1;
		fetchFansArtiste(node_id,limit,display);
	});
	
	$$('.artiste_bookmark_button').each(function(i) {
		var artisteNodeID = i.readAttribute('id').sub('bookmark_', '');
		var url = '/layout/set/empty/content/view/attribute/' + artisteNodeID + '/(type)/bookmark';
		
		new Ajax.Request(url, { onSuccess: function(transport) {
							
							i.update(transport.responseText);
							
							var elemID = i.down('img').identify();
							var e = $(elemID);
							
							var src = e.readAttribute('src');
							
							if(e.hasClassName('selected'))
							{
							
								e.writeAttribute('src', src.sub('.png', '_ok.png'));
							
							}
							else
							{
							
								e.observe('mouseover', function() {
									this.writeAttribute('src', src.sub('.png', '_hover.png'));
								});

								e.observe('mouseout', function() {
									this.writeAttribute('src', src.sub('_on.png', '.png'));
								});

								e.observe('click', function() {
									addArtisteBookmark(artisteNodeID, '');
								});
							
							}
							
						   }
						   
				      });
			
	});
	
}
//*************************************************//
//		BOOKMARK FUNCTIONS	           //
//*************************************************//
on_facebook_login_login = function(){
        //alert("logged on facebook");
    url = "/authentification/facebook?fb_action=login&fb_sig_session_key="+FB.Facebook.apiClient.get_session().session_key+"&fb_sig_user="+FB.Connect.get_loggedInUser();
        new Ajax.Request(url,
                         { onLoading: function() { },
                           onSuccess: function(transport) {
                                                            fb_infos = transport.responseText;
                                                            switch(fb_infos){
                                                                case "notlegitimate":
                                                                    alert("Connexion error : bad id");
                                                                    break;
                                                                case "false":
                                                                    break;
                                                                case "true":
                                                                    //close and refresh
                                                                    Lightview.hide();
                                                                    setTimeout("window.location.reload()", 100);
                                                                    break;
                                                                case "notregistered":
                                                                    //close and open registration
                                                                    createAccount();
                                                                    break;
                                                                default:
                                                                    alert(fb_infos);
                                                                    break;
                                                            }
                                      }
                         }
                        );

}

on_facebook_login_register = function(){
        //alert("logged on facebook");
        $('facebook_connect_register_button').hide();
        $('facebook_connect_register_connected').show();
        $('register_user_login').value = "....";
        $('label_register_password').hide();
        $('element_register_password').hide();
        $('label_register_password_confirm').hide();
        $('element_register_password_confirm').hide();
        fb_load();

        url = "/authentification/facebook?fb_action=get_info&fb_sig_session_key="+FB.Facebook.apiClient.get_session().session_key+"&fb_sig_user="+FB.Connect.get_loggedInUser();
        new Ajax.Request(url,
                         { onLoading: function() { },
                           onSuccess: function(transport) {
                                                            fb_infos = transport.responseXML.documentElement;
                                                            first_name = fb_infos.getElementsByTagName("first_name")[0].textContent || "";
                                                            last_name = fb_infos.getElementsByTagName("last_name")[0].textContent || "";
                                                            email = fb_infos.getElementsByTagName("email")[0].textContent || "";
                                                            username = fb_infos.getElementsByTagName("username")[0].textContent || "";

                                                            suggested_username = username != "" ? username : first_name.toLowerCase()+"."+last_name.toLowerCase();
                                                            suggested_email = email.split("@")[1] != "proxymail.facebook.com" ? email : "";
                                                            fb_sig_user = FB.Connect.get_loggedInUser();
                                                            suggested_password = Math.floor(Math.random()*100000000);

                                                            $('register_user_login').value = suggested_username;
                                                            $('register_user_email').value = suggested_email;
                                                            $('register_user_fbuid').value = fb_sig_user;

                                                            $('element_register_password').value = suggested_password;
                                                            $('element_register_password_confirm').value = suggested_password;

                                      }
                         }
                        );

}

function showLogin ()
{
	Lightview.show({
		href: '/authentification/login',
		rel: 'ajax',
		options: {
			//width: 485,
			//height: 241,
			width: 485,
			height: 177,
			topclose: true,
			closeButton: true,
			ajax: {
				method: 'get',
				evalScripts: true,
				onComplete: function() 
				{
					submitLogin();
					
					$$('.hoverButton').each(function(i) {

						var src = i.readAttribute('src');

						i.observe('mouseover', function() {
							this.writeAttribute('src', src.sub('.png', '_hover.png'));
						});

						i.observe('mouseout', function() {
							this.writeAttribute('src', src.sub('_on.png', '.png'));
						});
					});
					
					document.observe('lightview:opened', function(event) {
						$('user_name').focus();
					});
					
					$('create').observe('click', function(event) {
						 createAccount();
					});
				},
				onFailed: function()
				{
					showLogin();
				}
			}
		}
	});
}

function createAccount ()
{
	Lightview.show({
		href: '/authentification/register',
		rel: 'ajax',
		options: {
			//height: 300,
			//width: 578,
			autosize:true,
			topclose: true,
			closeButton: true,
			ajax: {
				method: 'post',
				evalScripts: true,
				onComplete: function() {
					submitAccount();
					$$('.hoverButton').each(function(i) {

						var src = i.readAttribute('src');

						i.observe('mouseover', function() {
							this.writeAttribute('src', src.sub('.png', '_hover.png'));
						});

						i.observe('mouseout', function() {
							this.writeAttribute('src', src.sub('_on.png', '.png'));
						});
					});
				}
			}
		}
	});
}

function submitAccount ()
{
	$('submit').observe('click', function(event) {

		event.stop();

		Lightview.show({
			href: '/authentification/register',
			rel: 'ajax',
			options: {
				autosize:true,
				//height: 300,
                //width: 578,
				topclose: true,
				closeButton: true,
				ajax: {
					evalScripts: true,
					parameters: Form.serialize('ajaxForm'),
					onComplete: function() {
						submitAccount();
					},
					onFailure: function() {
					},
					onSuccess: function() {
						if($('concours_not_logged_in'))
							concoursNotLoggedIn();
						else
							setTimeout("window.location.reload()", 100);
					}
				}
			}
		});
	});

	$('cancel').observe('click', function(event) {
		Lightview.hide();
	});
}

function submitLogin ()
{
	$$('.hoverButton').each(function(i) {

		var src = i.readAttribute('src');

		i.observe('mouseover', function() {
			this.writeAttribute('src', src.sub('.png', '_hover.png'));
		});

		i.observe('mouseout', function() {
			this.writeAttribute('src', src.sub('_on.png', '.png'));
		});
	});

	
	$('user_name').observe('keypress', function(e) {
		if(e.keyCode == Event.KEY_RETURN) {
			$('sign_in').hide();
			e.stop();

			Lightview.show({
				href: '/authentification/login',
				rel: 'ajax',
				options: {
					width: 485,
					height: 220,
					topclose: true,
					closeButton: true,
					ajax: {
						parameters: Form.serialize('ajaxForm'),
						onComplete: function() {
							submitLogin();
						},
						onFailure: function() {
						},
						onSuccess: function() {
							Lightview.hide();
							if($('concours_not_logged_in'))
								concoursNotLoggedIn();
							else
								window.location.reload();
						}
					}
				}
			});
		}
	});
	
	$('password').observe('keypress', function(e) {
		if(e.keyCode == Event.KEY_RETURN) {
			$('sign_in').hide();
			e.stop();

			Lightview.show({
				href: '/authentification/login',
				rel: 'ajax',
				options: {
					width: 485,
					height: 220,
					topclose: true,
					closeButton: true,
					ajax: {
						parameters: Form.serialize('ajaxForm'),
						onComplete: function() {
							submitLogin();
						},
						onFailure: function() {
						},
						onSuccess: function() {
							Lightview.hide();
							if($('concours_not_logged_in'))
								concoursNotLoggedIn();
							else
								window.location.reload();
						}
					}
				}
			});
		}
	});
	
	$('sign_in').observe('click', function(event) {
		
		this.hide();
		event.stop();

		Lightview.show({
			href: '/authentification/login',
			rel: 'ajax',
			options: {
				width: 485,
				height: 220,
				topclose: true,
				closeButton: true,
				ajax: {
					parameters: Form.serialize('ajaxForm'),
					onComplete: function() {
						submitLogin();
					},
					onFailure: function() {
					},
					onSuccess: function() {
						Lightview.hide();
						if($('concours_not_logged_in'))
								concoursNotLoggedIn();
							else
								window.location.reload();
					}
				}
			}
		});
	});
}
//*************************************************//
//               RATING FUNCTIONS                  //
//*************************************************//
function rate(url)
{
	new Ajax.Request(url, { 
		onSuccess: function(transport) {
				if($('percent-view'))
					updateRatingRatio();
				
				// if removing the rate
				var newRate = transport.getHeader('newRate');
				var noteID = transport.getHeader('noteID');
				if (newRate == 0) {
					updateRateByRateId(noteID);
				}
			return true;
		},
		onFailure: function( transport ) {
			showLogin();
		}
	});
	
}
//*************************************************//
//		    ACTORS FUNCTIONS          	           //
//*************************************************//
function fetchPlaylist ( offset )
{
	var contentNodeID = $('playlist_list').readAttribute('class').split(' ').first().split('_').last();
	var limit = $('playlist_list').readAttribute('class').split(' ').last().split('_').last();
	var url = '/vodkaster/children/' + contentNodeID + '/extrait/' + isCurrentUser + '/playlist/ajax_playlist/' + limit + '/' + offset;

	new Ajax.Request(url, { onLoading: function() {
						new Effect.Opacity('playlist_list', { from: 1, to: 0.2, duration: 0.2 });
					    },
				 onSuccess: function(transport) {
						$('playlist_loader').hide();

						new Effect.Opacity('playlist_list', { from: 0.2, to: 1, duration: 0.2 });

						$('playlist_list').update( transport.responseText );

						// Make sortable
						if( isCurrentUser )
						{
							makePlaylistSortable(contentNodeID);
						}

						// Paginate
						PaginatePlaylist();
					    }
			});
}

function fetchPlaylists (offset)
{
	var contentNodeID = $('playlists_list').readAttribute('class').split(' ').first().split('_').last();
	var limit = $('playlists_list').readAttribute('class').split(' ').last().split('_').last();
	var url = '/vodkaster/children/' + contentNodeID + '/playlist/' + isCurrentUser + '/playlists/ajax/' + limit + '/' + offset + '/priority,true/false';

	new Ajax.Request(url, { onLoading: function() {
						new Effect.Opacity('playlists_list', { from: 1, to: 0.2, duration: 0.2 });
					    },
				 onSuccess: function(transport) {
						$('playlists_loader').hide();

						new Effect.Opacity('playlists_list', { from: 0.2, to: 1, duration: 0.2 });

						$('playlists_list').update( transport.responseText );

						// Paginate
						PaginatePlaylists();

						// Make sortable
						if( isCurrentUser )
						{
							makePlaylistsSortable(contentNodeID);
						}
					    }
			});
}
//*************************************************//
//	 MAKE PLAYLIST & PLAYLISTS SORTABLE        //
//*************************************************//
function PaginatePlaylist()
{
	$('playlist_list').select('a.pagination_link').each(function(i) {

		var offset = i.readAttribute('class').split(' ').last().split('_').last();

		i.observe('click', function(event) {
			fetchPlaylist(offset);
		});
	});
}
function PaginatePlaylists()
{
	$('playlists_list').select('a.pagination_link').each(function(i) {

		var offset = i.readAttribute('class').split(' ').last().split('_').last();

		i.observe('click', function(event) {
			fetchPlaylists(offset);
		});
	});
}
function PaginateComments()
{
	$('comments_list').select('a.pagination_link').each(function(i) {

		var offset = i.readAttribute('class').split(' ').last().split('_').last();

		i.observe('click', function(event) {
			fetchComments(offset);
		});
	});
}
function PaginateBookmark()
{
	$('bookmark_list').select('a.pagination_link').each(function(i) {
		var offset = i.readAttribute('class').split(' ').last().split('_').last();
		i.observe('click', function(event) {
			fetchBookmarks(offset);
		});
	});
}
function PaginateFavoriteMovies()
{
	$('favorite_movies_list').select('a.pagination_link').each(function(i) {
		var offset = i.readAttribute('class').split(' ').last().split('_').last();
		i.observe('click', function(event) {
			fetchFavoriteMovies(offset);
		});
	});
}
function PaginateFavoriteArtists()
{
	$('favorite_artists_list').select('a.pagination_link').each(function(i) {
		var offset = i.readAttribute('class').split(' ').last().split('_').last();
		i.observe('click', function(event) {
			fetchFavoriteArtists(offset);
		});
	});
}

function PaginateFansArtisteFull()
{
	$('fans_artiste_full').select('a.pagination_link').each(function(i) {
		var offset = i.readAttribute('class').split(' ').last().split('_').last();
		i.observe('click', function(event) {
			$$('.fans_artiste_full').each(function(i) {
				limit   = i.readAttribute('limit');
				node_id = i.readAttribute('id').split(' ').first().split('_').first();
				fetchFansArtisteFull(node_id,limit,offset);
			});
		});
	});
}

function PaginateFansFilmFull()
{
	$('fans_film_full').select('a.pagination_link').each(function(i) {
		var offset = i.readAttribute('class').split(' ').last().split('_').last();
		i.observe('click', function(event) {
			$$('.fans_film_full').each(function(i) {
				limit   = i.readAttribute('limit');
				fetchFansFilmFull(contentObjectID,limit,offset);
			});
		});
	});
}
//*************************************************//
//	 MAKE PLAYLIST & PLAYLISTS SORTABLE        //
//*************************************************//
function makePlaylistSortable(contentNodeID)
{
	var listID = $$('#playlist_list > ul').first().identify();

	Sortable.create(listID, { onUpdate: function() {
						      updatePlaylistPriorities(contentNodeID);
					    }
			});
}

function makePlaylistsSortable(contentNodeID)
{
	var listID = $$('#playlists_list > ul').first().identify();

	Sortable.create(listID, { onUpdate: function(i) {
						      updatePlaylistsPriorities(contentNodeID);
					    }
			});
}
//*************************************************//
//		    ACTORS FUNCTIONS          	   //
//*************************************************//
function updatePlaylistsPriorities ( contentNodeID )
{
	var priorityIDArray = '';
	var url = '/vodkaster/updatepriorities/' + contentNodeID;

	// Get each node_id from each line
	$$('#playlists_list > ul > li > div.content-view-ajax').each(function(i) {
		priorityIDArray = priorityIDArray + ',' + i.readAttribute('id').split('_').last();
	});

	// Remove first character from the string which is ","
	priorityIDArray = priorityIDArray.substring(1);

	new Ajax.Request(url, { parameters: { priorityIDArray: priorityIDArray },
				method: 'post',
				onSuccess: function(transport) {
					fetchPlaylists(0);
				}
			});
}

function updatePlaylistPriorities ( contentNodeID )
{
	var priorityIDArray = '';
	var url = '/vodkaster/updatepriorities/' + contentNodeID;

	// Get each node_id from each line
	$$('#playlist_list > ul > li > div.content-view-ajax').each(function(i) {
		priorityIDArray = priorityIDArray + ',' + i.readAttribute('id').split('_').last();
	});

	// Remove first character from the string which is ","
	priorityIDArray = priorityIDArray.substring(1);

	new Ajax.Request(url, { parameters: { priorityIDArray: priorityIDArray },
				method: 'post',
				onSuccess: function(transport) {
					fetchPlaylist(0);
				}
			});
}
//*************************************************//
//		    ACTORS FUNCTIONS          	   //
//*************************************************//
function removePlaylist (contentNodeID)
{
	Lightview.show({
		href: '#confirm',
		options: {
			width: 300,
			height: 90,
			topclose: false,
			closeButton: false
		}
	});

	$('accept').observe('click', function(event) {

		Lightview.hide();

		var url = '/vodkaster/delete/' + contentNodeID;

		new Ajax.Request(url, { onSuccess: function(transport) {
							   fetchPlaylists(0);
							   warn('La playlist a bien &eacute;t&eacute;e supprim&eacute;e.');
						   }
		});
	});

	$('cancel').observe('click', function(event) {
		Lightview.hide();
	});
}

function removePlaylistFull (contentNodeID)
{
	Lightview.show({
		href: '#confirm',
		options: {
			width: 300,
			height: 90,
			topclose: false,
			closeButton: false
		}
	});

	$('accept').observe('click', function(event) {

		Lightview.hide();

		var url = '/vodkaster/delete/' + contentNodeID;

		new Ajax.Request(url, { onSuccess: function(transport) {

							   warn('La playlist a bien &eacute;t&eacute;e supprim&eacute;e.');

							   // Ok now we can redirect
							   document.location.href = $$('li.currenttab').first().select('a').first().readAttribute('href');
						   }
		});
	});

	$('cancel').observe('click', function(event) {
		Lightview.hide();
	});
}


function removeFromPlaylist (contentNodeID)
{
	Lightview.show({
		href: '#confirm',
		options: {
			width: 300,
			height: 90,
			topclose: false,
			closeButton: false
		}
	});

	$('accept').observe('click', function(event) {

		Lightview.hide();
		
		var url = '/vodkaster/delete_location/' + contentNodeID;

		new Ajax.Request(url, { onSuccess: function(transport) {
									  fetchPlaylist(0);
									  fetchPlaylists(0);
									  warn('L\'extrait a &eacute;t&eacute; supprim&eacute; de la playlist.');
									}
				});
	});

	$('cancel').observe('click', function(event) {
		Lightview.hide();
	});
}
//*************************************************//
//		    ACTORS FUNCTIONS          	   //
//*************************************************//
function warn (messages)
{
	$('warning').update( messages );

	new Effect.Appear('warning', { duration: 0.3, queue: { scope: 'warningscope' } });
	new Effect.Fade('warning', { duration: 0.3, delay: 4, queue: { position: 'end', scope: 'warningscope' } });
}
//*************************************************//
//		    ACTORS FUNCTIONS          	   //
//*************************************************//
function submitAjaxCollect(event)
{
	event.stop();

	Lightview.show({
		href: '/layout/set/empty/content/action',
		rel: 'ajax',
		options: {
			autosize: true,
			closeButton: false,
			ajax: {
				parameters: $('ajaxForm').serialize(true),
				method: 'post',
				onComplete: function(transport) {
						    $('ajaxSubmit').observe('click', submitAjaxCollect);
					    }
			}
		}
	});
}

function submitAjaxCreate(event)
{
	//var elements = $('ajaxForm').getInputs();

	/*$('ajaxForm').request({
		onComplete: function() {
		},
		onFailure: function() {
			$('ajaxSubmit').observe('click', submitAjaxCreate);
		},
		onSuccess: function() {
			fetchPlaylists(0);

			if($('bookmark_list'))
			{
				fetchBookmarks(0);
			}

			Lightview.hide();
		}
	});*/
		var href = $('ajaxForm').readAttribute('action');

		Lightview.show({
		href: href,
		rel: 'ajax',
		options: {
			autosize: true,
			closeButton: false,
			ajax: {
				parameters: $('ajaxForm').serialize(true),
				method: 'post',
				onComplete: function(transport) {
						    $('ajaxSubmit').observe('click', submitAjaxCreate);
					    },
				onSuccess: function() {

					fetchPlaylists(0);

					if($('bookmark_list'))
					{
						fetchBookmarks(0);
					}

					Lightview.hide();
				}
			}
		}
	});
}
//*************************************************//
//       DECLARE AND FIRE LIGHTVIEW ON SHARING     //
//*************************************************//
function shareExtract(first_time)
{
	var current_url   = $F('current_url');
	var current_title = $('twitter').getAttribute('extrait');

	if(first_time)
	{
		var lvHeight = 450;
		if ($("do_not_display_checkbox"))
		{
			$("do_not_display_checkbox").checked = false;
		}
	}
	else
	{
		if($('first_view_extrait_top'))
		{
			$('first_view_extrait_top').hide();
			$('second_view_extrait_top').show();
		}
		if($('first_view_extrait_bottom'))
		{
			$('first_view_extrait_bottom').hide();
		}
		var lvHeight = 265;
	}

	if(!getCookie('__show_again_message') || !first_time)
	{
		Lightview.show({
			href: '#social_share',
			options: {
				width: 385,
				height: lvHeight,
				topclose: true,
				closeButton: true,
				//wmode: window,
				scrolling: false
			}
		});
	} else return;
	
	$('current_url').observe('click', function(event) {
		this.select();
	});
	
	
	$('twitter').observe('click', function(event) {
		var movie   = this.getAttribute('movie');
		var vdk_url = this.getAttribute('url');
		var extrait = this.getAttribute('extrait');
		var tw_url = '';
		
		
		BitlyCB.alertResponse = function(data) {
            var first_result;
            // Results are keyed by longUrl, so we need to grab the first one.
            for(var r in data.results){
                first_result = data.results[r]; 
                break;
            }
            
            var url_bitly = first_result['shortUrl'].toString();
            var message = extrait+' extrait de '+movie+' : '+url_bitly;
            tw_url='http://twitter.com/home/?status='+encodeURIComponent(message);
            window.open(tw_url);
            Lightview.hide();
			return;    
		}
		
		BitlyClient.call('shorten', {'longUrl': current_url}, 'BitlyCB.alertResponse');
		return; 

	});
		
	$('facebook').observe('click', function(event) {
		Lightview.hide();
		fb_url='http://www.facebook.com/sharer.php?u='+encodeURIComponent(current_url)+'&t='+encodeURIComponent(current_title);
		window.open(fb_url,'sharer','toolbar=0,status=0,width=626,height=436');
		return;
	});
	
	$('email').observe('click', function(event) {
		Lightview.hide();
		em_url='mailto://?subject='+encodeURIComponent(current_title)+'&body='+encodeURIComponent(current_url);
		window.open(em_url);
		return;
	});

}

//*************************************************//
//     Close message light view when just published//
//*************************************************//
function closeFirstTimePublish()
{
	if( $("do_not_display_checkbox").checked )
	{
		// to not display this message put new cookie 
		setCookie('__show_again_message','true',1209600);
	}
	Lightview.hide();
}


//*************************************************//
//     Cookies management                          //
//*************************************************//
function setCookie(c_name,value,expireseconde)
{
	var expdate = new Date();
	expdate.setTime (expdate.getTime() + ( expireseconde * 1000));
	document.cookie = c_name+ "=" +escape(value)+";path=/"+((expireseconde==null) ? "" : ";expires="+expdate.toGMTString());
}

function getCookie(c_name)
{
	if (document.cookie.length>0)
    {
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1)
		{
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
		    if (c_end==-1) c_end=document.cookie.length;
		    	return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return "";
}
//*************************************************//
//		    CONTROL PLAYLIST          	   //
//*************************************************//
function onVodkasterPlayerReady(swfid)
{
	updatePlayCount();
}

function onVodkasterPlayerComplete(swfid)
{
	// Get each node_id from each line
	$$('#related_playlist > li.highlight').each(function(i) {
		var hostname = 'http://' + window.location.hostname;
		
		// Read href of the first 'a' element under current element
		if(i.next(0)) {
			var next_url = hostname + i.next(0).select('a').first().readAttribute('href');
		} else {
			var next_url = hostname + $('return_playlist').readAttribute('href');
		}

		// Ok now we can redirect
		document.location.href = next_url;
	});
}

function updatePlayCount()
{
	var url = '/vodkaster/play_count/' + contentMainNodeID;
	new Ajax.Request(url);
}


function suscribeNotificationExtrait()
{
	var url = '/vodkaster/notification/'+contentNodeID;
	new Ajax.Request(url,{
		parameters: {
			'ActionAddToNotification': true,
			'ContentNodeID':contentNodeID }
	});
}

function fetchPlaylistsExtrait()
{
	var url = '/vodkaster/playlist_extrait/'+contentObjectID;
	
	new Ajax.Request(url,{
		parameters: {'contentObjectID':contentObjectID},
		method: 'post',
	 	onSuccess: function(transport) {
		   $('playlist-extrait_loader').hide();
		   $('playlist_extrait').update( transport.responseText );
		   var response = transport.responseText;

		   if (response.search("no_result") == -1)
		   {
			   $('bloc_extrait_playlist').show();
		   }
		},
		onFailure: function() {
		}
	});
}

function fetchFansFilm(display)
{
	var url = '/vodkaster/fans_film/'+contentObjectID;
	new Ajax.Request(url,{
		parameters: {'contentObjectID':contentObjectID},
		method: 'post',
	 	onSuccess: function(transport) {
		   $('fans_film_loader').hide();
		   $('fans_film').update( transport.responseText );
		   var response = transport.responseText;

		   if (response.search("no_result") == -1)
		   {
				$('bloc_fans_film').show();
				$('tab_fans_film').show();
				
				if ($('nb_fans')) {
					var nb_fans = transport.getHeader('nb_fans');
					if (nb_fans == 1) $('nb_fans').update('<span>1</span> fan');
					else $('nb_fans').update('<span>'+nb_fans+'</span> fans');
					$('nb_fans').show();
				}
		   }
		   else
		   {
				$('bloc_fans_film').hide();
				$('tab_fans_film').hide();
				$('nb_fans').hide();
		   }
		},
		onFailure: function() {
		}
	});
}

function fetchFansExtrait(contentNodeID,limit,display)
{
	var url = '/vodkaster/fans_extrait/'+contentNodeID+'/'+limit;
	
	if( display == "no_ajax" ){
		$('fans_extrait_loader_'+contentNodeID).hide();
		new Ajax.Request(url,{
			parameters: {'contentObjectID':contentNodeID,'limit':limit},
			method: 'post',
		 	onSuccess: function(transport) {
			   var response = transport.responseText;
			   $(contentNodeID+'_fans_extrait').update( transport.responseText );
	
			   if (response.search("no_result") == -1)
			   {
				   new Effect.BlindDown('bloc_fans_extrait_'+contentNodeID);
				   $('list_fans_'+contentNodeID).show();
			   }
			   else
			   {
				   $('bloc_fans_extrait'+contentNodeID).hide();
			   }
			},
			onFailure: function() {
			}
		});
	}
	else if( display == "show_ajax" )
	{
		$('fans_extrait_loader_'+contentNodeID).show();
		var src = $('collapse_'+contentNodeID).getAttribute('src');
		$('collapse_'+contentNodeID).writeAttribute('src', src.sub('right_on.png', 'bottom_off.png'));
		
		new Ajax.Request(url,{
			parameters: {'contentObjectID':contentNodeID,'limit':limit},
			method: 'post',
		 	onSuccess: function(transport) {
			   $('fans_extrait_loader_'+contentNodeID).hide();
			   var response = transport.responseText;
			   $(contentNodeID+'_fans_extrait').update( response );
			   
			   $(contentNodeID+'_fans_extrait').writeAttribute('display', 'hide_ajax');
			   $('show_users_'+contentNodeID).writeAttribute('onclick', 'fetchFansExtrait('+contentNodeID+','+limit+',"hide_ajax");');

			   if (response.search("no_result") == -1)
			   {
				   $('list_fans_'+contentNodeID).show();
				   new Effect.BlindDown('button_close_fans_'+contentNodeID);
				   new Effect.BlindDown('bloc_fans_extrait_'+contentNodeID);
			   }
			   else
			   {
				   $('bloc_fans_extrait'+contentNodeID).hide();
			   }
			},
			onFailure: function() {
			}
		});
	}
	else if ( display == "hide_ajax" )
	{
	    $(contentNodeID+'_fans_extrait').writeAttribute('display', 'show_ajax');
	    $('show_users_'+contentNodeID).writeAttribute('onclick', 'fetchFansExtrait('+contentNodeID+','+limit+',"show_ajax");');
		if( $('bloc_fans_extrait_'+contentNodeID) )
		{
			var src = $('collapse_'+contentNodeID).getAttribute('src');
			$('collapse_'+contentNodeID).writeAttribute('src', src.sub('bottom_off.png','right_on.png'));
			new Effect.BlindUp('bloc_fans_extrait_'+contentNodeID);
		}
	}
	else if( display == "refresh" )
	{
		if( $('show_users_'+contentNodeID) ){
			$(contentNodeID+'_fans_extrait').writeAttribute('display', 'hide_ajax');
			$('show_users_'+contentNodeID).writeAttribute('onclick', 'fetchFansExtrait('+contentNodeID+','+limit+',"hide_ajax");');
		}
		
		new Ajax.Request(url,{
			parameters: {'contentObjectID':contentNodeID,'limit':limit},
			method: 'post',
		 	onSuccess: function(transport) 
		 	{
			   $('fans_extrait_loader_'+contentNodeID).hide();
			   var response = transport.responseText;
			   $(contentNodeID+'_fans_extrait').update( response );
			   if( $('button_close_fans_'+contentNodeID) )
			   {
				   $('button_close_fans_'+contentNodeID).show();
			   }
			   $('list_fans_'+contentNodeID).show();
			   $('bloc_fans_extrait_'+contentNodeID).show();
			},
			onFailure: function() {
			}
		});		
	}
}

// manage the "fans" block if it has to be displayed and the "fans" tab
function fetchFansArtiste(contentNodeID, limit, display)
{
	if (display==1) {
		var url = '/vodkaster/fans_artiste/'+contentNodeID+'/'+limit;
		if ($('fans_artiste_loader_'+contentNodeID))
			$('fans_artiste_loader_'+contentNodeID).hide();
		new Ajax.Request(url,{
			parameters: {'contentNodeID':contentNodeID,'limit':limit},
			method: 'post',
			onSuccess: function(transport) {
				var response = transport.responseText;
				$(contentNodeID+'_fans_artiste').update( transport.responseText );

				if (response.search("no_result") == -1)
				{
					new Effect.BlindDown('bloc_fans_artiste_'+contentNodeID);
					$('list_fans_'+contentNodeID).show();
					$('tab_fans_artiste').show();
				}
				else
				{
					$('bloc_fans_artiste_'+contentNodeID).hide();
					$('tab_fans_artiste').hide();
				}
			},
			onFailure: function() {
			}
		});
		
	} else {
		var url = '/vodkaster/fans_artiste/'+contentNodeID+'/'+limit;
		new Ajax.Request(url,{
			parameters: {'contentNodeID':contentNodeID,'limit':limit},
			method: 'post',
			onSuccess: function(transport) {
				var response = transport.responseText;
				if (response.search("no_result") == -1)
				{
					$('tab_fans_artiste').show();
				}
				else
				{
					$('tab_fans_artiste').hide();
				}
			},
			onFailure: function() {
			}
		});
		
	}
}

function fetchFansArtisteFull(contentNodeID, limit, offset)
{
	$('fans_artiste_loader_'+contentNodeID).show();
	var url = '/vodkaster/fans_artiste_full/'+contentNodeID + '/' + limit + '/' + offset;
	new Ajax.Request(url,{
		parameters: {'contentNodeID':contentNodeID},
		method: 'post',
		onSuccess: function(transport) {
		    var response = transport.responseText;
			$(contentNodeID+'_fans_artiste_full').update( transport.responseText );
		    $('fans_artiste_loader_'+contentNodeID).hide();
			var nb_results = transport.getHeader('nbResults');
			if (nb_results > 0) {
				PaginateFansArtisteFull();
			} else {
				// if no result => no fan page => redirection
				document.location.href = $('main_artist_page').readAttribute('href');
			}
		},
		onFailure: function() {
		}
	});
}

function fetchFansFilmFull(contentObjectID, limit, offset)
{
	$('fans_film_full').hide();
	$('fans_film_loader').show();
	var url = '/vodkaster/fans_film_full/'+contentObjectID + '/' + limit + '/' + offset;
	new Ajax.Request(url,{
		parameters: {'contentNodeID':contentNodeID},
		method: 'post',
		onSuccess: function(transport) {
		    var response = transport.responseText;
			$('fans_film_full').update( transport.responseText );
			$('fans_film_full').show();
		    $('fans_film_loader').hide();
			var nb_results = transport.getHeader('nbResults');
			if (nb_results > 0) {
				PaginateFansFilmFull();
			} else {
				// if no result => no fan page => redirection
				document.location.href = $('main_film_page').readAttribute('href');
			}
		},
		onFailure: function() {
		}
	});
	
}

function newMovieMix()
{
	var url = '/vodkaster/moviemix/new';
	new Ajax.Request(url,{
		method: 'post',
	 	onSuccess: function(transport) {
		   document.location.href = transport.responseText ;
		}
	});
}

function movieMixShareOnFacebook()
{
	var current_url = $('facebook_share').getAttribute('current_url');
	fb_url='http://www.facebook.com/sharer.php?u='+encodeURIComponent(current_url);
	window.open(fb_url,'sharer','toolbar=0,status=0,width=626,height=436');
}

function movieMixShareOnTwitter()
{
	var current_url 	= $('twitter_share').getAttribute('current_url');
	var moviemix_title 	= $('twitter_share').getAttribute('moviemix_title');
		
	BitlyCB.alertResponse = function(data) {
        var first_result;
        // Results are keyed by longUrl, so we need to grab the first one.
        for(var r in data.results){
            first_result = data.results[r]; 
            break;
        }
        
        var url_bitly = first_result['shortUrl'].toString();
        var message = '#moviemix ' + moviemix_title + ' : ' + url_bitly;
        tw_url='http://twitter.com/home/?status=' + encodeURIComponent(message);
        window.open(tw_url);
		return;    
	}
	
	BitlyClient.call('shorten', {'longUrl': current_url}, 'BitlyCB.alertResponse');
}

function fetchMovieMixTop()
{
	var url = '/vodkaster/moviemix/top';
	new Ajax.Request(url,{
		onSuccess: function(transport) {
		   $('top_moviemix').update( transport.responseText );
		},
		onFailure: function() {
		}
	});
}

function updateRateByRateId(noteID)
{
	id = $('rating_'+noteID).up().readAttribute('id');
	id = id.sub('note_', '');
	var url = '/layout/set/empty/content/view/attribute/' + id;
	
	new Ajax.Request(url, { 			
		onSuccess: function(transport){
			$('rating_'+noteID).up().update(transport.responseText);
	   },
	   onFailure: function() {
	   }
  });
  
}


function updateRateUser(){
	$$('.note').each(function(i) {
		i.observe('click', function(event) {
			if($('fans_film')) {
				fetchFansFilm();
			}
			
			// updates fans film tab
			$$('.fans_film_full').each(function(i) {
				$('tab_fans_film').show();
				limit   = i.readAttribute('limit');
				offset   = i.readAttribute('offset');
				fetchFansFilmFull(contentObjectID,limit,offset);
			});
			
		});
		
		var extraitNodeID = i.readAttribute('id');
	
		extraitNodeID = extraitNodeID.sub('note_', '');
	
		var url = '/layout/set/empty/content/view/attribute/' + extraitNodeID;
	
		new Ajax.Request(url, { onSuccess: function(transport) {
						    i.update(transport.responseText);
						   }
				      });
	});
}

//*************************************************//
//  Retrospective                                  //
//*************************************************//
function imgHover(i, j)
{
	$$('.img_hover').each(function(i) {
		i.hide();
	});
	$(i + '_' + j + '_hover').show();
}

function imgOut(i, j)
{
	$(i + '_' + j + '_hover').hide();
}

function fetchRetroComments (offset)
{
	var limit = $('retro_comments_list').readAttribute('class').split('_').last();
	var retroNodeId = $('retro_comments_list').readAttribute('node_id');
	var url = '/vodkaster/children/' + retroNodeId + '/comment/' + isCurrentUser + '/comment/ajax/' + limit + '/' + offset + '/published,false/false';
	
	new Ajax.Request(url, { onLoading: function() {
						new Effect.Opacity('retro_comments_list', { from: 1, to: 0.2, duration: 0.2 });
					    },
				 onSuccess: function(transport) {
						$('comments_loader').hide();

						new Effect.Opacity('retro_comments_list', { from: 0.2, to: 1, duration: 0.2 });

						$('retro_comments_list').update( transport.responseText );

						// Paginate
						PaginateComments();
					    }
			});
}

function retroShareOnFacebook()
{
	var current_url = $('facebook_share').getAttribute('current_url');
	fb_url='http://www.facebook.com/sharer.php?u='+encodeURIComponent(current_url);
	window.open(fb_url,'sharer','toolbar=0,status=0,width=626,height=436');
}

function retroShareOnTwitter()
{
	var short_url 	= $('twitter_share').getAttribute('short_url');
	var message = $('twitter_share').getAttribute('message') + ' ' + short_url;
    tw_url='http://twitter.com/home/?status=' + encodeURIComponent(message);
    window.open(tw_url);
}

function femmesShareOnFacebook()
{
	var current_url = $('facebook_share').getAttribute('current_url');
	fb_url='http://www.facebook.com/sharer.php?u='+encodeURIComponent(current_url);
	window.open(fb_url,'sharer','toolbar=0,status=0,width=626,height=436');
}

function femmesShareOnTwitter()
{
	var short_url 	= $('twitter_share').getAttribute('short_url');
	var message = $('twitter_share').getAttribute('message') + ' ' + short_url + ' #journeedelafemme';
	tw_url='http://twitter.com/home/?status=' + encodeURIComponent(message);
    window.open(tw_url);
}

function fetchQuizTop()
{
	$('top_quiz_loader').show();
	$('top_quiz').hide();
	
	var quizId = $('top_quiz').readAttribute('quiz_id');
	var limit = $('top_quiz').readAttribute('limit');
	var url = '/vodkaster/quiz/top/' + quizId + '/' + limit;
	
	new Ajax.Request(url, { 
				onSuccess: function(transport) {
					$('top_quiz_loader').hide();
					$('top_quiz').show();
					$('top_quiz').update(transport.responseText);
					
			    }
	});
		
	
}
//*************************************************//
//     Facetting Liste Extraits Artiste/Film       //
//*************************************************//
function openFacettingComboBox (obj) {
	document.body.onclick = function() {};
	closeAllFacettingComboBoxes();
	obj.parentNode.className = 'facettingComboBox facettingComboBoxOpen';
	obj.className = 'selected openedCB';
	obj.onclick = function() {closeFacettingComboBox(obj);};
	obj.onmouseout = function() {
		onClickOutComboBox(obj);
	};
}
function closeFacettingComboBox (obj) {
	document.body.onclick = function() {};
	obj.parentNode.className = 'facettingComboBox';
	obj.className = 'selected';
	obj.onclick = function() {openFacettingComboBox(obj);};
}
function closeAllFacettingComboBoxes () {
	$$('.openedCB').each(function(i) {
		closeFacettingComboBox(i);
	});
}
function onClickOutComboBox(obj) {
	document.body.onclick = function() {closeFacettingComboBox(obj);};
}
//*************************************************//
//     Concours								       //
//*************************************************//
function concoursNotLoggedIn()
{
	// set in a session variable (through PHP) that the score has not been stored (because user has just logged in)
	// the score will be stored after the page reload
	var url =  '/vodkaster/quiz_store_score/?logged=0';
	//console.log(url);
	new Ajax.Request(url, { 
				parameters	: { score   : $('concours_not_logged_in').readAttribute('score'),
								nb_ok	: $('concours_not_logged_in').readAttribute('nb_ok')},
				onSuccess   : function(transport) {
					//alert(transport.responseText);
					setTimeout("window.location.reload()", 100);
			    }
	});
}


function concoursLoggedIn()
{
	url =  '/vodkaster/quiz_store_score/?logged=1&quiz_id=' + $('concours_logged_in').readAttribute('quiz_id')+'&user_id=' + $('concours_logged_in').readAttribute('user_id');
	//console.log(url);
	new Ajax.Request(url, {
				onSuccess   : function(transport) {
					//console.log(transport.responseText);
					fetchQuizTop();
			    }
	});
}