jQuery(
	function(){
		init();
	}
);

var loadOK=false;
function debug(message){
	$('#newNote').append('['+message+']\n');
	GetId('newNoteTextArea').value=GetId('newNoteTextArea').value+'['+message+']';
}
var lastMsgClick='';
var curMsgActions='';
var alertBlink=false;
var msgBlink=false;
function init(){
	if($('#myimg').width()<1000){
		setTimeout(function(){init();},1000);
		return;
	}

	javascript:scroll(0,0); //Scroll to top of page
	
	$("#tabs").tabs();
	
	initSlider();

	$("#siteInfo").draggable({ containment: 'document' });
	$("#Coms_Container").draggable({ containment: 'document',handle:'#ComBar',cursor:'move',opacity:0.35 });
	$("#addMessage_Container").draggable({ containment: 'document',handle:'#addMessageBar',cursor:'move',opacity:0.35 });
	$("#textColor_Container").draggable({ containment: 'document',handle:'#textColorBar',cursor:'move',opacity:0.35 });
	$("#backColor_Container").draggable({ containment: 'document',handle:'#backColorBar',cursor:'move',opacity:0.35 });
	
	setTAValueToNote();
	
	//attachInfoText("siteInfoImg","Informations");
	//attachInfoText("addMessage","Ajouter un message");
	attachInfoText("messageFlood","Protection contre le flood");
	//attachInfoText("zoom_plus","Zoomer");
	//attachInfoText("zoom_moins","Dézoomer");
	//attachInfoText("textEdit","Modifier le contenu");
	//attachInfoText("addImage","Attacher une image au message");
	//attachInfoText("backColor","Modifier la couleur de fond");
	//attachInfoText("fontColor","Modifier la couleur d'écriture");
	attachInfoText("newNoteDragIcon","Déplacer votre message");
	attachInfoText("newNoteSwitchIcon","Voir l'image");
	attachInfoText("newNoteImageSwitchIcon","Voir le message");
	//attachInfoText("close_Button","Fermer");
	//attachInfoText("saveMessage","Enregistrer");
	//attachInfoText("cancelMessage","Ne pas enregistrer");
	//attachInfoText("waitSave","Enregistrement en cours...");
	//attachInfoText("saveOk","Message enregistré !");
	
	defDraggable();
	defResizable();
	
	$('#siteInfo').show();
	$('#Coms_Container').show();
	$(document).pngFix(); 
	$('#tools2').hide();
	$('#siteInfo').hide();
	$('#Coms_Container').hide();
	$('#closeButton').hide();
	$('#saveMessage').hide();
	$('#cancelMessage').hide();
	$('#waitSave').hide();
	$('#saveOk').hide();
	$('#zoom_moins').hide();
	$('#zoom_plus').hide();
	$('#newNoteContainer').hide();
	
	//Init event wall selection
    $('#wallSelection').mouseenter(function(){
      $('#wallSelectionImg').hide();$('#wallList').show();$('#wallSelection').css('width',100);
    }).mouseleave(function(){
      $('#wallSelectionImg').show();$('#wallList').hide();$('#wallSelection').css('width',32);
    });
	
	//Positionement alerté du message new
    $('#avertMessage').mouseenter(function(){
		alertBlink=true;
		
    }).mouseleave(function(){
		alertBlink=false;
    });
	setInterval(function(){
		if(alertBlink) $('#newNoteContainer').toggle();
		else if($('#addMessage_Container').css('display')!='none') $('#newNoteContainer').show();
	},700);
	
	////
	if( $('.msgBlink').size() > 0){
		msgBlink=true;
		$('.msgBlink').mouseleave(function(){
			msgBlink=false;
			$('.msgBlink').show();
		});
		$('.msgBlink').children().mouseleave(function(){
			msgBlink=false;
			$('.msgBlink').show();
		});
		setInterval(function(){
			//debug('toggle');
			if(msgBlink){ 
				if($('.msgBlink').css('display') != 'none') $('.msgBlink').hide();
				else $('.msgBlink').show();
			}
			else $('.msgBlink').show();
		},1000);
	}
	
	//Effet sur les listes dans les menus
    $('#portalDiv').mouseenter(function(){
		$('#portailList').show();
		
    }).mouseleave(function(){
		$('#portailList').hide();
    });
    $('#portailList').mouseenter(function(){
		$('#portailList').show();
		
    }).mouseleave(function(){
		$('#portailList').hide();
    });
    $('#wallSelection2').mouseenter(function(){
		$('#wallsList').show();
		
    }).mouseleave(function(){
		$('#wallsList').hide();
    });
    $('#wallsList').mouseenter(function(){
		$('#wallsList').show();
		
    }).mouseleave(function(){
		$('#wallsList').hide();
    });
	
	//Initialisation des zones images
	$(".bla").each(function () {
		saveTable[this.id+'height']=$(this).height();
		saveTable[this.id+'width']=$(this).width();
		
		if(this.id!="newNoteContainer" && getImageId('#'+this.id)!=''){
			saveTable[getImageId('#'+this.id)+'height']=$('#'+getImageId('#'+this.id)).height();
			saveTable[getImageId('#'+this.id)+'width']=$('#'+getImageId('#'+this.id)).width();
			
			var thisId=this.id;
			
			$('#'+getImageId('#'+this.id)).mouseenter(function () {
				messageEnter(thisId, this.id);
			});
			
			$('#'+getImageId('#'+this.id)).click(function () {
				messageClick(thisId, this.id);
			});
			
			$('#'+getImageId('#'+this.id)).mouseleave(function () {
				messageLeave(thisId, this.id);
			});
		}
		
	});

	initialWallSize=$('#myimg').width();
	ratio=initialWallSize/(pageWidth());

	switchZoomMode();
	
	//Mise en place des zones texte
	$(".bla").mouseenter(function (event) {
		if(this.id!="newNoteContainer"){ 
			event.stopPropagation();
			messageEnter(this.id, this.id);
		}
	});
	
	$(".bla").click(function (event) {
		if(this.id!="newNoteContainer"){ 
			event.stopPropagation();
			messageClick(this.id, this.id);
		}
	});
	
	$(".bla").mouseleave(function (event) {
		if(this.id!="newNoteContainer"){ 
			event.stopPropagation();
			messageLeave(this.id, this.id);
		}
	});

	
	$('#colorWheelText').farbtastic(function(color) {
			colorType='color';
			changeSomeColor(color);
		}
	);
	$('#colorWheelBack').farbtastic(function(color) {
			colorType='backgroundColor';
			changeSomeColor(color);
		}
	);
	
	initUploadButton();
	
	initialFloodVerif();
	
	loadOK=true;
}
var rand;
var addImageInUploader;
function initUploadButton(){
	rand=Math.floor((new Date()).getTime() / 1000) +''+Math.floor(Math.random()*1000);

	$('#addImageIn').fileUpload ({		'uploader'  : 'jquery-upload/uploader.swf',		'script'    : 'jquery-upload/upload.php',		'cancelImg' : 'jquery-upload/cancel.png',		'auto'      : true,		'multi'      : false,		'buttonText'      : '',		'width'      : 120,		'height'      : 26,		'simUploadLimit'      : 1,		'wmode'      : 'transparent',		'hideButton'      : true,		'displayData': 'speed',		'folder' : ''+rand, /*Parametre qui ne marche pas, aller modifier upload.php */		onSelectOnce: function (a, b) {			$('#addImageInQueue').fadeIn();		},		onComplete: function (a, b ,c, d, e) {			ImageUploadComplete(c['name']);			}	});
	addImageInUploader=document.getElementById("addImageInUploader");
	$('#addImageInQueue').draggable();
	$('#addImageInQueue').css("background","transparent");
	$('#addImageInQueue').css("border","1px dotted black");
	$('#addImageInQueue').css("position","absolute");
	$('#addImageInQueue').css("top","50px");
	$('#addImageInQueue').css("padding","15px");
	$('#addImageInQueue').css("display","none");
	
	
}

