/*
 2010 Alban COQUOIN
*/
void 0!==typeof jQuery&&function(b){b.fn.ratingSprite=function(e){function f(a,c,d){b("img",c).removeAttr("class");b.browser.msie?b("img",c).css({"background-position-x":"","background-position-y":""}):b("img",c).css("background-position","");0==a?b("img",c).addClass(d.className.empty):parseInt(a,10)!=a?(a=parseInt(a,10),b("img:gt("+(a-1)+")",c).addClass(d.className.empty),b("img:lt("+(a+1)+")",c).addClass(d.className.full),b("img:eq("+a+")",c).addClass(d.className.half)):(b("img:gt("+(a-1)+")",c).addClass(d.className.empty),
b("img:lt("+a+")",c).addClass(d.className.full));b("img",c).each(function(a){var c,e;b.browser.msie?(c=parseInt(b(this).css("background-position-x"),10),e=parseInt(b(this).css("background-position-y"),10)):(c=parseInt(b(this).css("background-position").split(" ")[0],10),e=parseInt(b(this).css("background-position").split(" ")[1],10));b(this).css({"background-position":0==a%d.divide?c+"px "+(e-Math.round(parseInt(b(this).width(),10))*(a%d.divide))+"px":c-Math.round(parseInt(b(this).width(),10))*(a%
d.divide)+"px "+e+"px"})})}var a=b.extend({},{note:10,divide:2,className:{empty:"",full:""},readOnly:!1,defaultValue:5,image:"/api/img/pixel.gif",callback:function(){return!1},hover:function(){return!1}},e);return this.each(function(){var g=b(this),c=a.note*Math.max(1,a.divide);e.className.empty=e.className.empty.replace(/\./gi," ");e.className.full=e.className.full.replace(/\./gi," ");e.className.half&&(e.className.half=e.className.half.replace(/\./gi," "));b(this).html("");for(var d=1;d<=c;d++){var h=
b("<img />").attr({src:a.image,title:Math.round(100*(d/a.divide))/100+"/"+a.note,alt:Math.round(100*(d/a.divide))/100}).addClass(a.defaultValue*a.divide>=d?a.className.full:a.className.empty);b(this).append(h)}b("img",this).each(function(c){b(this).css("width",Math.round(b(this).width()/a.divide))});f(a.defaultValue*a.divide,this,a);a.hover(a.defaultValue);!1===a.readOnly&&(b("img",this).css("cursor","pointer").mouseenter(function(c){f(b(this).index()+1,g,a);a.hover(b(this).attr("alt"))}),b("img",
this).css("cursor","pointer").mouseleave(function(c){var d=b(this).offset();0==b(this).index()&&d.left>c.pageX&&(f(0,g,a),a.hover(0))}),b(this).mouseleave(function(){a.hover(a.defaultValue);f(a.defaultValue*a.divide,g,a)}),b("img",this).click(function(){a.defaultValue=b(this).attr("alt");a.readOnly=!0;g.find("img").unbind().css("cursor","default");a.callback(b(this).attr("alt"))}))})}}(jQuery);


$(document).ready(function(){$("#infosJeux .note-globale .notation").each(function(){$(this).ratingSprite({className:{empty:".sprite-global.etoile_vide_png",full:".sprite-global.etoile_pleine_png"},readOnly:!0,defaultValue:$(this).text()})})});


$(document).ready(function() {
	var block = $('.block-jeux-slideshow');
	var pageNumber = 1;
	var pageNumberTotal = $(block).find('.image_navigate .info .imageNumberTotal').html();
	var currentImage = $(block).find('.image_slideshow img.current');

	var url = '/ajax.php?action=get_image';
	var width = parseInt($('#image_slideshow_width').val());
	var canMoveNext = true;

	var imageContainer = $(block).find('.image_slideshow .image_container');
	var imageNumberTag = $(block).find('.image_navigate .info .imageNumber');


	var imageTag = $(block).find('.image_slideshow img.current');
	var nextButton = $(block).find(' .image_navigate a.next');
	var prevButton = $(block).find(' .image_navigate a.prev');
	var diapoButton = $(block).find('.diapo a');
	var agrandirButton = $(block).find('.more a');
	var imageSupport = $(block).find('.support img');
	var datePhoto = $(block).find('.support .date');

	timer = null;

	// lancement / arret du diapo
	$(diapoButton).click(function() {
		if (timer != null) {
			stopDiapo();
		} else {
			moveNextImage();
			timer = window.setInterval(function() {moveNextImage();}, 3000);
			$(diapoButton).text('Stopper le diaporama');
		}
	});

	// arr�t du diapo
	stopDiapo = function () {
		clearInterval(timer);
		timer = null;
		$(diapoButton).text('Lancer le diaporama');
	}

	// clic sur le bouton "suivante" : on arr�te la diapo et si elle est en cours et on passe � l'image suivante
	$(nextButton).click(function() {
		stopDiapo();
		moveNextImage();
	});

	// clic sur le bouton "pr�c�dente" : on arr�te la diapo et on revient en arri�re
	$(prevButton).click(function() {
		stopDiapo();
		movePrevImage();
	});

	movePrevImage = function () {
		moveImage(false);
	}

	// d�placement vers l'image suivante
	moveNextImage = function () {
		moveImage(true);
	}

	// d�placement vers l'image suivant si next = true, ou pr�c�dente sinon
	moveImage = function(next) {
		if (canMoveNext) {
			canMoveNext = false;
			if (next) {
				pageNumber ++;
				if (pageNumber > pageNumberTotal) {
					pageNumber = 1;
				}
			} else {	// previous
				pageNumber --;
				if (pageNumber < 1) {
					pageNumber = pageNumberTotal;
				}
			}
			$(imageContainer).animate(
				{'left': - width *(pageNumber-1)},
				((next && pageNumber == 1 || !next && pageNumber == pageNumberTotal) ? 0 : 'slow'),
				function() {
					// on bouge l'image courante
					currentImage = $(currentImage).parent().find('.i' + pageNumber);
					$(imageNumberTag).html(pageNumber);

					// on change le lien "agrandir l'image"
					$(agrandirButton).attr('href', $(agrandirButton).attr('href').replace(/([0-9]+).html$/g, $(currentImage).attr('rel') + '.html'));
					$(imageSupport).attr('class', 'console sprite-global logo_' + $(currentImage).attr('rev') + '_png');
					$(datePhoto).text('Publi�e le ' + $(currentImage).attr('date'));

					// si l'on est en "manque" de photo, on en charge d'autres
					if (next && !$(currentImage).parent().find('.i'+(pageNumber+5)).length && pageNumber+5 <= pageNumberTotal) {	// next
						loadImages(pageNumber+5);
					} else if (!next && !$(currentImage).parent().find('.i'+(pageNumber-5)).length && pageNumber-5 >= 1) {	// previous
						loadImages(pageNumber-9);
					} else {
						canMoveNext = true;
					}
				}
			);
		}
	}

	loadImages = function(start) {
		$.ajax({
			type: 'post',
			url: url,
			data : {
				idJeu : $('input#idJeu:hidden').val(),
				width: width,
				numPage: start
			},
			success: function(data) {
				lines = data.split('\n');
				imageId = new Array();
				imageUrl = new Array();
				support = new Array();
				date = new Array();
				var newPos = new Array();
				var newImg = new Array();
				//var pos = parseInt($(imageContainer).find('img:last-child').css('left'));
				var pos = parseInt((start-1)*width);
				$.each(lines, function(index, line) {
					// Pour chaque image
					if (line.length > 0) {
						// on r�cup�re les infos n�c�ssaires
						dataTable = line.split('|', 4);
						imageId[index] = dataTable[0];
						imageUrl[index] = dataTable[1];
						support[index] = dataTable[2];
						date[index] = dataTable[3];

						// on calcul la position de l'image
						newPos[index] = pos + (width * index);

						// on ajoute l'image au DOM
						newImg[index] = currentImage.clone()
										.attr('src', imageUrl[index])
										.attr('rel', imageId[index])
										.attr('rev', support[index])
										.attr('date', date[index])
										.attr('class', 'next i'+(start+index))
										.css('left', newPos[index]);
						if (!$(imageContainer).find('.i'+(start+index)).length) {
							$(imageContainer).append(newImg[index]);
						}
					}
				});
				canMoveNext = true;
			}
		});
	}
});


