// JavaScript Document

var fckCount = 0;
var zoomFactor;
var originalImageWidth;
var lastPath;
var lastPathDiv;

$(document).ready(function() { init(); });

function init(){

	// Masque la zone de message
	$('#msgbox').fadeOut(200);
	
	// ajax form...
	$('#editForm').ajaxForm({success:showResponse, dataType:'json'});
	
	// ajax form...
	$('#editFormDiv').ajaxForm({success:showResponseDiv, dataType:'json'});
	
	$('#editFormInscription').ajaxForm({success:showResponseInscription, dataType:'json'});
	
	// tabs...
	$("#langues").tabs();
	
	// FCKEditor...
	$.fck.config = {path: 'fckeditor/', height:300 };
	$('.fckeditor').fck({ toolbar:'Basic' });
	fckCount = $('.fckeditor').length;
	
	// Désactive les boutons en attendant que FCKEditor soit prêt...
	if(fckCount > 0) $('.interfaceButton').attr("disabled","disabled");
	
	// aide en ligne...
	$('.helpLink').click(function(){
		if($(this).hasClass('visibleHelp')){
			$(this).html('?').removeClass('visibleHelp');
		} else {
			$(this).load('ajax.php?msgKey='+$(this).attr('id')).addClass('visibleHelp');
		}
	});
	
	// album photo
	$("#pics").sortable({
		axis:'y',
		opacity:50,
		revert: true,
		stop:function(){
			saveOrder();
		}
	});
	
	// items (générique)
	$("#itemsDiv").sortable({
		axis:'y',
		opacity:50,
		revert: true,
		stop:function(){
			saveItemsOrder();
		}
	});
	
	// génération de thumbnail...
	zoomFactor = 100;
	originalImageWidth = $('#imgImg').attr('width');
	$('#imgdiv').draggable({
		stop: function(event,ui){
			$('#offsetLeft').val(Math.abs(ui.position.left));
			$('#offsetTop').val(Math.abs(ui.position.top));
			updateImage();
		}
	});
	
	// fin de init();
}

// récupère la réponse du serveur (array json)
function showResponse(data){
	$('#msgbox').css("backgroundColor", data.color);
	$('#msgbox').html(data.message).fadeIn(300).fadeOut(2000);
	$('#itemID').val(data.newID);
	itemID = data.newID;
	if(data.lastPath != ""){ lastPath = data.lastPath; }
	if(data.action == 'showpics'){ showpics(itemID); }
	if(data.action == 'reloadContent') { reloadContent(); }
	if(data.action == 'reloadAlbum') { reloadAlbum(itemID); }
	if(data.action == 'reloadRealisation') { reloadRealisation(itemID); }
}

// récupère la réponse du serveur (array json)
function showResponseDiv(data){
	$('#msgbox').css("backgroundColor", data.color);
	$('#msgbox').html(data.message).fadeIn(300).fadeOut(2000);
	$('#itemID').val(data.newID);
	itemID = data.newID;
	path = "";
	if(data.lastPathDiv != ""){ path = data.lastPathDiv; }
	if(data.action == 'showpics'){ showpics(itemID); }
	if(data.action == 'reloadContent') { reloadContentDiv(path,data.div); }
}

// récupère la réponse du serveur (array json)
function showResponseInscription(data){
	$('#msgbox').css("backgroundColor", data.color);
	$('#msgbox').html(data.message).fadeIn(300).fadeOut(2000);
	$('#itemID').val(data.newID);
	itemID = data.newID;
	path = data.path;
	
	//alert("ok");
	if(data.action == 'reloadContent' && data.color != "red") { 
		window.location = path;
	}else if (data.color == "red"){
		document.getElementById("captcha_code").value = "";
		document.getElementById('captcha').src = data.siteRoot+'/securimage/securimage_show.php?' + Math.random();		
	}
}

// changement d'affichage
function loadContentDiv(path,div){
	$(div).fadeOut(200,function(){
		$(this).load(path, {}, function(){
			init();
			$(this).fadeIn('fast');
		});
	});
}