//////////////////////////////////////////Message events
function messageEnter(messageId, currentId){ //currentId est soit l'id du message, soit de l'image
	//debug(messageId+'Enter');
	if(loadOK){
		noteSwitchZoom(messageId,true);
		$('#'+currentId+'Toggler').show();
		$('#'+currentId+'msgActions').show();
		if('#'+currentId == lastMsgClick) $(lastMsgClick).css('zIndex',5);
		
		$('#'+messageId+'of').css('overflow','auto');
	}
}

function messageClick(messageId, currentId){
	//debug(messageId+'Click');
	if(loadOK){
		lastMsgClick='#'+currentId;
		$('#'+currentId).css('zIndex',5);
		majMsgCounts('#'+messageId);
	}
}

function messageLeave(messageId, currentId){
	//if(curMsgActions==currentId) return;
	//debug(messageId+'Leave');
	if(loadOK){
		noteSwitchZoom(messageId,false);
		$('#'+currentId).css('zIndex',2);
		$('#'+currentId+'Toggler').hide();
		$('#'+currentId+'msgActions').hide();
		
		$('#'+messageId+'of').css('overflow','hidden');
	}
}

//////////////////////////////////////////Verif message flood
function initialFloodVerif(){
	if(floodLeft<2){
		//pas de flood détecté
	}
	else{
		$('#addMessage').hide();
		$('#messageFlood').html(floodLeft+' s');
		$('#messageFlood').show();
		setTimeout(function(){majFloodVerif();},1000);
	}
}

function majFloodVerif(){
	floodLeft=floodLeft-1;
	if(floodLeft>0){
		$('#messageFlood').html(floodLeft+' s');
		setTimeout(function(){majFloodVerif();},1000);
	}
	else{
		$.post("php_scripts/ajax_wallFlood.php", "id="+wallId,
				function(data){ 
					if(data=='' || data=='0'){
						//pas de flood détecté
						floodLeft=0;
						$('#addMessage').show();
						$('#messageFlood').hide();
					}
					else{
						floodLeft=parseInt(data);
						$('#messageFlood').html(parseInt(data)+' s');
						setTimeout(function(){majFloodVerif();},1000);
					}
				}
			);
	}
}