$(document).ready(function() {
	var selecteurAttente = '.header .block-infos-right .attente';
	$.each($(selecteurAttente), function(index, val) {
		var c = Utils.getCookie('attente_jeu_' + $(val).find('.idJeu').val());
		if (c != null) {
			// Si l'utilisateur � d�j� donn� son niveau d'attente
			$(val).find("input[name='input_attente'][value=" + c + "]").attr('checked', 'checked');
			$(val).find("input[name='input_attente']").attr('disabled', 'disabled');
		} else {
			$(val).find("input[name='input_attente']").removeAttr('disabled').removeAttr('checked');
			// On est sur le niveau d'attente et dans les widgets
			$(val).find(".widget .attente_internaute_form input[type='radio']").live('click', function() {
				$(this).closest('form').trigger('submit');
				return false;
			});
			$(val).find('.attente_internaute_form input[type=radio]').click(function() {
				$(this).closest('form').trigger('submit');
			});
			$(val).find('.attente_internaute_form').submit(function() {
				if(typeof $(val).find("input[name='input_attente']:checked").val() == 'undefined'){
					$.facebox.alert("Veuillez choisir un niveau d'attente !");
				}else{
					var note = $(val).find("input[name='input_attente']:checked").val();

					$.ajax({
						url: $(this).attr('action'),
						type: 'post',
						data: {
							idJeu: $(val).find('.idJeu').val(),
							note: note,
							type: 'attente'
						},
						success: function(){
							$(val).find("input[name='input_attente']").attr('disabled', 'disabled');
							$.facebox({
								url : '/api/membre/facebox.post.attente.php',
								//titre : (note == '1' ? 'Souhaitez-vous recevoir les alertes de ce jeu ?' : 'Pourquoi n\'attendez-vous pas ce jeu ?'),
								titre : 'Pourquoi ' + ($(val).find("input[name='input_attente']:checked").val() == 1 ? 'attendez-vous' : 'vous n\'attendez pas') + ' ce jeu ?',
								post : {
									id : $(val).find('.idJeu').val(),
									type : 'fiche jeux',
									note : note,
									forum : $('#forumJeu').val()
								}
							});
						}
					});
				}
				return false;
			});
		}
	});

	$('.donner_son_avis a').click(function() {
		$.facebox({
			url: '/ajax.php?action=donner_votre_avis',
			post: {idJeu: $('#infosJeux .id').attr('rel')},
			titre: 'Donner votre avis sur ' + $('#infosJeux').attr('rel'),
			width: '500'
		});
		return false;
	});

	if( $('.header .bloc_header.preview ').length == 0 ){
		var cadrePlus = $('.bloc_header').eq(0), cadreMoins = $('.bloc_header').eq(1);
		if(cadrePlus.outerHeight() > cadreMoins.outerHeight()) {
			cadreMoins.css('height',cadrePlus.outerHeight()+'px');
		}else{
			cadrePlus.css('height',cadreMoins.outerHeight()+'px');
		}
	}

});


/**
 * Slideshow (for jQuery)
 * version: 2.1 (27/12/2010)
 * @requires jQuery v1.4.0 or later
 * @copyright 2010 C�cile Aubin
 */

if(parseFloat($().jquery) < 1.4){
	alert("Librairie JQuery incompatible avec le slideshow.\nMerci d'utiliser Jquery >= 1.4.0");
}

var $slideshow = null;

$.slideshow = function(settings) {
	new Slideshow(settings);
}

$.fn.slideshow = function(settings) {
	settings = (typeof settings == 'undefined' ? {} : settings);
	settings.id = this.attr('id');
	new Slideshow(settings);
}

Slideshow = function(settings){
	this.__construct(settings);
};

Slideshow.defaultSettings = {
	id : 'slideshow_trans',								// @public Id de la div � charger
	index: '',											// @public Id du slideshow (permet pour les �ditos d'enregistrer les stats d'affichage)
	skin : false,										// @public Skin graphique
	size : 700,											// @public Largeur du diaporama 700 / 1000 / etc
	first : 0,											// @public Position du slideshow
	display: 1,											// @public Nombre d'image affich� dans le viewport
	nb_img_load: 3, 									// @public Nombre d'image charg�s (suivantes et pr�cedentes) � celle en cours
	animate_duration: 700,								// @public Dur�e (en millisecondes) de l'animation des photos
	has_thumbnails: 'ss_thumbnails',					// @public Affichage un slideshow compos�e de miniature
	parent: false,										// @Private
	legend: false,										// @public Affichage de la l�gende de la photo
	parse_legend: false,								// @public Affichage de la l�gende pars�e de la photo (utilis� en embed)
	page_last: false,									// @public Passerelle vers la derni�re page
	page_first: false,									// @public Passerelle vers la premi�re page
	pagination_thumbs: false,							// @public Pagination des miniatures par href
	edito : false,										// @public Mode edito du diaporama transverse
	auto_load : false,									// @public Si false, force un diaporama edito aux rechargement  des pages
	urlPage : false,									// @public Remplit le href des liens suivants/precedents/premier et dernier (pour click droit)
	autoslide : 3E3,									// @public Temps de changement (en millisecondes) d'image pour la lecture du diaporama
	nb_thumbs  : -1										// @public Nombre de miniatures affich�es dans le slide miniature
};