// relance la dernière requête - recharge le formulaire
function reloadContentDiv(path,div){
	loadContentDiv(path,div);
}


// changement d'affichage
function loadContent(path){
	lastPath = path;
	$('#mainContent').fadeOut(200,function(){
		$(this).load(path, {}, function(){
			init();
			$(this).fadeIn('fast');
		});
	});
}



// relance la dernière requête - recharge le formulaire
function reloadContent(){
	loadContent(lastPath);
}


// réactive le bouton "save" quand les éditeurs sont prêts
function FCKeditor_OnComplete( editorInstance ){
	fckCount --;
	if(fckCount == 0){
		$('.interfaceButton').removeAttr("disabled");
	}
}

/*
// recharge le formulaire d'édition d'un album
//(après enregistrement d'un nouvel album)
function reloadAlbumEditForm(){
	javascript:loadContent('albumEdit.php?itemID='+itemID);
}
*/

// reloadAlbum
function reloadAlbum(albumID){
	//alert('albumEdit.php?itemID='+albumID);
	loadContent('albumEdit.php?itemID='+albumID);
}

// reloadRealisation
function reloadRealisation(realisationID){
	//alert('realisationEdit.php?itemID='+realisationID);
	loadContent('realisationEdit.php?itemID='+realisationID);
}

// remplace le texte du DIV #titlebar
function setTitle(newTitle){
	$('#titlebar').html(newTitle);
}

// affiche un texte d'aide sur un contrôle
function showHelp(msgKey,ctrl){
	ctrl.after('<span id="helpTxt"></span>');
	$('#helpTxt').load('ajax.php?msgKey='+msgKey);
}

// Affiche les photos d'un album
function showpics(albumID){
	$('#pics').load("ajax.php?albumID="+albumID);
}

// TODO: trouver un nom de fonction moins général...
function saveOrder(){
	$('#debug').html('enregistrement...');
	var strout = '';
	$('.itemDiv').each(function(i){
		strout += ';' + this.id.replace('item','');
	});
	if(strout != ''){
		$('#debug').load("action.php", {setalbumorder:itemID,photos:strout}, function(){});
	}
	else {
		alert('aucune photo');
	}
}

// fonction générique pour tri arbitraire
function saveItemsOrder(){
	var strout = '';
	var tableName = $('#vilaincabotData').text();
	$('.itemDiv').each(function(i){
		strout += ';' + this.id.replace('item','');
	});
	if(strout != ''){
		$('#debug').load("action.php", {action:'setItemsOrder',data:strout,table:tableName}, function(){ /*alert('OK');*/ });
	}
}

// TODO: vérifier utilité??
function deletePic(pic){
	if(confirm('Voulez-vous supprimer la photo?')){
		//document.getElementById(pic).parentNode.removeChild(document.getElementById(pic));
		$(pic).remove();
		saveOrder();
	}
}

// reload les photos d'un album
function refreshPhotoSelection(pageID){
	$('#photoselection').load("ajax.php?getPhotos="+pageID);
}

// suppression d'un item dans une liste (générique)
function deleteItem(contenttype,contentid){
	var okToDelete = confirm('?');
	var itemID = contentid;
	
	if(okToDelete) $('#debug').load("action.php", {"deletecontent":contenttype,"id":contentid,"action":0}, function(){ $('#item'+itemID).remove(); });
}

// génération de thumbnails ci-dessous...


function zoomOut(){
	if(zoomFactor > 10){
		zoomFactor -= 5;
		updateImage();
	} else {
		alert('Minimum!');
	}
}

function zoomIn(){
	if(zoomFactor < 100){
		zoomFactor += 5;
		updateImage();
	} else {
		alert('Maximum!');
	}
}

function centerImage(){
	$('#imgdiv').css('top','0');
	$('#imgdiv').css('left','0');
}

function updateImage(){
	var resizedImageWidth = Math.abs(originalImageWidth*zoomFactor/100);
	$('#imgImg').attr('width',resizedImageWidth);
	$('#zoomFactor').val(zoomFactor);
}