//////////////////////////////////////////Slider init
//Todo: ne pas destroy à la maj, juste changer le max, mais mettre la value à max si le cas précédemment
//Todo: une icône permettant de masquer/afficher/afficher en historique inverse, le slider
var currentSlideValue=-1;
var oldSlideMax=-1;
function initSlider(){
	if($('.AllMessage').size()>0){
		//alert($('.AllMessage').size());
		
		if(currentSlideValue==oldSlideMax)
			currentSlideValue=$('.AllMessage').size();
		else
			$('.AllMessage:lt('+($('.AllMessage').size()-oldSlideMax)+')').hide();
		
		oldSlideMax=$('.AllMessage').size();
		$("#slider").slider({
			value:currentSlideValue,
			min: 0,
			max:$('.AllMessage').size(),
			step: 1,
			slide: function(event, ui) {
				currentSlideValue=ui.value;
				if($('.AllMessage').size()==ui.value)
					$('.AllMessage').show();
				else{
					$('.AllMessage').hide();
					$('.AllMessage:gt('+($('.AllMessage').size()-ui.value-1)+')').show();
				}
				
			}
		});
	}
}

function majSlider(){
	$("#slider").slider( 'destroy' );
	initSlider();
}

//////////////////////////////////////////Switch Msg TXT/IMG & Upload Image
function newNoteToggle(){//*
	if($('#newNoteSpan').css('display')=='none'){
		$('#newNoteImageSpan').hide();
		$('#newNoteSpan').fadeIn();
	}
	else{
		$('#newNoteSpan').hide();
		$('#newNoteImageSpan').fadeIn();
	}//*/
}

function getNewNoteImageStatus(){
	if($('#newNoteSpan').css('display')=='none'){
		return 'image';
	}
	else{
		return 'message';
	}
}

function ImageUploadComplete(name){
	$('#addImageInQueue').fadeOut();
	messageImg='img/'+rand+'_'+name;

	$('#newNoteImage').html('<img id="nNimg" src="" />');

	document.getElementById('nNimg').src=messageImg;
	document.getElementById('nNimg').onload = function() {
		displayUploadedImage();
	};
}

function displayUploadedImage(){
	var newNoteW=parseFloat($("#newNote").css('width'));
	var newNoteH=parseFloat($("#newNote").css('height'));

	$('#newNoteToggler').show();
	$('#newNoteSpan').hide();
	$('#newNoteImageSpan').show();

	var noteImgW=$('#nNimg').width();
	var noteImgH=$('#nNimg').height();
	
	if(noteImgW>newNoteW){
		var transratio=noteImgW/newNoteW;
		noteImgW=noteImgW/transratio;
		noteImgH=noteImgH/transratio;
	}
	if(noteImgH>newNoteH){
		var transratio=noteImgH/newNoteH;
		noteImgW=noteImgW/transratio;
		noteImgH=noteImgH/transratio;
	}

	$("#newNoteImage").css('width',noteImgW);
	$("#newNoteImage").css('height',noteImgH);
	$('#nNimg').css('width',noteImgW+'px');
	$('#nNimg').css('height',noteImgH+'px');

	 defResizable();
}

////////////////////////////////////////////////////////////////Notes Image
function getImageId(noteId){
	return $(noteId+'imageId').html();
}

function noteToggle(id,smooth){
	if($(id).css('display')=='none'){
		$('#'+getImageId(id)).hide();
		if(smooth) $(id).fadeIn();
		else $(id).show();
	}
	else{
		$(id).hide();
		if(smooth) $('#'+getImageId(id)).fadeIn();
		else $('#'+getImageId(id)).show();
	}
}

function getNoteImageStatus(id){
	if($(id).css('display')=='none'){
		return 'image';
	}
	else{
		return 'message';
	}
}

/////////////////////////////////////////////////////////////Options des messages affichés

function noteAlert(id){
	$.post("php_scripts/ajax_alert.php", "id="+id.substr(5,20),
		function(data){ 
			$(id+'AlertIcon').hide();
			$(id+'AlertIconOk').show();
			$('#'+getImageId(id)+'AlertIcon').hide();
			$('#'+getImageId(id)+'AlertIconOk').show();
			majMsgCounts(id);
		}
	);	
}
function comAlert(id){
	$.post("php_scripts/ajax_comAlert.php", "id="+id,
		function(data){ 
			$('#com'+id+'AlertIcon').hide();
			$('#com'+id+'AlertIconOk').show();
		}
	);	
}
var currentComId=0;
function noteCom(id){
	$.post("php_scripts/ajax_com.php", "id="+id.substr(5,20),
		function(data){ 
			$('#Coms').html(data);
			currentComId=id;
			$('#Coms_Container').fadeIn();
			majMsgCounts(id);
		}
	);	
}