Slideshow.prototype = {
	/**
	 * Instanciation et apparition de la facebox
	 */
	__construct : function(settings){
        
		var othis = this;

		if(typeof slideshowSettings != 'undefined'){
			Slideshow.defaultSettings = $.extend({}, Slideshow.defaultSettings, slideshowSettings);
		}
		if(settings){
			this.settings = $.extend({
				context : $('body')
			}, Slideshow.defaultSettings, settings);
		}
		
		// Forcer certains param�tres si miniatures
		if (this.settings.parent){
			this.settings.has_thumbnails = false;
			this.settings.legend = false;
			// desactivation pour les miniatures et le viewport
            this.settings.page_first = false;
            this.settings.page_last = false;
		}
		
		// DESACTIVATION PERMANTENTE DE FIRST ET LAST
		this.settings.page_first = false;
        this.settings.page_last = false;
		
		// On enregistre les stats d'affichage pour les "Editos"
		if (this.settings.edito){ 
			$.ajax({
				url: "/api/slideshow/ajax/count.php?id="+this.settings.index+"&type=diaporama",
				cache: false
			});
		}

		// Buttons
		var dom_pagination_parent = "";
		if (!this.settings.parent){
		  var dom_pagination_parent = " .ss_viewport ";
    	}
		this.bnext = $('#'+this.settings.id+' > '+dom_pagination_parent+'.ss_pagination .ss_next');
		this.bprev = $('#'+this.settings.id+' > '+dom_pagination_parent+'.ss_pagination .ss_prev');
		this.bfirst = $('#'+this.settings.id+' > '+dom_pagination_parent+'.ss_pagination .ss_first');
		this.blast = $('#'+this.settings.id+' > '+dom_pagination_parent+'.ss_pagination .ss_last');
    
		
		// Listing des �lements
		this.first = $('#'+this.settings.id+' > .ss_viewport li:first');
		this.last = $('#'+this.settings.id+' > .ss_viewport li:last-child');
		this.viewport = $('#'+this.settings.id+' > .ss_viewport');
		this.list = $('#'+this.settings.id+' > .ss_viewport .ss_main');
		if (this.settings.parse_legend){
			this.allparselegend = $('#'+this.settings.id+' > .ss_allparselegend');
		}
		
		// Informations
		this.title = $('#'+this.settings.id+' > .ss_info_photo .ss_title');
		this.credit = $('#'+this.settings.id+' > .ss_info_photo .ss_credit');
		this.legend = $('#'+this.settings.id+' > .ss_info_photo .ss_legend');
		this.pcurrent = $('#'+this.settings.id+' > .ss_informations .ss_pcurrent');
		this.timeout = false;
		this.thumbnails = false;
		this.firstload = true;
		
		// Template et skin
		if (this.settings.auto_load || !this.settings.edito){ // Alleger les editos sans autoload, en supprimant certaines actions deja fait dans le dom
		
			// Initialiser les dimensions
			this.setDimensions();
	        this.list.css({'width':$('#'+this.settings.id+' .ss_main li').length * this.viewport_width});  
			
			// Ajout des skins (celle par d�faut et celle appel�e) 
	        $('#'+this.settings.id).addClass('ss_default_slideshow');
	        $('#'+this.settings.id).addClass('ss_width_'+this.settings.size);  
	        if (this.settings.skin) $('#'+this.settings.id).addClass('ss_'+this.settings.skin);  
	        if (this.settings.legend) $('<div>',{'class': 'ss_legend'}).insertAfter('#'+this.settings.id+' div.ss_title');
		
			this.setButtons();
		
			if (!this.settings.parent ){  // Si diaporama principal
				this.goPosition(this.settings.first);
			}else{ // Si thumbnails
	        	this.goPagePosition(this.settings.first);
	        }
	        
	        // Actions du clavier
	        $(document).keydown( function(e) { 
	        	if( (e.which == 37 || e.which == 39 )&& e.target.nodeName != 'TEXTAREA'){
    				e.stopImmediatePropagation();
        			e.preventDefault();	
		        	if(e.which == 37){othis.goPrev(1); } 
			        if(e.which == 39){othis.goNext(1); }
	        	}
	        });
        }
        // Cr�ation d'un Thumbnails
		if (this.settings.has_thumbnails){
			
			// Si pas pass� en param�tre le nombre est pr�d�fini 
			// (garantie la compatibilit� avec les diaporamas hors module)
			if(this.settings.nb_thumbs < 0){
				if (this.settings.size == 'mobile') {var nb_thumbs = 4;}
				if (this.settings.size == 300) {var nb_thumbs = 4;}
				if (this.settings.size == 700) {var nb_thumbs = 5;}
				if (this.settings.size == 1000) {var nb_thumbs = 7;}
			}else{
				var nb_thumbs = this.settings.nb_thumbs;
			}
			
			/* Slideshow Miniatures */
			this.thumbnails = new Slideshow({
				id : 'ss_thumbnails'+this.settings.index,
				index: this.settings.index,
				has_thumbnails: false,
				size: this.settings.size,
				first: this.settings.first,
				display: nb_thumbs,
				nb_img_load: parseInt(nb_thumbs*2),
				animate_duration: 1000,
				parent: this
			});
		}
	},
	// Lecture automatique
  	play: function (){ 
  		var othis = this;
  		// D�sactiver les boutons le temps de l'animation
  		this.desactiveButtons();
		
  		if (!this.timeout) { othis.goNext(1); }
  		this.timeout = setTimeout(function() { 
			if (!othis.Element.next().length ) { 
				othis.goFirst(); 
			}else{
				othis.goNext(1);
			}
  		}, this.settings.autoslide);
  	},
  	// Arreter la lecture automatique
  	stop: function (){ clearTimeout(this.timeout); this.timeout = null; this.activeButtons();},
	focusVignette : function() { this.Element.find('img').addClass('focus');},
    clearFocus : function() { this.list.children().each(function(index) { $(this).find('img').removeClass('focus');}); },
    getCurrentPositionX : function () { var i = this.getCurrentIndex(); if (i == 0) return 0; else return (i * this.image_width); },// Retourne la position en cours (en pixels)
    getCurrentIndex : function(){  	return parseInt(this.Element.attr('nav'));},
    getViewportPosition : function (){	return -parseInt(this.list.css('left'));}, // Valeur absolue
    goFirst : function(e) { 
    	this.clearFocus(); this.Element = this.first;  this.positionVignette(e); this.focusVignette();
    	if (this.settings.has_thumbnails && this.thumbnails){	this.thumbnails.goFirst(e); }// R�percuter sur le thumbnails
    },
    goLast : function(e) { 
    	this.clearFocus(); this.Element = this.last; this.focusVignette(); this.positionVignette(e); 
    	if (this.settings.has_thumbnails){	this.thumbnails.goLast(e); }// R�percuter sur le thumbnails
    },
    goPosition :function (i){this.clearFocus(); this.changeElement('position',parseInt(i)); this.focusVignette(); this.positionVignette();}, 
    goPositionWF :function (i){ this.changeElement('position',parseInt(i)); this.positionVignette();}, 
    // Le slideshow recule suivant un nombre d'elements demand�es, et  r�alise une animation
    goNext : function(nb, e) { 
      	// On modifie l'Element en cours
    	var ret = this.changeElement('next',nb);
    	// Si changement ok
		if(ret){ 
			this.clearFocus();	this.positionVignette(e); this.focusVignette();
			// R�percuter next sur le slideshow des thumbnails 
    		if (this.settings.has_thumbnails && this.thumbnails){ this.thumbnails.goPagePosition(this.getCurrentIndex()); }
    		if (this.timeout){ this.play();}
    	}else if (this.settings.auto_load ){ // Si diaporama edito auto load, et qu'il ne trouve pas le suivant on envoie sur la page de listing
    		$(location).attr('href','/diaporama/');
    	}
   },
   // Le slideshow recule suivant un nombre d'elements demand�es, et r�alise une animation
   goPrev : function(nb, e) { 
    
    	// On modifie l'Element en cours
    	var ret = this.changeElement('prev',nb);
    
    	if (ret){
	    	this.clearFocus();	this.positionVignette(e); this.focusVignette();
	    	// R�percuter sur le slideshow des thumbnails 
    		if (this.settings.has_thumbnails && this.thumbnails){this.thumbnails.goPagePosition(this.getCurrentIndex());}
    	} 
   },
   // Aller sur la page pr�cedente (sp�cifique au thumbnails)
    goPagePrev : function (){
    	// goPagePrev // On avance le viewport de plus X suivant la position actuelle du viewport
    	if ( this.settings.parent){
    		var page = Math.floor(this.getCurrentIndex() / this.settings.display)-1;
    		// Position du viewport
    		this.goPositionWF(parseInt(page*this.settings.display));
  	 	}
    },
    goPagePosition : function (index){
		
		if ( this.settings.parent){
			var page = Math.floor(index / this.settings.display);
			// Position du viewport
			this.goPosition(parseInt(page*this.settings.display));
			// Position sur le dernier l'element du viewport
			this.clearFocus();
  			this.changeElement('position',index);
  			this.focusVignette();
		}
    },
    // Aller sur la page suivante (sp�cifique au thumbnails)
    goPageNext : function (){
        if ( this.settings.parent){
    		var page = Math.floor(this.getCurrentIndex() / this.settings.display)+1;
    		this.goPositionWF(parseInt(page*this.settings.display));
    	}
    },
   // On modifie l'element en cours, (peut etre appel� en direct, ou depuis la fonction goPrev/goNext si on doit positionner le slideshow sur l'element
   changeElement: function (action,nb){
   		var ret = false;
   		if (action == 'position'){
   			ret = true;
   		}else if(this.Element.next().length && action == 'next'){ 
			ret = true;
		}else if (this.Element.prev().length && action == 'prev'){
			ret = true;
		}
		
		if (ret){
			if (nb == 1){// Si on demande la voisine
    			if (action == 'next') {this.Element = this.Element.next(); }
    			else if (action == 'prev'){this.Element = this.Element.prev(); }
    			else if (action == 'position'){this.Element = $('#'+this.settings.id+' > .ss_viewport li:eq('+nb+')');}
    		// Sinon
    		}else{
    			if (action == 'next') {
	    			var l = this.Element.nextAll();
		    		if (l.size() > nb){
		    			var i = parseInt(this.Element.attr('nav'));
		    			this.Element = $('#'+this.settings.id+' > .ss_viewport li:eq('+parseInt(i+nb)+')');// +5
		    		}
		    	}else if (action == 'prev'){
		    		var l = this.Element.prevAll();
		    		if (l.size() >= 1){
		    			var i = parseInt(this.Element.attr('nav'));
		    			var index = parseInt(i-nb);
		    			if (index < 0) index = 0;
		    			this.Element = $('#'+this.settings.id+' > .ss_viewport li:eq('+index+')');// +5
		    		}
		    	}else if (action == 'position'){
		    		this.Element = $('#'+this.settings.id+' > .ss_viewport li:eq('+nb+')');
		    	}
	    	}
	    }

	    return ret;
   },
    /**
     * Positionne le slideshow sur la vignette en cours 
     */
    positionVignette : function(e) {

    	var othis = this;
		// Chargement des images
		this.loadImage(this.Element);
		this.loadPrevImages(); this.loadNextImages();

		// D�sactiver les boutons le temps de l'animation si on est pas en mode lecture &
		// && R�activer en callback animate( properties, [ duration ], [ easing ], [ callback ] )
		if (!this.timeout) { this.desactiveButtons(); }

        // Positionnement de la photo
        this.list.animate({ left: '-'+this.getCurrentPositionX()},  this.settings.animate_duration , '', function (){  if (!othis.timeout) { othis.activeButtons();} });

		// Zoom
        this.Element.hover(
        	function(){ $(this).find('a.zoom').css('display','block');},
        	function(){$(this).find('a.zoom').css('display','none');}
        );
        	
        // Mise � jour des informations: Titre / Cr�dit / L�gende / Page en cours 
        // Si ce n'est pas une miniature d'un edito sans recharchegement auto
        if(!this.settings.parent && (!this.settings.edito || this.settings.auto_load)){
			this.title.html(this.Element.find('h2.ssp_titre').html());
	        this.credit.html('Cr&eacute;dit : '+(this.Element.find('span.ssp_credit').html()!=''?this.Element.find('span.ssp_credit').html():'DR'));
	      	this.pcurrent.html(parseInt(this.Element.attr('nav'))+1);
        	
        	// Si le slideshow poss�de des l�gendes
        	if (this.settings.legend){
        		// Si le slideshow poss�de des l�gendes pars�es
	        	if (this.settings.parse_legend){

                    var legend = this.allparselegend.find('.ss_pl'+this.Element.attr('nav')).html();
                    if ((typeof legend != undefined) && legend !== null){
                        legend = Utils.htmlspecialchars_decode(legend);
                        this.legend.html(legend);
                    }
	        	}else{ // Autrement des l�gendes normales
	        		 this.legend.html(this.Element.find('span.ssp_legend').html());
		        }
		   	}
		   	if (this.settings.size != 'mobile' && this.settings.auto_load && this.settings.edito && !this.firstload){
        		// ne pas rafraichir la pub au premier chargement
        		if(typeof refreshAds == 'function') { 
        			refreshAds();
        		}
        		if(typeof refreshTags == 'function') { 
                    refreshTags();
                }
        		// On enregistre les stats d'affichage pour les "Editos"
                $.ajax({
                    url: "/api/slideshow/ajax/count.php?id="+this.settings.index+"&type=diaporama",
                    cache: false
                });
        	}else{
        		this.firstload = false;
        	}
        }
        this.toggleButtons();
    },
    
    /**
     * Charge une image dans le DOM
     */
    loadImage : function(elt) { 
    	var othis = this;
    	var lia = elt.find('a.ss_aimg');
    	
		if (!lia.has('img').length || elt.hasClass('load')){
			
        	if (!lia.has('img').length){
        		lia.html($('<img />',{'src': lia.attr('rel'), 'class':'ss_img', alt:lia.attr('title'), title:lia.attr('title')}));
            }
            
            elt.removeClass('load');
            if (!this.settings.parent){
              
            	if (!this.settings.urlPage && this.settings.size == 300){
            		lia.click(function(e){othis.goNext(1); e.preventDefault(); });
            	}
            }else{
             	// Si slideshow miniatues, on envoie sur la grande image
             	var parent = othis.settings.parent;
             	if (parent.settings.auto_load || !parent.settings.edito){
            		lia.click(function(e){othis.clearFocus(); othis.changeElement('position',elt.attr('nav')); othis.focusVignette(); parent.goPosition(elt.attr('nav'));  e.preventDefault(); });
            	}
            	// Si non c'est le lien href existant qui est pris en compte
            }
        }
        
    },
     /**
     * Chargement des images pr�cedentes si besoin
     */
    loadPrevImages: function(){ 
    	var i = 0;
    	var cprev = this.Element.prev();
    	while(cprev.length && i < this.settings.nb_img_load){
        	this.loadImage(cprev);
        	cprev = cprev.prev();
        	i++;	
        }
    },
    /**
     * Chargement des images suivantes si besoin
     */
    loadNextImages: function(){ 
    	var i = 0;
    	var cnext = this.Element.next();
    	while(cnext.length && i < this.settings.nb_img_load){
        	this.loadImage(cnext); cnext = cnext.next(); i++;	
        }
    },
    /**
     * R�active les boutons apr�s une animation 
     */
    activeButtons : function (){ 
       
        this.actionButtonPrev(); this.actionButtonNext(); this.actionButtonFirst(); this.actionButtonLast();
    },
    /**
     * D�sactive les boutons pendant une animation 
     */
    desactiveButtons : function (){ 
		this.bprev.unbind('click');	this.bnext.unbind('click'); 
		if (this.settings.page_first){ this.bfirst.unbind('click');  }
		if (this.settings.page_last){ this.blast.unbind('click'); }
    },
    /**
     * Action sur le bouton first
     */
    actionButtonFirst : function (){
   	 	if (this.settings.page_first){ 
   	 		if (!this.settings.parent){ // Si slideshow principal
	   	 		if (this.settings.urlPage){ // Si il existe un url -- on permet sur click normal onclick, et sur click droit d'ouvrir une page
        			// On remplit l'url avec l'url existante dans les miniatures
        			this.bfirst.attr('href',this.settings.page_first);
	        	}
	        	var othis = this;
	        	this.bfirst.click(function(e){ othis.goFirst(e);  e.preventDefault();}); 
	        }
   	 	}
    },
    /**
     * Action sur le bouton first
     */ 
    actionButtonLast : function (){
   	 	if (this.settings.page_last){ 
   	 		if (!this.settings.parent){ // Si slideshow principal
	   	 		if (this.settings.urlPage){ // Si il existe un url -- on permet sur click normal onclick, et sur click droit d'ouvrir une page
        			// On remplit l'url avec l'url existante dans les miniatures
        			this.blast.attr('href',this.settings.page_last);
	        	}
	        	var othis = this;
	        	this.blast.click(function(e){ othis.goLast(e);  e.preventDefault();}); 
	        }
   	 	}
    },
    /**
     * Action sur le bouton pr�cedent
     */ 
    actionButtonPrev : function (){    	
    	var othis = this;
    	if (!this.settings.parent){ // Si slideshow principal
			if (this.settings.urlPage){ // Si il existe un url -- on permet sur click normal onclick, et sur click droit d'ouvrir une page
        		if (this.thumbnails.Element){
        			// On remplit l'url avec l'url existante dans les miniatures
        			this.bprev.attr('href',this.thumbnails.Element.prev().find('.ss_aimg').attr('href'));
        		}
        	}
        	this.bprev.click(function(e){ e.stopImmediatePropagation(); othis.goPrev(1);  e.preventDefault(); });
    	
		}else{ // Si thumbnails
		      this.bprev.click(function(e){ othis.goPagePrev();}); 
		}
    },
    /**
     * Action sur le bouton suivant
     */
    actionButtonNext : function (){
   	 	var othis = this;
   	 	
   	 	if (!this.settings.parent){ // Si slideshow principale
   	 		if (this.Element.next().length){ // S'il existe une image suivante
				if (this.settings.urlPage){ // S'il existe une url -- on permet sur click normal onclick, et sur click droit d'ouvrir une page
	        		if (this.thumbnails.Element){
	        			// On remplit l'url avec l'url existante dans les miniatures
	        			this.bnext.attr('href',this.thumbnails.Element.next().find('.ss_aimg').attr('href'));
	        		}
	        	}
	        	this.bnext.click(function(e){ e.stopImmediatePropagation(); othis.goNext(1);  e.preventDefault(); });
	        }else if (this.settings.edito && this.settings.auto_load && this.settings.redirect_to_list ){ // si pas d'image suivante mais diaporama edito en auto load, on ajoute une url sp�cial
	        	this.bnext.attr('href',this.settings.redirect_to_list);
	        }
        	
		}else{ // Si thumbnails
			this.bnext.click(function(e){ othis.goPageNext();}); 
		}
    },    
    /**
     * Initialise les boutons
     */
    setButtons: function () { 
    	// Bouton play/stop
    	var othis = this;
        $('#'+this.settings.id+' #ss_auto'+this.settings.index).click(function(obj,e){        		
        		if ($('#'+this.id).hasClass('ss_read')){
        			othis.play(); 
        			$('#'+this.id).addClass('ss_stop'); 
	        		$('#'+this.id).removeClass('ss_read'); 
	        		$('#'+this.id).html('Arr�ter le diaporama'); 
	        	}else{
	        		othis.stop(); 
	        		$('#'+this.id).addClass('ss_read');  
	        		$('#'+this.id).removeClass('ss_stop'); 
	        		$('#'+this.id).html('Lancer le diaporama'); 
	        	}
        });
        // Supprimer les buttons s'ils existent sans etre appel�s
        if (!this.settings.page_first){ $('#'+this.settings.id+' > .ss_pagination  a').remove('.ss_first') };
        if (!this.settings.page_last){ $('#'+this.settings.id+' > .ss_pagination  a').remove('.ss_last') };
    }, 
     /**
     * Affiche ou Cache les boutons
     */
    toggleButtons : function() { 
    	
    	var prev = false;
    	// Recherche du pr�cedent
    	if (this.settings.display == 1){
	    	prev = this.Element.prev(); 
    	}else{
			var l = this.Element.prevAll();
    		if (l.size() >= 1){
    			var i = parseInt(this.Element.attr('nav'));
    			var index = parseInt(i-this.settings.display);
    			if (index < 0) index = 0;
    			prev = $('#'+this.settings.id+' > .ss_viewport li:eq('+index+')');// -X
    		}
    	}
    
    	// Affichage ou non du bouton pr�c�dent
    	if (!prev.length){ 
    		this.bprev.hide();
    		if (this.settings.page_first) { this.bfirst.hide(); }
    	}else{
    		this.bprev.show();
    		if (this.settings.page_first) { this.bfirst.show(); }
    	}
    	
    	var next = false;
    	// Recherche du suivant
    	if (this.settings.display == 1){
	    		next = this.Element.next(); 
    	}else{
    		var l = this.Element.nextAll();
			if (l.size() > this.settings.display-1){
				var i = parseInt(this.Element.attr('nav'));
    			next = $('#'+this.settings.id+' > .ss_viewport li:eq('+parseInt(i+this.settings.display)+')');// +X
    		}
    	}
    	
    	// Affichage ou non du bouton suivant
        if (!next.length){ 
        	// Si le diaporama n'est pas en edito auto load ou s'il n'a pas de lien de redirection vers un listing, on cache
        	if (!this.settings.auto_load || !this.settings.redirect_to_list) {this.bnext.hide(); } 
        	if (this.settings.page_last) { this.blast.hide(); }
        } else{
        	this.bnext.show();
        	if (this.settings.page_last) { this.blast.show(); }
        }
    },
    /**
     * Param�trage les dimensions :  Calcul de la taille du viewport et des images
     */
    setDimensions : function(){
    	// Si Slideshow classique
		if (!this.settings.parent){
			this.viewport_width = parseInt(this.viewport.css('width'));
			this.image_width = parseInt(this.viewport_width / this.settings.display);

		// Child Slideshow "imbriqu� miniatures"
		}else{
			// Param�tres des miniatures - Slideshow avec des propri�t�s sp�cifiques
			this.viewport_width = parseInt(this.viewport.css('width'));
			var li =$('#'+this.settings.id+' .ss_main li');
			this.image_width = parseInt(li.css('width'))+parseInt(li.css('padding-left'))+parseInt(li.css('padding-right'));
		}
    }
};

