
var noNav = false;
var actualPage = 0;
var actualId = 0;
var documentw;
var documenth;
var VideoPlaying = false;

function loading() { 
	$('#loading').toggle();
}

// changer les thumbs d'une 'page' (glossaire ou news)
// ATTENTION : pour que ca marche les id des liens des images sont imageID, puis le tableau js doit être défini
function screenshots_Page(page) {
	actualPage = page;
	$(".intbut").css("fontWeight", "normal"); //démarquer l'ancienne
	$("#navText"+page).css("fontWeight", "bold"); //marquer la "page" actuelle
	
	for (n=0; n<screenshotsPage; n++) {
		id = page * screenshotsPage + n;

		//rermplir avec du spacer pour la dernière
		if (id > screenshotsData.length-1) {
			src = chemin+"/images/divers/spacer.gif";
			title = "";
			lnk = "#null";
		} else {
			title = screenshotsData[id][0].replace(/"/g, '&#34;');
			lnk = chemin+"/"+screenshotsData[id][1];
			src = chemin+"/"+screenshotsData[id][2];
		}

		//changer les attributs de chaque screenshot de la "page"
		//un jour ce serait bien d'enlever tous les attributs deg : commentaire / forcetitle
		$("#image"+n+" img").attr("title", title);
		$("#image"+n+" img").attr("src", src);
		$("#image"+n).attr("href", lnk);
		$("#image"+n).attr("commentaire", title); //à cause du plugin tooltip...
		$("#image"+n+" img").Tooltip({
		    track: true, 
		    delay: 300, 
		    showURL: false, 
		    extraClass: "petit"
		});
	}
}

//mettre à jour le numéro dans la navig
function majNav(id) {
	id = (id*1) + 1;
	total = screenshotsData.length;
	$("#jsNav span").html( "<table border=0><tr><td class=texte2 style='border-bottom:1px solid #888888'><b>"+ ((id<10) ? "0"+id : id) + "</b></td></tr><tr><td class=texte2>" + ((total<10) ? "0"+total : total) + "</td></tr></table>");
}

var ImageViewing = false;

//afficher une image avec le BS
function affImage(link) {
	//fermeture de la visionneuse (image + navig)
	var myCloseImage = function(hash){
		ImageViewing = false;
		hash.w.fadeOut('1000', function(){
			hash.o.remove();
		});
		$('#jsNav').fadeOut();
		nettoyer();
		//si jamais...
		if ($("#loading").css("display") != "none")
			loading();
	};

	//on connait pas l'élém au moment du changement de page
	if (typeof($(link).attr('href')) != 'undefined') {
		picComm = $(link).attr("commentaire");
		picSrc = $(link).attr('href');
	} else {
		picComm = screenshotsData[actualId][0];
		picSrc = screenshotsData[actualId][1];
		picSrc = (picSrc.substring(0, 7)=='http://') ? picSrc : chemin+'/'+picSrc;
	}

	//préparer l'image cible
	var oldLink = chemin + "/scripts/image.php?url=";
	var img = new Image();
	picSrc = (picSrc.indexOf(oldLink) != -1) ? picSrc.substring(oldLink.length, picSrc.length) : picSrc;
	picSrc.replace('%22',''); //IE...
	loading();

	//si une popup ajax a été appelée avant (bugfix)
	var myLoadImage = function(hash){
		$(img).load(function () {
			var picw = this.width*1;
			var pich = this.height*1;
			placeImage($(this), picw, pich);
		});
	};
	
	//placer au centre de l'écran
	$('#modalWindow')
		.jqm({
			target: '#jqmContent',
			onShow: myShowGallery,
			onLoad: myLoadImage,
			onHide: myCloseImage
		})
		.jqmShow();

	$(img)
		.attr('src', picSrc )
		.load(function () {
			var picw = this.width*1;
			var pich = this.height*1;

			if (picw>0 && pich>0 && !ImageViewing) {
				//fin du chargement
				ImageViewing = true;
				loading();

				//afficher la nav
				//try à cause du screenshotsData
				try {
					if (!noNav && screenshotsData.length>1) {
						majNav( actualId );
						$('#jsNav').css("opacity", 0.75).show();
					}
				}
				catch(e) {}

				placeImage($(this), picw, pich);

				//légende
				if (typeof(picComm)!='undefined' && picComm!='')
					$('#jqmContent').append('<br><div class="cell_alt texte2" style="padding:3px; text-align:center;">'+picComm+'</div>');
			}
		})
		.trigger('load')
		.error(function () {
			loading();
			alert("Cette image n'existe pas");
			$('#modalWindow').jqmHide();
			nettoyer();
		});
}

//redimmensionne l'image si picw ou pich dépasse de l'écran
function placeImage(img, picw, pich) {
	var pourcentage = 100;
	//vérifier les dimensions
	if (picw > documentw)
		pourcentage = Math.floor((documentw * 100) / picw);
	if (Math.floor((pich * pourcentage) / 100) > documenth)
		pourcentage = Math.floor((documenth * 100) / pich);
	//redimmensionner
	if (pourcentage != 100) {
		picw = Math.floor((picw * pourcentage) / 100) - 100;
		pich = Math.floor((pich * pourcentage) / 100) - 100; 
	}

	nettoyer();
	$('#jqmContent').html( img );
	$('#jqmContent img').attr('width', picw ).attr('height', pich).attr('border', '1').css('cursor', 'pointer').click(function() { $('#modalWindow').jqmHide(); });
	$('#modalWindow').css({ width: picw+"px", height: pich+"px", left: Math.floor((documentw-picw)/2)+"px", top: Math.floor((documenth-pich)/2)+"px" }).fadeIn('fast');
}

//ouverture d'une vidéo ou image
var myShowGallery = function(hash){};

$(document).ready(function(){
	documentw = $(window).width();
	documenth = $(window).height();

	//zoom class
	//try à cause de screenshotsPage qui ex. que si navig
	$("a[class^=zoom]").click(function() {
		try {
			noNav = ($(this).attr('id').substr(0,5)=='image') ? false : true; //pas d'id = pas de navig
			actualId = actualPage * screenshotsPage + parseInt($(this).attr('id').substr(5)); //imageID
		}
		catch(e) {}
		
		if ($(this).attr('href')!='#null')
			affImage( $(this) );
		return false;
	});
	
	//agrandir image
	$("#agrandir").click(function() {
		document.location = $("#jqmContent img").attr("src");
		return false;
	});

	//navig précèdent
	$("#jsNav_prev").click(function () {
		if (actualPage == 0 && actualId == 0)
			return false;
		if (actualId % screenshotsPage == 0 && actualId > 0) {
			actualPage--;
			actualId = actualPage * screenshotsPage + (screenshotsPage-1);
			screenshots_Page(actualPage);
		} else
			actualId--;

		ImageViewing = false;
		$("#jqmContent").hide();
		affImage( $('#image'+actualId) );
	});

	//navig suivant
	$("#jsNav_next").click(function () {
		if (actualPage == Math.floor(screenshotsData.length/screenshotsPage) && (actualId+1) == screenshotsData.length)
			return false;
		if ((actualId+1) % screenshotsPage == 0 && actualId > 0) {
			actualPage++;
			actualId = actualPage * screenshotsPage;
			screenshots_Page(actualPage);
		} else
			actualId++;

		ImageViewing = false;
		$("#jqmContent").hide();
		affImage( $('#image'+actualId) );
	});

	//popups vidéo
	$("a[class=video]").click(function() {
		loading();
		var myLoadVideo = function(hash){
			var $modal = $(hash.w);
			var infos = $.trim($modal.text());
			
			//résultat ajax contenant titre etc
			if (infos != "") {
				//récupération des résultats
				var infosTab = infos.split("##");
				var titre = $.trim(infosTab[0]);
				var legende = $.trim(infosTab[1]);
				var vWidth = parseInt($.trim(infosTab[2]));
				var vHeight = parseInt($.trim(infosTab[3]));
				var id = $.trim(infosTab[4]);
				var cCount = parseInt($.trim(infosTab[5]));
				var cMoyenne = parseInt($.trim(infosTab[6]));

				//variables swf
				var flashvars = {
					myUrl: "../../videos/"+id+".flv"
				};
				var params = {
					menu: false,
					allowfullscreen: true,
					allowScriptAccess: "sameDomain"
				};
				var attributes = false;
				
				var checked;
				var rating = '<div class="texte2 cell_alt" style="width:'+vWidth+'px;" id="rating-star">';
				for (i=1; i<=10; i++) {
					checked = (i==cMoyenne) ? " checked=\"checked\"" : "";
					rating += '<input type="radio" value="'+i+'" name="rating" class="star"'+checked+' />';
				}
				rating += '&nbsp;&nbsp;<i><span id="counter">' + cCount + '</span> vote(s)</i></div>';

				if (!VideoPlaying) {
					loading();
					nettoyer();
					//ajout de la barre de titre
					$('#jqmTitle').html('<img class="jqmClose" alt="Fermer" src="'+chemin+'/images/design/symboles/close.gif" /><b>'+titre+'</b> - <i>'+legende+'</i>').addClass("texte2").css('padding', '1px');
					$('.jqmClose').click(function() { $('#modalWindow').jqmHide(); }); //fix
					//ajout de la vidéo
					//var unique = ($.browser.msie) ? new Date().getTime() : 0;
					var unique = new Date().getTime();
					swfobject.embedSWF(chemin+"/scripts/fPlayer/fPlayerIn.swf?t="+unique, "jqmContent", vWidth, vHeight, "9.0.0", "fPlayer", flashvars, params, attributes);
					//placement de la popup
					$('#modalWindow').append(rating).css({ width: vWidth+"px", height: vHeight+20+"px", left: Math.floor((documentw-vWidth)/2), top: Math.floor((documenth-vHeight)/2) }).addClass('cell_alt');
					//rating
					$('input[type=radio].star').rating({
						callback: function(value, link) {
							$.ajax({
								type: "POST",
								url: chemin + "/scripts/ajax/voteVideo.php",
								data: { id:id, note:value } ,
								dataType: "text",
								success: function(string){
									if (string=="no")
										alert("Vous devez ête membre pour voter");
									else if (string=="add")
										$("#counter").hide().text( ++cCount ).fadeIn();
									else if (string=="up")
										$("#counter").hide().fadeIn();
								}
							});
						}
					});
					$('#modalWindow').fadeIn();
					VideoPlaying = true;
				}
			}
			else {
				loading();
				alert("Cette vidéo n'existe pas");
			}
		};

		var myCloseVideo = function(hash){
			VideoPlaying = false;
			swfobject.removeSWF("jqmContent");
			hash.o.remove();
			nettoyer();
		};

		$('#modalWindow')
			.jqm({
				target: '#jqmTitle',
				ajax: $(this).attr("href")+"&aff=1",
				onShow: myShowGallery,
				onLoad: myLoadVideo,
				onHide: myCloseVideo
			})
			.jqmShow();

		return false;
	});
});