function noteComAdd(){
	$.post("php_scripts/ajax_addcom.php", "id="+currentComId.substr(5,20)+"&text="+$('#newComText').attr('value'),
		function(data){ 
			if(data.substring(0,1)=='P'){ //flood
				alert(data);
			}
			else{
				$('#Coms').html(data);
				$('#newComText').attr('value','');
			}
			
			majMsgCounts(currentComId);
		}
	);	
}

function closeComs(){
	$('#Coms_Container').fadeOut();
}

function noteLike(id){
	$.post("php_scripts/ajax_like.php", "id="+id.substr(5,20),
		function(data){
			$(id+'LikeIcon').hide();
			$(id+'LikeIconOk').show();
			$('#'+getImageId(id)+'LikeIcon').hide();
			$('#'+getImageId(id)+'LikeIconOk').show();
			majMsgCounts(id)
		}
	);	
}

function noteDislike(id){
	$.post("php_scripts/ajax_dislike.php", "id="+id.substr(5,20),
		function(data){
			$(id+'DislikeIcon').hide();
			$(id+'DislikeIconOk').show();
			$('#'+getImageId(id)+'DislikeIcon').hide();
			$('#'+getImageId(id)+'DislikeIconOk').show();
			majMsgCounts(id)
		}
	);	
}

function majMsgCounts(id){
	$.post("php_scripts/msgCounts.php", "id="+id.substr(5,20),
		function(data){
			var reg=new RegExp("[;]+", "g");
			var tableau=data.split(reg);
			$(id+'AlertCount').html(tableau[0]);
			$('#'+getImageId(id)+'AlertCount').html(tableau[0]);
			$(id+'ComCount').html(tableau[1]);
			$('#'+getImageId(id)+'ComCount').html(tableau[1]);
			$(id+'LikeCount').html(tableau[2]);
			$('#'+getImageId(id)+'LikeCount').html(tableau[2]);
			$(id+'DislikeCount').html(tableau[3]);
			$('#'+getImageId(id)+'DislikeCount').html(tableau[3]);
		}
	);	
}

//////////////////////////////////////////////////////////////

function noteSwitchZoom(id,cursorIsOnMessage){
	if(mode=='zoom') return;
	
	if(id=='newNoteContainer') return;
	
	if(blockAnim) return;
	blockAnim=true;

	var this_percentage;
	
	if($('#'+(id)+'mode').html()=='zoom'){ 
		if(cursorIsOnMessage==true){ blockAnim=false; return; }
		//debug('dezoom');
		this_percentage=100/ratio;
		$('#'+(id)+'mode').html('normal');
	}
	else{ 
		//debug('zoom');
		this_percentage=100*ratio;
		$('#'+(id)+'mode').html('zoom');
	}
	
	reduceElement('#'+(id),this_percentage,true,false,true,$('#'+(id)+'mode').html());
	
	if($('#'+(id)+'mode').html()=='zoom') restoreNoteSize(id);
	
	blockAnim=false;
}

function restoreNoteSize(id){ //Utiliser pour contrer le décalage progressif entraîné par les arrondis
	if('#'+id!='#newNoteContainer' && getImageId('#'+id)!='' ){
		var imageId=getImageId('#'+id);
		var saveStatus=getNoteImageStatus('#'+id);
		if(saveStatus=='image') noteToggle('#'+id,false);
		$('#'+id).height(saveTable[id+'height']);$('#'+id+'of').height(saveTable[id+'height']);
		$('#'+id).width(saveTable[id+'width']);
		noteToggle('#'+id,false);
		$('#'+imageId).height(saveTable[imageId+'height']);
		$('#'+imageId).width(saveTable[imageId+'width']);	
		$('#'+imageId+'Bis').height(saveTable[imageId+'height']);
		$('#'+imageId+'Bis').width(saveTable[imageId+'width']);	
		if(saveStatus!=getNoteImageStatus('#'+id)) noteToggle('#'+id,false);
	}
	else{
		$('#'+id).height(saveTable[id+'height']);$('#'+id+'of').height(saveTable[id+'height']);
		$('#'+id).width(saveTable[id+'width']);
	}
}

function switchZoomMode(){
	if(blockAnim) return;
	blockAnim=true;

	//Agrandissement/diminution du mur
	if(mode=='all'){
		$('#zoom_plus').fadeOut("slow");
		percentage=100*ratio;
		mode='zoom';
		$('#zoom_moins').fadeIn("slow");
		$('body').css('overflowX','scroll');
	}
	else{
		$('#zoom_moins').fadeOut("slow");
		percentage=100/ratio;
		mode='all';
		$('#zoom_plus').fadeIn("slow");
		$('body').css('overflowX','hidden');
	}

	reduceElement('#myimg',percentage,true,false);

	//Déplacement et modif des tailles des notes 
	$(".bla").each(function () {
		var position=true;
		var size=false;
	
		//Si la dimension de la note n'est pas adaptée à ce mode, on l'ajuste
		if($('#'+(this.id)+'mode').html()!=mode){ 
			size=true;
		}

		reduceElement('#'+this.id,percentage,size,position,true,mode);
		
		if(mode=='zoom') restoreNoteSize(this.id);
		
		$('#'+(this.id)+'mode').html(mode);
	});
	
	defMinMaxResize();
	
	blockAnim=false;
}