/**
 * Autocomplete
 */
 
$(document).ready(function(){

    var sav = {
        init : function init(){
            $('#category').change(function() {
                $('#titreQuestionSAV').val($(this).val());
            });
            
            $('#buttonAskQuestion').live('click', function(e) {
                $.facebox.close();
                $.facebox({
                    url: '/sav/askQuestion.php',
                    post: { 
                        id_jeu :     $('#idJeuHidden').val(),
                        titre :      $('#titreQuestionSAV').val()/*,
                        anonyme :    (!getCookie('nfuserid') ? true : false)*/
                    },
                    titre: $('#titreQuestionSAV').val(),
                    id: 'askQuestion'
                });
            });
            
            $('#suggestbtn input').live('click', function(e) {
                e.preventDefault();
                var idJeu = $('#idJeuHidden').val() != '' ?  parseInt($('#idJeuHidden').val()) : 0, 
                    support = $('#supportForumHidden').val(), 
                    titreQuestion = $('#titreQuestionSAV').val(),
                    errorCss = {'color' : '#F43D3D', 'text-shadow' : '0 0 2px #000'}, 
                    errorDie = false;
                
                Encoder.EncodeType = "entity";
                titreQuestion = Encoder.htmlEncode(titreQuestion);
                
                $('#anonymeEmail label, #textAcceptQuestion, #zoneTitreJeu label, label[for=titreQuestion]').css({'color':'#FFF','text-shadow':'none'});
               
               
                if(idJeu <= 0 || $('#idJeuHidden').val() == ''){
                    $('#zoneTitreJeu label').css(errorCss);
                    errorDie = true;
                }
                
                if(titreQuestion.length <= 3){
                    $('label[for=titreQuestion]').css(errorCss);
                    errorDie = true;
                }
                
                if($('#acceptQuestion').attr('checked') == false){
                    $('#textAcceptQuestion').css(errorCss);
                    errorDie = true;
                }
                
                if ($('#anonymePost').is(':visible')){
                    if ($('#acceptEmail').attr('checked') && !/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/.test($('#anonymeEmailInput').val())) {
                        $('#anonymeEmail label').css(errorCss);
                        errorDie = true;
                    }
                }
                
                $.post('/api/forum/ajax.php?act=checkInsults', { content: titreQuestion }, function(content){
                    if(content == 'found'){
                        $.facebox.alert('<strong>Votre message contient un mot � caract�re insultant.<br />Merci de le corriger pour pouvoir publier votre message.</strong><br /><a href="/api/creer_un_compte.php" style="color:#016683 !important"><u>En devenant membre</u></a>, vous ne serez pas soumis � ce type de filtre.', 8);
                    }else{
                        if (errorDie == false && idJeu > 0 && support.length > 0 && titreQuestion.length > 3) {
                            $.facebox({
                                url: '/sav/searchQuestion.php',
                                post: { 
                                    id_jeu :        idJeu,
                                    displayall :    true,
                                    titre :         titreQuestion,
                                    question:       true
                                },
                                titre: 'R�sultats de la recherche'
                            });
                        }
                    }
                });
            });
        }
    };
    
    sav.init();

    $('#titreJeuSAV').keyup(function(){
        var keys = $(this).val(), i = 0;
        if(keys.length > 2){
            $.ajax({
                url: '/ajax.php?action=autocomplete',
                type: 'POST',
                data: {
                    key : keys,
                    mode : 'sav'
                },
                success: function(res){
                    $('#suggestSAVGame').html(res).show();
                }
            });
        }else{
            $('#suggestSAVGame').html('').hide();
            $('#selectedSAVGame').html('');
            $('#supportForumHiddenn #idJeuHidden').val('');
        }
    });
    $('.SAVGamesplus').live('click', function(){
        $('#suggestSAVGames > li').each(function(){
            $('.SAVGamesplus').hide();
            $(this).show();
        });
    });
    $('.itemGame').live('click', function() {
        var tmp = $(this).attr('rel').split('|');
        $('#idJeuHidden').val(tmp[0]);
        $('#supportForumHidden').val(tmp[3]);
        $('#selectedSAVGame').html('<img src="'+tmp[2].replace('"', '\\"')+'" alt="'+tmp[1]+'" /><p>'+tmp[1]+'</p><a href="#" id="changeSAVGame">(Changer de jeu)</a>');
        $('#suggestSAVGame').html('').hide();
        $('#zoneTitreJeu').hide();
        return false;
    });
    $('#changeSAVGame').live('click', function() {
        $('#selectedSAVGame').html('');
        $('#idJeuHidden, #supportForumHidden').val('');
        $('#zoneTitreJeu').show();
        $('input#titreJeuSAV').val('').focus();
        return false; 
    });
    $('#formSAV').submit(function(){
        checkSavForm();
        return false;
    });
    
    $('#btnSearchTips').live('click', function() {
        checkSavSearch();
        return false;
    });
});