function reduceElement(id,p,size,position,font,fontMode){
	p/=1;
	if(size){
		if(id=='#myimg') 
			$(id).width($(id).width()*p*0.01);
		else{
			if(id=='#newNoteContainer'){
				$(id).css('width',$(id).width()*p*0.01);
				$(id).css('height',$(id).height()*p*0.01);
				var saveStatus=getNewNoteImageStatus();
				if(saveStatus=='image') newNoteToggle();
				$('#newNote').css('width',$('#newNote').width()*p*0.01);
				$('#newNote').css('height',$('#newNote').height()*p*0.01);
				newNoteToggle();
				$('#newNoteImage').css('width',$('#newNoteImage').width()*p*0.01);
				$('#newNoteImage').css('height',$('#newNoteImage').height()*p*0.01);				
				$('#nNimg').css('width',$('#nNimg').width()*p*0.01);
				$('#nNimg').css('height',$('#nNimg').height()*p*0.01);
				if(saveStatus!=getNewNoteImageStatus()) newNoteToggle();
			}
			else{
				//Message normal, on verifie si on doit modifier son image
				var imageId=getImageId(id);
				if(imageId!=''){
					var saveStatus=getNoteImageStatus(id);
					if(saveStatus=='image') noteToggle(id,false);
					$(id).css('width',$(id).width()*p*0.01);
					$(id).css('height',$(id).height()*p*0.01);$(id+'of').css('height',$(id+'of').height()*p*0.01);
					noteToggle(id,false);
					$('#'+imageId).css('width',$('#'+imageId).width()*p*0.01);
					$('#'+imageId).css('height',$('#'+imageId).height()*p*0.01);
					$('#'+imageId+'Bis').css('width',parseInt($('#'+imageId+'Bis').css('width'))*p*0.01);
					$('#'+imageId+'Bis').css('height',parseInt($('#'+imageId+'Bis').css('height'))*p*0.01);
					if(saveStatus!=getNoteImageStatus(id)) noteToggle(id,false);
				}
				else{
					$(id).css('width',$(id).width()*p*0.01);
					$(id).css('height',$(id).height()*p*0.01);$(id+'of').css('height',$(id+'of').height()*p*0.01);
				}
			}
		}		
	}
	if(position){
		var imageId=getImageId(id);

		if(imageId!='' && id!='#newNoteContainer'){
			var saveStatus=getNoteImageStatus(id);
			if(saveStatus=='image') noteToggle(id,false);
			$(id).css('top',$(id).position().top*p*0.01);
			$(id).css('left',$(id).position().left*p*0.01);
			noteToggle(id,false);
			$('#'+imageId).css('top',$('#'+imageId).position().top*p*0.01);
			$('#'+imageId).css('left',$('#'+imageId).position().left*p*0.01);		
			if(saveStatus!=getNoteImageStatus(id)) noteToggle(id,false);
		}
		else{
			$(id).css('top',$(id).position().top*p*0.01);
			$(id).css('left',$(id).position().left*p*0.01);
		}
	}
	if(font){
		if(fontMode=='zoom') $(id).css('fontSize','100%');
		else $(id).css('fontSize', p+'%');
	}
}

function pageWidth(){
	return window.innerWidth != null? window.innerWidth: document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth:document.body != null? document.body.clientWidth:null;
}
function pageHeight(){
	return window.innerHeight != null? window.innerHeight: document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight:document.body != null? document.body.clientHeight:null;
}

function attachInfoText(id,info){
	$('#'+id).mouseenter(function () {
		montreBulle(info);
	});
	
	$('#'+id).mouseleave(function () {
		cacheBulle();
	});	//*/
	/*$('#'+id).mouseover(function () {
		montreBulle(info);
	});
	
	$('#'+id).mouseout(function () {
		cacheBulle();
	});*/
}

function addMessage(){
	//$('#addMessage').fadeOut();
	//$('#saveMessage').fadeIn();
	//$('#cancelMessage').fadeIn();
	$('#newNoteContainer').fadeIn(); //Prévisu de la note
	//$('#tools2').fadeIn();
	$('#addMessage_Container').fadeIn(); //Formulaire d'ajout
	setNoteToMinSize();
	$('#newNoteContainer').css('top',$('#toolsBox').position().top+50);
	$('#newNoteContainer').css('left',$('#toolsBox').position().left+230);
	pageState='NewMessage';
}

function saveMessage(){
	$.post("php_scripts/ajax_wallFlood.php", "id="+wallId,
			function(data){ 
				if(data==''){
					//pas de flood détecté
					if(confirm("Êtes-vous sûr de vouloir envoyer ce message? Vous ne pourrez plus le modifier par la suite...")){
						$('#addMessage').hide();
						//$('#cancelMessage').fadeOut();
						//$('#tools2').fadeOut();
						//$('#newNoteTextEdit').fadeOut();
						//$('#colorpicker').fadeOut();
						//$('#closeButton').fadeOut();
						$('#addMessage_Container').fadeOut();
						$('#textColor_Container').fadeOut();
						$('#backColor_Container').fadeOut();
						$('#waitSave').fadeIn();
						
						$("#newNoteContainer").draggable('destroy');
						$("#newNote").resizable('destroy');
						
						var mult=1;
						if(mode=='all'){
							mult=ratio;
						}
						
						var param='';
						
						var saveStatus=getNewNoteImageStatus();
						$('#newNoteSpan').show();
						$('#newNoteImageSpan').show();
						
						param+='&wallId='+wallId;
						param+='&Color='+$('#newNote').css('color');
						param+='&BackColor='+$('#newNote').css('backgroundColor');
						param+='&Value='+GetId('newNoteTextArea').value; 
						param+='&Top='+$("#newNoteContainer").position().top*mult;
						param+='&Left='+$("#newNoteContainer").position().left*mult;
						param+='&Height='+$("#newNote").height()*mult;
						param+='&Width='+$("#newNote").width()*mult;
						
						if($('#nNimg').attr('src')!='NONE'){
							param+='&imagePath='+$('#nNimg').attr('src');
							param+='&imageHeight='+$("#nNimg").height()*mult;
							param+='&imageWidth='+$("#nNimg").width()*mult;
						}
						else{
							param+='&imagePath='+'NONE';
							param+='&imageHeight='+0;
							param+='&imageWidth='+0;
						}
						
						$.post("php_scripts/saveMessage.php", param,
							function(data){
								//alert(data);
								if(data==''){
									$('#waitSave').hide();
									$('#saveOk').fadeIn();
									
									if(saveStatus=='image')
										$('#newNoteSpan').hide();
									else
										$('#newNoteImageSpan').hide();
									
									$("#newNoteContainer").fadeOut();
									
									pageState='MessageAdded';
								}
								else{
									alert(data);
								}
							}
						);	
						
					}
				}
				else{
					alert('Protection contre le flood : encore '+parseInt(data)+' secondes avant de pouvoir envoyer un message.');
				}
			}
		);
}

function setTAValueToNote(){
	$("#newNote").resizable('destroy');
	var value=GetId('newNoteTextArea').value;
	rExp = new RegExp( "\\n", "g" );
	value=value.replace(rExp,"<br>");
	$('#newNote').html(value);
	defResizable();
}

var colorType;
function textEditClick(){ //Methode OBSOLETE ????
	$('#tools2').fadeOut();
	$('#newNoteTextEdit').fadeIn();
	$('#closeButton').fadeIn();
	
	//On masque pour éviter la confusion
	$('#saveMessage').hide();
	$('#cancelMessage').hide();
}

function backColorClick(){
	$('#tools2').fadeOut();
	colorType='backgroundColor';
	$('#colorpicker').fadeIn();
	$('#closeButton').fadeIn();
	
	//On masque pour éviter la confusion
	$('#saveMessage').hide();
	$('#cancelMessage').hide();
}

function fontColorClick(){
	$('#tools2').fadeOut();
	colorType='color';
	$('#colorpicker').fadeIn();
	$('#closeButton').fadeIn();
	
	//On masque pour éviter la confusion
	$('#saveMessage').hide();
	$('#cancelMessage').hide();
}

function editClose(){ //Methode OBSOLETE ????
	if($('#newNoteTextEdit').css('display')!='none') $('#newNoteTextEdit').fadeOut();
	if($('#colorpicker').css('display')!='none') $('#colorpicker').fadeOut();
	$('#closeButton').fadeOut();
	$('#tools2').fadeIn();
	
	//Rétablissement
	$('#saveMessage').show();
	$('#cancelMessage').show();
}

function cancelMessage(){
	//$('#saveMessage').fadeOut();
	//$('#cancelMessage').fadeOut();
	//$('#tools2').fadeOut();
	//$('#newNoteTextEdit').fadeOut();
	$('#addMessage_Container').fadeOut();
	$('#textColor_Container').fadeOut();
	$('#backColor_Container').fadeOut();
	//$('#colorpicker').fadeOut();
	//$('#closeButton').fadeOut();
	$("#newNoteContainer").fadeOut();
	//$('#addMessage').fadeIn();
	pageState='Read';
}

function changeSomeColor(color){
	$('#newNote').css(colorType,color);
}