function checkSavForm(){
}

function checkSavSearch(){
    var errorDie = false;
    var idJeu = $('#idJeuHidden').val() != '' ?  parseInt($('#idJeuHidden').val()) : 0;
    var support = $('#supportForumHidden').val(), text = $('#searchTips').val();

    if(idJeu <= 0 || idJeu == ''){
        errorDie = true;
    }
    if(text.length <= 3){
        errorDie = true;
        //$.facebox.alert('<strong>Votre message contient un mot � caract�re insultant.<br />Merci de le corriger pour pouvoir publier votre message.</strong><br /><a href="/api/creer_un_compte.php" style="color:#016683 !important"><u>En devenant membre</u></a>, vous ne serez pas soumis � ce type de filtre.', 8);
    }
    
    if (errorDie == false && idJeu > 0 && support.length > 0 ) {
        $.facebox({url: '/sav/searchQuestion.php',post: { id_jeu: $('#idJeuHidden').val(), displayall : true, titre: text},titre: 'R�sultats de la recherche'});
    }
}

function refreshBlockSolved(page, id_jeu, filterSelectedSubjets){
        $.ajax({
            url: '/ajax.php?action=refreshBlockSolved',
            type: 'POST',
            data: {
                page: page,
                id_jeu: id_jeu,
                selected : filterSelectedSubjets
            },
            success: function(contenu2){
                tmpDiv = filterSelectedSubjets ? '#selectedQuestion' : '#solvedQuestion';
                $(tmpDiv).html(contenu2);
                $(tmpDiv).goTo();
            }
        });
}