function loadNewMessages(){
	//$('#refreshImg').show();
	$('#refreshImgImg').attr('src','img/icons/wait.gif');
	attachInfoText("refreshImgImg","Mise à jour du mur...");
	
	var param='';
	var old_last_id=last_id;
	param+='wallId='+wallId;
	param+='&last_id='+last_id;
	
	var ref=document.getElementById('the_last_id');
	if(ref) ref.parentNode.removeChild(ref);

	$.post("php_scripts/loadNewMessages.php", param,
		function(data){
		//	alert(data);
			$('body').prepend(data);
			
			last_id=parseInt($('#the_last_id').html());
			
			var maj_Slider=false;
			if(last_id>old_last_id) //Il y a un/des nouveau(x) message(s)
				var maj_Slider=true;
			
			old_last_id++;
			while(old_last_id<=last_id){
				if(document.getElementById('note'+old_last_id)){
					$('#note'+old_last_id).show();

					saveTable['note'+old_last_id+'height']=$('#note'+old_last_id).height();
					saveTable['note'+old_last_id+'width']=$('#note'+old_last_id).width();
					
					if(getImageId('#note'+old_last_id)!=''){
						saveTable[getImageId('#note'+old_last_id)+'height']=$('#'+getImageId('#note'+old_last_id)).height();
						saveTable[getImageId('#note'+old_last_id)+'width']=$('#'+getImageId('#note'+old_last_id)).width();
						
						var thisId='note'+old_last_id;
						
						$('#'+getImageId('#note'+old_last_id)).mouseenter(function () {
							messageEnter(thisId, this.id);
						});
						
						$('#'+getImageId('#note'+old_last_id)).click(function () {
							messageClick(thisId, this.id);
						});
						
						$('#'+getImageId('#note'+old_last_id)).mouseleave(function () {
							messageLeave(thisId, this.id);
						});
					}		
		
					if(mode=='all'){
						//Conve-rsion de la note au mode all
						//alert('#note'+old_last_id);
						reduceElement('#note'+old_last_id,100/ratio,true,true,true,'all');
						$('#note'+old_last_id+'mode').html('all');
					} 
					$('#note'+old_last_id).hide();
					if(getImageId('#note'+old_last_id)!='') $('#'+getImageId('#note'+old_last_id)).fadeIn("slow");
					else $('#note'+old_last_id).fadeIn("slow");
					
					$('#note'+old_last_id).mouseenter(function () {
						messageEnter(this.id, this.id);
					});
					
					$('#note'+old_last_id).click(function () {
						messageClick(this.id, this.id);
					});
					
					$('#note'+old_last_id).mouseleave(function () {
						messageLeave(this.id, this.id);
					});
				}
				old_last_id++;
			}
			if(maj_Slider) majSlider();
			$('#refreshImgImg').attr('src','img/icons/accept.png');
			attachInfoText("refreshImgImg","Le mur est à jour");
			setTimeout(function(){loadNewMessages();},5000);
		}
	);	
	
	
}
loadNewMessages();

////////////////////////AFFICHAGE/MASQUAGE DE L'INTERFACE UTILISATEUR/////////////////////////

	function changeOpac(opacity, id) {
		if(!document.getElementById(id)) {
			return;
		}

		var object = document.getElementById(id).style;
		object.opacity = (opacity / 100);
		object.MozOpacity = (opacity / 100);
		object.KhtmlOpacity = (opacity / 100);
		object.filter = "alpha(opacity=" + opacity + ")";

		if(opacity<=0) 
			object.display="none";
		else if(object.display=="none")
			object.display="block";
	}	

function toggleUi(){
	if($('#user-interface').css("display")=='none'){
		$('#user-interface').show();
		$('#toggleuiBox').hide();
	}
	else{
		$('#user-interface').hide();
		$('#toggleuiBox').show();
	}
}

////////////////////////CODE DE GESTION DU DRAG ET DU RESIZE/////////////////////////
	function defDraggable(){
		$("#newNoteContainer").draggable({ containment: 'document' });
	}

	function defResizable(){
		$("#newNote").resizable( 'destroy' );
		$("#newNoteImage").resizable( 'destroy' );
		
		if($('#nNimg').length){//Si une image a été uploadée
			$("#newNote").resizable({ containment: 'document'});
			
			$("#newNoteImage").resizable({ containment: 'document',aspectRatio:true });
			$('#newNoteImage').resizable('option', 'alsoResize', '#nNimg');//Pour ne pas déformer l'image
		}
		else{
			$("#newNote").resizable({ containment: 'document' });
			$('#newNote').resizable('option', 'alsoResize', '#newNoteImage');
			
			$("#newNoteImage").resizable({ containment: 'document' });
		}
		
		defMinMaxResize();
	}
	
	function defMinMaxResize(){
		var imageRatio = 1;
		
		if($('#nNimg').length){
			imageRatio = parseInt($('#nNimg').css('width')) / parseInt($('#nNimg').css('height'));
			//debug('\n '+ $('#nNimg').css('width') + '-' + $('#nNimg').css('height') +' \n');
		}
		
		if(mode=='zoom'){
			$('#newNote').resizable('option', 'maxHeight', 200);
			$('#newNote').resizable('option', 'minHeight', 80);		
			$('#newNote').resizable('option', 'maxWidth', 200);
			$('#newNote').resizable('option', 'minWidth', 80);
			$('#newNoteImage').resizable('option', 'maxHeight', 200/imageRatio);
			$('#newNoteImage').resizable('option', 'minHeight', 80/imageRatio);		
			$('#newNoteImage').resizable('option', 'maxWidth', 200);
			$('#newNoteImage').resizable('option', 'minWidth', 80);
		}
		else{
			$('#newNote').resizable('option', 'maxHeight', 200/ratio);
			$('#newNote').resizable('option', 'minHeight', 80/ratio);		
			$('#newNote').resizable('option', 'maxWidth', 200/ratio);
			$('#newNote').resizable('option', 'minWidth', 80/ratio);
			$('#newNoteImage').resizable('option', 'maxHeight', 200/(ratio*imageRatio));
			$('#newNoteImage').resizable('option', 'minHeight', 80/(ratio*imageRatio));		
			$('#newNoteImage').resizable('option', 'maxWidth', 200/ratio);
			$('#newNoteImage').resizable('option', 'minWidth', 80/ratio);
			//debug('maxH:'+200/(ratio*imageRatio)+'minH:'+80/(ratio*imageRatio)+'maxW:'+200/ratio+'minW:'+80/ratio);
		}
	}
	
	function setNoteToMinSize(){
		if(mode=='zoom'){
			$('#newNote').height(80);
			$('#newNote').width(80);	
			$('#newNoteImage').height(80);
			$('#newNoteImage').width(80);			
		}
		else{
			$('#newNote').height(80/ratio);
			$('#newNote').width(80/ratio);		
			$('#newNoteImage').height(80/ratio);
			$('#newNoteImage').width(80/ratio);	
		}
	}

////////////////////////CODE DE GESTION DES INFOBULLES/////////////////////////
var CurVisible=false;
function GetId(id){
	return document.getElementById(id);
}

function move(e){
	if(CurVisible) {
		if (navigator.appName!="Microsoft Internet Explorer"){ // Si on est pas sous IE
			GetId("Cur").style.left=(e.pageX+5)+"px";
			GetId("Cur").style.top=(e.pageY+5)+"px";
		}
		else{ 
			if(document.documentElement.clientWidth>0){
				//$('#debug').html(20+' '+(event.clientX)+' '+(event.x)+' '+document.documentElement.scrollLeft);
				GetId("Cur").style.left=(5+event.clientX+document.documentElement.scrollLeft)+"px";
				GetId("Cur").style.top=(5+event.clientY+document.documentElement.scrollTop)+"px";
			} 
			else{
				GetId("Cur").style.left=(20+event.x+document.body.scrollLeft)+"px";
				GetId("Cur").style.top=(10+event.y+document.body.scrollTop)+"px";
			}
		}
		
		var hwin=getDocHeight();
		var wwin=getDocWidth();
		var cadout=false;
		var YOffset=window.pageYOffset?window.pageYOffset:document.documentElement.scrollTop;
		var XOffset=window.pageXOffset?window.pageXOffset:document.documentElement.scrollLeft;
		
		if( (parseInt(GetId("Cur").style.top)+GetId("Cur").offsetHeight) > (hwin+YOffset) )
			GetId("Cur").style.top=parseInt(GetId("Cur").style.top)-( (parseInt(GetId("Cur").style.top)+GetId("Cur").offsetHeight) - (hwin+YOffset) )+"px";
		var dec=30;
		if( (parseInt(GetId("Cur").style.left)+GetId("Cur").offsetWidth+dec) > (wwin+XOffset) )
			GetId("Cur").style.left=parseInt(GetId("Cur").style.left)-( (parseInt(GetId("Cur").style.left)+GetId("Cur").offsetWidth+dec) - (wwin+XOffset) )+"px";
	}
}

function getDocHeight() {
	var windowHeight;
	if (self.innerHeight) { // all except Explorer
	windowHeight = self.innerHeight;
	} 
	else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
	windowHeight = document.documentElement.clientHeight;
	} 
	else if (document.body) { // other Explorers
	windowHeight = document.body.clientHeight;
	}
	return windowHeight;
}

function getDocWidth() {
	var windowHeight;
	if (self.innerWidth) { // all except Explorer
	windowWidth = self.innerWidth;
	} 
	else if (document.documentElement && document.documentElement.clientWidth) { // Explorer 6 Strict Mode
	windowWidth = document.documentElement.clientWidth;
	} 
	else if (document.body) { // other Explorers
	windowWidth = document.body.clientWidth;
	}
	return windowWidth;
}

function montreBulle(text){
	if(!CurVisible){
		$('#InfoBulleText').html(text);
		$('#Cur').show();
		CurVisible=true;
	}
}
function cacheBulle(){
	if(CurVisible){
		$('#Cur').hide();
		CurVisible=false;
	}
}

document.onmousemove=move; // des que la souris bouge, on appelle la fonction move pour mettre a jour la position de la bulle.