function refreshBlockUnsolved(page, id_jeu){
        $.ajax({
            url: '/ajax.php?action=refreshBlockUnsolved',
            type: 'POST',
            data: {
                page: page,
                id_jeu: id_jeu            
            },
            success: function(contenu2){
                $('#unsolvedQuestion').html(contenu2);
                $('#unsolvedQuestion').goTo();
            }
        });
}


$(document).ready(function(){(function(){getCookie("nfuserid")||($("#anonymeLoginInput").defaultValue("Anonyme"),$("#anonymePost").show());$(document).delegate("#boutonEnvoisQuestion","click",function(){var c=$.trim($("#titreQuestionSAV").val()),e=$.trim($("#detailsQuestion").val()),d=$("#supportForumHidden").val(),a=!1,f={color:"#F43D3D","text-shadow":"0 0 2px #000"};$("#acceptEmail").attr("checked");var h=$("#acceptEmail").attr("checked")||getCookie("nfuserid")?"true":"false",k=getCookie("nfuserid")?
"":$("#anonymeLoginInput").val(),l=getCookie("nfuserid")||""==$("#anonymeEmailInput").val()?"":$("#anonymeEmailInput").val(),m=getCookie("nfuserid")?!1:!0,b=""!=$("#idJeuHidden").val()?parseInt($("#idJeuHidden").val()):0;$("#anonymePost").is(":visible")&&$("#acceptEmail").attr("checked")&&!/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/.test($("#anonymeEmailInput").val())&&($("#anonymeEmail label").css(f),a=!0);0==$("#acceptQuestion2").attr("checked")&&($("#textAcceptQuestion2 label").css(f),
a=!0);if(0==a){$.facebox.startLoading();var g=d+":fiche jeux:"+b;$.ajax({url:"/api/forum/ajax.php?act=poster_message",type:"POST",dataType:"html",data:{api_mode:"question",titre:c,txt:e,forum:d,fiche:g,id_fiche:b,type_fiche:"fiche jeux",redirect:"true",anonyme:m,notify:h,pseudo:k,email:l},success:function(a){Utils.setCookie("questionSavId",a,Utils.strtotime("+10 min"),"/",".jeuxvideo.fr");$.ajax({url:"/ajax.php?action=finQuestionSav",type:"POST",data:{titre:c,forum:d,fiche:g,id_fiche:b,type_fiche:"fiche jeux"},
success:function(){Utils.setCookie("questionSavTitre",b+"-"+c,Utils.strtotime("+5 min"),"/",".jeuxvideo.fr");Utils.setCookie("questionSavMessage",e,Utils.strtotime("+5 min"),"/",".jeuxvideo.fr");window.location="/sav/question-enregistree"}})}})}})})()});


Collection=function(a){this.initialize(a)};
Collection.prototype={id_user:0,games:[],callbacks:null,initialize:function(a){this.id_user=a;this.callbacks=new Collection_Callbacks(this)},setGames:function(a){for(var b in a)if("function"!=typeof a[b]){var c=new Collection_Game(this,a[b]);c instanceof Collection_Game&&0!=c.id&&this.pushGame(c)}},load:function(a,b){if(this.logged()){"number"!=typeof a&&(a=-1);typeof b!=typeof $.noop&&(b=$.noop);var c=this;$.post("/ajax.php?action=collection-load",{id_user:this.id_user,partial:a},function(a){a.error||
c.setGames(a.games);b.call(this,""!==a.error)},"json")}},addGame:function(a,b){typeof b!=typeof $.noop&&(b=$.noop);var c=this;$.post("/ajax.php?action=collection-add",{id:a,id_user:this.id_user},function(a){a.error?b.call(this,!1,a.error):(a=new Collection_Game(c,a.game),c.pushGame(a),c.callbacks.execute("add",a),b.call(this,!0))},"json")},pushGame:function(a){var b=this;a.onRemove(function(a){var d=b.indexOf(a.datas.id);delete b.games[d];b.games.splice(d,1);b.callbacks.execute("remove",a)});this.callbacks.execute("push",
a);this.games.push(a)},exists:function(a){for(var b in this.games)if(this.games[b].datas&&this.games[b].datas.id==a)return!0;return!1},indexOf:function(a){for(var b in this.games)if(this.games[b].datas.id==a)return b;return-1},logged:function(){return 0<this.id_user},onPush:function(a){this.callbacks.add("push",a)},onAdd:function(a){this.callbacks.add("add",a)},onRemove:function(a){this.callbacks.add("remove",a)}};Collection_Game=function(a,b){this.initialize(a,b)};
Collection_Game.prototype={callbacks:null,collection:null,datas:null,initialize:function(a,b){if(!1===a instanceof Collection)throw"Collection_Game.initialize() : collection is not a Collection object";this.callbacks=new Collection_Callbacks(this);this.collection=a;this.datas=b},setDatas:function(a){this.datas=a;return this},load:function(){var a=this;$.post("/ajax.php?action=collection-game",{id:this.datas.id,id_user:this.collection.id_user},function(b){b.error?alert(b.error):(a.datas=b,a.callbacks.execute("change"))},
"json");return this},change:function(a,b){typeof b!=typeof $.noop&&(b=$.noop);if(a==this.datas.id)b.call(this,!1);else{var c=this;$.post("/ajax.php?action=collection-change",{id_user:this.collection.id_user,old:this.datas.id,"new":a},function(a){a.error?(alert(a.error),b.call(this,!1)):(b.call(this,!0),c.datas=a.game,c.callbacks.execute("change"))},"json");return this}},note:function(a,b){typeof b!=typeof $.noop&&(b=$.noop);var c=this;$.post("/ajax.php?action=collection-note",{id_user:this.collection.id_user,
id_jeu:this.datas.id,note:a},function(a){a.error?(alert(a.error),b.call(this,!1)):(b.call(this,!0),c.datas=a.game)},"json");return this},remove:function(){var a=this;$.post("/ajax.php?action=collection-remove",{id:this.datas.id,id_user:this.collection.id_user},function(b){b.error?alert(b.error):a.callbacks.execute("remove",a)},"json");return this},onChange:function(a){this.callbacks.add("change",a)},onRemove:function(a){this.callbacks.add("remove",a)}};Collection_Callbacks=function(a){this.initialize(a)};
Collection_Callbacks.prototype={context:null,callbacks:null,initialize:function(a){"undefined"==typeof a&&(a=this);this.context=a;this.callbacks={}},add:function(a,b){"undefined"==typeof this.callbacks[a]&&(this.callbacks[a]=[]);this.callbacks[a].push(b)},execute:function(a){if("undefined"!=typeof this.callbacks[a]){for(var b=[],c=0;c<arguments.length;c++)0<c&&b.push(arguments[c]);for(c in this.callbacks[a])this.callbacks[a][c].apply(this.context,b)}}};


Collection_Btn=function(a){this.initialize(a)};Collection_Btn.collection=null;Collection_Btn.ready=!1;Collection_Btn.instances=[];
Collection_Btn.prototype={$:null,datas:null,supports:null,members:null,loading:!1,opened:!1,disabled:!1,initialize:function(a){Collection_Btn.instances.push(this);this.checkCollection();this.datas=a;this.members=new Collection_Btn_Members(this);this.render()},checkCollection:function(){null===Collection_Btn.collection&&(Collection_Btn.collection=new Collection(Utils.getCookie("nfuserid")),Collection_Btn.collection.loading=!1);!Collection_Btn.collection.logged()||Collection_Btn.ready||Collection_Btn.collection.loading||
(Collection_Btn.collection.loading=!0,Collection_Btn.collection.load(0,function(a){for(var b in Collection_Btn.instances)Collection_Btn.ready=!0,Collection_Btn.collection.loading=!1,"function"===typeof Collection_Btn.instances[b].update&&Collection_Btn.instances[b].update()}))},add:function(a){if(!this.disabled&&!this.loading){var b=this;Collection_Btn.collection.logged()?(this.load(),Collection_Btn.collection.addGame(a,function(a,d){b.load(!0);a?b.thanks():b.error(d)})):$.facebox({url:"/api/membre/facebox.login.php",
titre:"Vous devez vous connecter",callbacks:{success:function(){Collection_Btn.collection.id_user=Utils.getCookie("nfuserid");b.checkCollection();b.add(a);$.facebox.close()}}})}},error:function(a){if(!this.disabled&&!this.loading){var b=this,c=this.$.find(".btn"),d=c.text();this.disable();this.$.addClass("error");c.text(a);setTimeout(function(){c.text(d);b.$.removeClass("error");b.enable()},3E3)}},toggle:function(){this.opened?this.close():this.open()},open:function(){this.disabled||this.loading||
this.opened||(this.$.addClass("opened"),this.opened=!0)},close:function(){this.opened&&(this.$.removeClass("opened"),this.opened=!1)},load:function(a){"boolean"==typeof a&&a&&this.loading?(this.$.removeClass("loading"),this.loading=!1):this.loading||(this.$.addClass("loading"),this.loading=!0)},enable:function(){this.disabled&&!this.loading&&(this.$.removeClass("disabled"),this.disabled=!1)},disable:function(){this.disabled||this.loading||(this.close(),this.$.addClass("disabled"),this.disabled=!0)},
thanks:function(){if(!this.disabled&&!this.loading){this.disable();this.$.find(".btn").text("Ajout\u00e9");this.$.find(".count .txt").text(this.datas.count+"+1");var a=this;setTimeout(function(){a.$.find(".btn").text("G\u00e9rer ma collection").unbind("click").click(function(a){window.location="/forum/profil.php"});a.renderCount(parseInt(a.datas.count)+1)},3E3)}},exists:function(){this.disabled||this.loading||(this.disable(),this.$.find(".btn").text("D\u00e9j\u00e0 ajout\u00e9").unbind("click").click(function(a){window.location=
"/forum/profil.php"}))},update:function(){if(Collection_Btn.ready&&Collection_Btn.collection.logged())if(1<this.datas.supports.length)for(var a in this.datas.supports){if(Collection_Btn.collection.exists(this.datas.supports[a].id)){this.exists();break}}else Collection_Btn.collection.exists(this.datas.supports[0].id)&&this.exists()},render:function(){var a;a='<div class="collection-btn">\t<a class="btn" href="javascript:;">Ajouter \u00e0 ma collection</a>';a+='\t<div class="bull count">';a+='\t\t<div class="arrow"></div>';
a+='\t\t<div class="txt">'+this.datas.count+"</div>";a+="\t</div>";a+='\t<div class="bull loading">';a+='\t\t<div class="arrow"></div>';a+='\t\t<div class="txt">&nbsp;</div>';a+="\t</div>";a+="</div>";this.$=$(a);this.renderCount(this.datas.count);var b=this;$(document).click(function(a){$(a.target).closest(".collection-btn").length||b.close()});1<this.datas.supports.length?(this.supports=new Collection_Btn_Supports(this.datas.supports),this.supports.onClick=function(a){b.add(b.datas.supports[a].id)},
this.$.append(this.supports.$),this.$.find(".btn").click(function(a){a.preventDefault();b.toggle()})):this.$.find(".btn").click(function(a){a.preventDefault();b.add(b.datas.supports[0].id)});this.update()},renderCount:function(a){var b=this,c=1<this.datas.count?this.datas.count+" utilisateurs poss\u00e8dent ce jeu":1==this.datas.count?"1 utilisateur poss\u00e8de ce jeu":"Aucun utilisateur poss\u00e8de ce jeu";0<a?this.$.find(".count .txt").html('<a href="javascript:;" title="'+c+'">'+a+"</a>").find("a").click(function(a){a.preventDefault();
b.members.hide();b.members.show()}):this.$.find(".count .txt").html('<span title="'+c+'">0</span>')}};Collection_Btn_Supports=function(a){this.initialize(a)};
Collection_Btn_Supports.prototype={$:null,list:null,count:0,initialize:function(a){this.list=a;this.render()},render:function(){var a;a='<div class="bull supports">\t<div class="arrow"></div>';a+='\t<div class="txt">';for(var b in this.list)a+='\t<a href="javascript:;">'+this.list[b].name+"</a>";a+="\t</div>";a+="</div>";this.$=$(a);var c=this;this.$.find("a").each(function(a){$(this).click(function(b){b.preventDefault();c.onClick(a)})})},disabled:function(){return this.count==this.list.length},disable:function(a){a=
this.indexOf(a);0>a||(this.$.find(".txt > *:eq("+a+")").unbind().replaceWith("<span>"+this.list[a].name+"</span>"),this.count++)},indexOf:function(a){for(var b in this.list)if(this.list[b].id==a)return b;return-1},onClick:function(a){}};Collection_Btn_Members=function(a){this.initialize(a)};
Collection_Btn_Members.prototype={$:null,btn:null,sb:null,filters:null,shawn:!1,initialize:function(a){this.btn=a;this.filters={}},create:function(){if(null===this.$){var a=this,b;b='<div class="collection-btn-members" style="display:none">\t<div class="cbm-arrow"><span></span></div>';b+='\t<a class="cbm-close" href="javascript:;">Fermer</a>';b+='\t<div class="cbm-content"><div style="display:none">';b+='\t\t<div class="cbm-top">';b+="\t\t\t<p>Membres ayant ajout\u00e9 "+this.btn.datas.title+" \u00e0 leur collection</p>";
b+="\t\t</div>";b+='\t\t<div class="cbm-list">Chargement...</div>';b+="\t</div></div>";b+="</div>";this.$=$(b);if(1<this.btn.datas.supports.length){this.sb=new Collection_Btn_Selectbox;this.sb.setBlankField("Tous supports");this.sb.onChange=function(b){b.key?a.filters.game=b.key:"undefined"!==typeof a.filters.game&&delete a.filters.game;a.load()};for(var c in this.btn.datas.supports)b=this.btn.datas.supports[c],this.sb.fields.add(new Collection_Btn_Selectbox_Field(b.id,b.name));this.$.find(".cbm-top").prepend(this.sb.render())}this.$.appendTo(this.btn.$.find(".bull"));
this.$.find(".cbm-close").click(function(b){b.preventDefault();a.hide()});$(document).click(function(b){$(b.target).closest(".collection-btn-members").length||a.hide()})}},show:function(){if(!this.shawn){this.btn.load();this.create();var a=this;this.load(1,function(b){if(b){a.btn.load(!0);a.shawn=!0;b=$(document).width();var c=a.btn.$.find(".bull"),d=c.width(),c=c.offset().left+Math.floor(d/2)+5;c<=b/2?(b=Math.max(0,(b-1E3)/2-(c-620)),a.$.find(".cbm-content").css("margin-left","-"+(600-b)+"px"),a.$.find(".cbm-close").css({right:0,
left:"auto","margin-left":"0"})):(b=Math.min(0,1E3+(b-1E3)/2-(c+620)),a.$.find(".cbm-content").css("margin-left","-"+(200-b)+"px"),a.$.find(".cbm-close").css({right:"auto",left:0,"margin-left":"-"+(200-b)+"px"}));a.$.fadeIn("fast",function(){a.$.find(".cbm-content > div").slideDown("fast")});this.btn.$.find(".bull.count").css("z-index",this.btn.$.find(".bull.count").css("z-index")+1)}})}},hide:function(){this.shawn&&(this.shawn=!1,this.$.hide().find(".cbm-content > div").hide(),this.btn.$.find(".bull.count").css("z-index",
this.btn.$.find(".bull.count").css("z-index")-1))},getFilters:function(){filters={games:[]};if("undefined"!==typeof this.filters.game)filters.games.push(this.filters.game);else for(var a in this.btn.datas.supports)filters.games.push(this.btn.datas.supports[a].id);return filters},load:function(a,b){"undefined"==typeof a&&(a=1);"function"!==typeof b&&(b=$.noop);var c=this,d=this.getFilters();d.page=a;$.post("/ajax.php?action=collection-members",d,function(d){d.e?$.facebox.alert(d.e,function(){b.call(c,
!1)}):(d.page=a,c.render(d),b.call(c,!0))},"json")},render:function(a){var b="";0==a.t?b+='<div class="cbm-empty">Aucun membre n\'\u00e0 \u00e9t\u00e9 trouv\u00e9</div>':(b+=this.renderMembers(a.m),b+=this.renderNavigation(a.page,a.t));this.$.find(".cbm-content .cbm-list").html(b);var c=this;this.$.find(".cbm-nav a").click(function(a){a.preventDefault();c.load($(this).attr("href").substr(1))})},renderMembers:function(a){Utils.getCookie("nfusername");var b="",c;for(c in a){var d=a[c],e=/ \(moi\)$/.test(d.l);
"object"==typeof d&&(b+='<div class="cbm-member"><div>',b+='\t<img src="/api/img/pixel.gif" style="background-image:url('+d.a+')" />',b+='\t<p class="l"><a href="'+d.p+'">'+d.l+"</a></p>",b+='\t<p class="s"><span></span> '+d.s+"</p>",b+='\t<p class="c"><a href="'+d.p+'">Voir '+(e?"ma":"sa")+" collection</a></p>",d.mp&&!e&&(b+='<p class="mp"><a href="'+d.mp+'">Envoyer un MP</a></p>'),b+="</div></div>")}return b+'<div class="clearer"></div>'},renderNavigation:function(a,b){a=parseInt(a);b=parseInt(b);
var c=Math.ceil(b/20),d="",e=Math.max(1,Math.min(a,c-3)),c=Math.min(a+3,c);if(20<b){d+='<div class="cbm-nav">\t<b>Page :</b>';for(1<e&&(d+='<a href="#1">1</a>'+(2<a?"<b>...</b>":""));e<=c;e++)d=e==a?d+("<span>"+e+"</span>"):d+('<a href="#'+e+'">'+e+"</a>");d+="</div>"}return d}};Collection_Btn_Selectbox=function(a){this.initialize(a)};Collection_Btn_Selectbox.count=0;
Collection_Btn_Selectbox.prototype={$:null,id:0,fields:null,opened:!1,disabled:!1,initialize:function(a){this.id=Collection_Btn_Selectbox.count++;this.fields=new Collection_Btn_Selectbox_Fields(a);this.$=$('<div class="cbm-selectbox cbm-selectbox'+this.id+'"></div>');var b=this;this.fields.onSelect=function(a){b.select(a)};$(document).click(function(a){$(a.target).closest(".cbm-selectbox"+b.id).length||b.close()})},onChange:function(){},enable:function(){this.disabled&&this.$.show();this.disabled=
!1},disable:function(){this.disabled||this.$.hide();this.disabled=!0},toggle:function(){this.opened?this.close():this.open();return this},close:function(){this.opened&&(this.$.removeClass("open"),this.opened=!1);return this},open:function(){this.opened||(this.$.addClass("open"),this.opened=!0);return this},cancel:function(){this.fields.setCurrent(this.fields.defaut);this.$.find(".cbm-sb-selected").text(this.fields.defaut.value)},select:function(a){this.fields.setCurrent(a)&&(this.$.find(".cbm-sb-selected").text(a.value),
this.onChange(a));this.close();return this},setBlankField:function(a){a=new Collection_Btn_Selectbox_Field("",a);a.blank=!0;this.fields.add(a)},setFields:function(a){this.fields.setFields(a)},addField:function(a,b){this.fields.add(new Collection_Btn_Selectbox_Field(a,b))},removeField:function(a){return this.fields.remove(a)},render:function(){var a;a='<div class="cbm-sb-arrow"><span></span></div>'+('<div class="cbm-sb-selected">'+this.fields.current.value+"</div>");this.$.html(a);this.$.append(this.fields.$);
var b=this;this.$.find(".cbm-sb-arrow").click(function(){b.toggle()});return this.$}};Collection_Btn_Selectbox_Fields=function(a){this.initialize(a)};
Collection_Btn_Selectbox_Fields.prototype={$:null,fields:null,defaut:null,current:null,index:-1,initialize:function(a){this.$=$('<div class="cbm-sb-list"></div>');this.fields=[];this.setFields(a)},setFields:function(a){for(var b in a)this.add(new Collection_Btn_Selectbox_Field(b,a[b]));return this},setDefault:function(a){!1===a instanceof Collection_Btn_Selectbox_Field&&(a=this.get(a));this.current=this.defaut=a;return this},setCurrent:function(a){!1===a instanceof Collection_Btn_Selectbox_Field&&
(a=this.get(a));if(!this.exists(a.key)||this.current.key==a.key)return!1;this.current=a;return!0},add:function(a){if(!this.exists(a.key)){var b=-1,c;for(c in this.fields){if(a.blank){b=-1;break}if(!this.fields[c].blank&&a.value<this.fields[c].value){b=c-1;break}b=c}0>b?this.$.prepend(a.$):a.$.insertAfter(this.fields[b].$);var d=this;a.onClick=function(a){d.onSelect(a)};null===this.defaut&&this.setDefault(a);this.push(a,b+1)}},remove:function(a){var b=this.indexOf(a);if(0>b)return!1;this.fields[b].$.remove();
delete this.fields[b];this.fields.splice(b,1);if(a==this.current.key)this.onSelect(this.fields[0]);return!0},push:function(a,b){"number"!=typeof b||0==this.fields.length?this.fields.push(a):0>b?this.fields.unshift(a):this.fields.splice(b,0,a)},get:function(a){for(var b in this.fields)if(a==this.fields[b].key)return this.fields[b];return!1},exists:function(a){"string"!=typeof a&&(a="");return 0<=this.indexOf(a)},indexOf:function(a){var b=0,c;for(c in this.fields){if(this.fields[c].key==a)return b;
b++}return-1},fetch:function(){return++this.index==this.fields.length?(this.index=-1,!1):this.fields[this.index]},onSelect:function(a){}};Collection_Btn_Selectbox_Field=function(a,b){this.initialize(a,b)};Collection_Btn_Selectbox_Field.prototype={$:null,key:null,value:null,blank:!1,initialize:function(a,b){this.$=$('<a href="javascript:;" class="cbm-sb-item">'+b+"</a>");this.key=a;this.value=b;var c=this;this.$.click(function(a){a.preventDefault();c.onClick(c)})},onClick:function(a){}};