//pour écouter le clavier
//document.onkeyup = onKeyUp;

function onKeyUp(event) {
	code = event.keyCode;
	if (code == 27) {
		if (elementSelected != -1)
			unselectElement(elementSelected);
		elementSelected = -1;
	}
}

var Photo = {
	//édition de la légende
	edit_legende: function(evt){
		Event.stop(evt);
		elmt = Event.element(evt);

		new Event.stopObserving(elmt, 'click', Photo.edit_legende);

		id = elmt.readAttribute('id').split('_')[1];
		legende_value = elmt.firstChild.nodeValue;

		elmt.update('<input type="text" name="legende_'+id+'" id="inputlegende_'+id+'" value="'+legende_value+'" />');
		elmt.toggleClassName('champ_modif');

		function send_request(evt, id, elmt){	
			Field.disable('inputlegende_'+id);
			new Ajax.Request('xml/modif.php', {
				method: 'post',
				postBody: $H({'id':id, 'legende':$F('inputlegende_'+id)}).toQueryString(),
				onSuccess: function(){
					elmt.update($F('inputlegende_'+id));
					elmt.removeClassName('champ_modif');
					new Event.observe(elmt, 'click', Photo.edit_legende);
				},
				onFailure: function(){
					elmt.update('Modification Impossible');
					elmt.removeClassName('champ_modif');
				}
			});


		}

		//si on clique à côté
		new Event.observe('inputlegende_'+id, 'blur', function(e){
			send_request(e, id, elmt);
		});
		//si la touche ok est utilisée on enleve le onblur et fait le requete
		new Event.observe('inputlegende_'+id, 'keypress', function(e){
			if (e.keyCode == 13 || e.keyCode == 27) {
				send_request(e, id, elmt);
			}
		});

		//focus dans l'input et selection du texte
		Field.activate('inputlegende_'+id);
	},
	//édition date
	edit_date: function(e){
		Event.stop(e);
		elmt = Event.element(e);

		new Event.stopObserving(elmt, 'click', Photo.edit_date);
		
		id = elmt.readAttribute('id').split('_')[1];
		elmt.update('<input type="text" class="calendar" name="inputdate_'+id+'" id="inputdate_'+id+'" value="'+elmt.firstChild.nodeValue+'" />');
		elmt.toggleClassName('champ_modif');
		//Cal_photo_div = new Element('div', {'id':'cal_date','class':'googleblue'});
		//Element.insert(elmt, {'after':Cal_photo_div});
		//Cal_photo = new scal('cal_date', 'inputdate_'+id, {updateformat: 'dd/mm/yyyy'})
		
		open_scal(e, 'inputdate_'+id, Photo.edit_date_req);
	},
	edit_date_req: function(d, id){
		elmt = Event.findElement('p');
		Field.disable('inputdate_'+id);
		new Ajax.Request('xml/modif.php', {
			method: 'post',
			postBody: $H({'id':id, 'date':d}).toQueryString(),
			onSuccess: function(){
				elmt.update($F('inputdate_'+id));
				elmt.removeClassName('champ_modif');
				new Event.observe(elmt, 'click', Photo.edit_date);
			},
			onFailure: function(){
				elmt.update('Modification Impossible');
				elmt.removeClassName('champ_modif');
			}
		});
	},
	suppr: function(evt){
		elmt = Event.element(evt);
		if(!elmt.hasClassName('photo')){
			elmt = elmt.up('div');
		}
		if(Confirm.suppr()){
			id = elmt.readAttribute('id').split('_')[1];
			new Ajax.Request('xml/suppr.php', {
				postBody: 'id='+id,
				onSuccess: function(){
					Element.remove(elmt);
					if($$('#photos .photo').any() === false){
						if($('alerte_aucunephoto'))
							Element.show('alerte_aucunephoto');
						else
							new Element.insert('photos', {'top':'<p class="alerte" id="alerte_aucunephoto">Aucune photo</p>'});
						close_alerte('alerte_aucunephoto');
					}
				},
				onFailure: function(){
					if($('alerte_aucunephoto'))
						Element.show('alerte_supprphoto');
					else
						new Element.insert('photos', {'top':'<p class="alerte" id="alerte_supprphoto">Impossible de supprimer la photo</p>'});
					close_alerte('alerte_supprphoto');
				}
			});
			
		}
	},
	change_album: function(element, album, album_en_cours){
		if(album != album_en_cours){
			Element.hide(element);
			id = element.attributes[0].nodeValue;
			id = id.split('photo');
			sendData('id='+id[1]+'&album='+album, 'xml/change.php', 'POST');
		}
		else
			Draggables.endDrag(element);

	},
	rotate_right: function(element){
		rotate(element, "right");
	},
	rotate_left: function(element){
		rotate(element, "left");
	},
	rotate: function(element, direction){
		id = element.id;
		new Ajax.Request("admin.php", {
			postBody: $H({"id":id,"direction":direction})
		});
	},
	showButtons: function(evt){
		elmt = Event.element(evt);
		if(elmt.hasClassName('photo'))
			mbuttons = $(elmt).down('.mbuttons');
		else
			mbuttons = $(elmt).up('.photo').down('.mbuttons');
		mbuttons.show();
	},
	hideButtons: function(evt){
		elmt = Event.element(evt);
		if(elmt.hasClassName('photo'))
			mbuttons = $(elmt).down('.mbuttons');
		else
			mbuttons = $(elmt).up('.photo').down('.mbuttons');
		new Effect.Fade(mbuttons, {duration: 1});
	}
	
}

var Photos = {
	activate: function(){
		$$('.img_suppr').each(function(element){
			new Event.observe(element, 'click', Photo.suppr);
		});
		$$('.date').each(function(elmt){
			new Event.observe(elmt, 'click', Photo.edit_date);
		});
		$$('.legende').each(function(elmt){
			new Event.observe(elmt, 'click', Photo.edit_legende);
		});
		$$('.photo').each(function(elmt){
			new Event.observe(elmt, 'mouseenter', Photo.showButtons);
			new Event.observe(elmt, 'mouseleave', Photo.hideButtons);
		});
	},
	desactivate: function(){
		$$('.img_suppr').each(function(element){
			new Event.stopObserving(element, 'click', Photo.suppr);
		});
		$$('.date').each(function(elmt){
			new Event.stopObserving(elmt, 'click', Photo.edit_date);
		});
		$$('.legende').each(function(elmt){
			new Event.stopObserving(elmt, 'click', Photo.edit_legende);
		});
		$$('.photo').each(function(elmt){
			new Event.stopObserving(elmt, 'mouseenter', Photo.showButtons);
			new Event.stopObserving(elmt, 'mouseleave', Photo.hideButtons);
		});
	}

}

function open_scal(e, id_field, callback){
	Field.activate(id_field);
	if(!$('scal_'+id_field)){
		p_input_wrapper = $(id_field).up('p');
		scal_div = new Element('div', {'id':'scal_'+id_field,'class':'scal tinyscal','style':'display:none'});
		Element.insert(p_input_wrapper, {'after': scal_div});
		nom_cal = 'Cal'+id_field;
		window['Cal'+id_field] = new scal('scal_'+id_field, id_field, {updateformat: 'dd/mm/yyyy', openeffect: Element.show, closeeffect: Element.hide});
		new Event.observe($('scal_'+id_field).select('.cal_wrapper')[0], 'click', function(e){
			window['Cal'+id_field].toggleCalendar();
			input_value = $F('input_date_album');
			p_input_wrapper.removeClassName('champ_modif').addClassName('champ');
			p_input_wrapper.update(input_value);
			callback(input_value);
		});
		
	}
	var d_in = $F(id_field).split('/');
	var date = new Date(d_in[1]+'/'+d_in[0]+'/'+d_in[2]);
	window['Cal'+id_field].setCurrentDate(isNaN(date) ? new Date() : date);
	window['Cal'+id_field].toggleCalendar();
}


function menu_open_close(evt){
	elmt = Event.element(evt);
	id = "menu-"+elmt.id.split('-')[1];
	
	new Effect.toggle($(id), "blind", {afterFinish: function(){
		if($(id).visible())
			elmt.writeAttribute('src', 'img/puce_moins.png');
		else
			elmt.writeAttribute('src', "img/puce_plus.png");
	}});
	
}

function close_alerte(id){
	id = $(id);
	new Effect.Pulsate(id, {
		pulses: 2, 
		afterFinish: function(){
			setTimeout(function(){
				new Effect.Fade(id);
			}, 5000);
		}
	});
}

var Album = {
	edit_nom: function(e){
		obj = Event.findElement(e, 'p');
		id = $F('id_m');
		nom_value = obj.firstChild.nodeValue;
		obj.removeClassName('champ').addClassName('champ_modif');
		input_elmt = new Element('input', {'value':nom_value, 'name':'nom_album', 'type':'text', 'id':'input_nom_album'});
		input = obj.update(input_elmt);
		Event.stopObserving(obj, 'click', Album.edit_nom);
		new Event.observe(input_elmt, 'blur', Album.edit_request_nom_album);
		new Event.observe(input_elmt, 'keypress', function(event){
			code = event.keyCode;
			if (code == 13 || code == 27)
				Album.edit_request_nom_album();
		});
		input_elmt.focus();
		input_elmt.select();
	},
	
	edit_date: function(e){
		elmt = Event.element(e);
		obj = Event.findElement(e, 'p');
		id = $F('id_m');
		nom_value = obj.firstChild.nodeValue;
		obj.removeClassName('champ').addClassName('champ_modif');
		input_elmt = new Element('input', {'value':nom_value, 'name':'date_album', 'type':'text', 'id':'input_date_album', 'class':'calendar'});
		input = obj.update(input_elmt);
		Event.stopObserving(obj, 'click', Album.edit_date);
		/*new Event.observe(input_elmt, 'blur', Album.edit_request_date_album);
		new Event.observe(input_elmt, 'keypress', function(event){
			code = event.keyCode;
			if (code == 13 || code == 27) {
				Album.edit_request_date_album();
			}
		});*/
		/*if(!$('cal_date_album')){
			div = new Element('div', {'id':'cal_date_album', 'class':'googleblue'});
			$('input_date_album').insert({'after':div});
			Cal = new scal('cal_date_album', 'input_date_album', {oncalchange: Album.edit_request_date_album, updateformat: 'dd/mm/yyyy'});
			new Element.observe('cal_date_album', 'click', Album.edit_request_date_album)
		}
		$('cal_date_album').show();*/
		open_scal(e, input_elmt, Album.edit_request_date_album);
	},
	
	edit_pub: function(e){
		id = $F('id_m');
		obj = Event.element(e);
		if(obj.checked)
			sendData('id='+id+'&pub=1', 'xml/modif_album.php', 'POST');
		else
			sendData('id='+id+'&pub=0', 'xml/modif_album.php', 'POST');
	},
	
	edit_request_nom_album: function(){
		input_value = $F('input_nom_album');
		$('nom_album').removeClassName('champ_modif').addClassName('champ');
		$('nom_album').update(input_value);
		sendData('id='+id+'&nom_album='+input_value, 'xml/modif_album.php', 'POST');
		new Event.observe('nom_album', 'click', Album.edit_nom);
	},
	edit_request_date_album: function(d){
		sendData('id='+id+'&date='+d, 'xml/modif_album.php', 'POST');
		new Event.observe('date_album', 'click', Album.edit_date);
	}
}


function createNewAlbum(){
	var name = prompt("Quel est le nom de votre nouvel album ?", "");
	if(name){
		name = encodeURI(name);
	}
	else if(name != null){
		name = "Nouvel Album";
	}
	sendData('nom_album='+name, 'xml/new_album.php', 'POST');
}


/**
* Permet d'envoyer des données en GET ou POST en utilisant les XmlHttpRequest
*
* @param string Les variables sous forme x=1&y=2&z=4...
* @param string Page de destination ex: live.php
* @param string method d'envoi : POST ou GET
*/
function sendData(data, page, method){
    if(document.all){
        //Internet Explorer
        var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP") ;
    }
    else{
        //Mozilla
        var xmlhttp = new XMLHttpRequest();
    }
    //définition de l'endroit d'affichage:
    var content = document.getElementById("contenu");
    //si on envoie par la méthode GET:
    if(method == "GET"){
        if(data == 'null'){
            //Ouverture du fichier sélectionné:
            xmlhttp.open("GET", page);
        }//fin if
        else{
            //Ouverture du fichier en methode GET
            xmlhttp.open("GET", page+"?"+data, true);
        }
    }
    else if(method == "POST"){
        //Ouverture du fichier en methode POST
        xmlhttp.open("POST", page, true);
    }
    //Ok pour la page cible
    xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
			//alert(xmlhttp.responseText);
			//on fait rien quand le script repond
		}  
    }
    if(method == "GET"){
        xmlhttp.send(null);
    }
    else if(method == "POST"){
        xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        xmlhttp.send(data);
    }
}

//Fontions pour confirmations
var Confirm = {
	suppr: function(){
		return confirm("Êtes-vous sûr de vouloir supprimer cette photo ?");
	},
	suppr_album: function(e){
		Event.stop(e);
		if(confirm("Êtes-vous sûr de vouloir supprimer cet album ?"));
			document.location = Event.element(e).readAttribute('href');
	}
}

//Diaporama !

//var pour le diaporama : PeriodicalExecuter
var pe;
var pause;

function diapo_suivante(action){
	new Ajax.Request('xml/diapo.php',
	{
		postBody: $H({'album':$F('id_album_courant'),'photo':$F('id_photo_courant'),'sens':'next'}).toQueryString(),
		onSuccess: function(req){
				Rep = {
					width: req.responseXML.getElementsByTagName('width')[0].firstChild.nodeValue,
					height: req.responseXML.getElementsByTagName('height')[0].firstChild.nodeValue,
					id: req.responseXML.getElementsByTagName('id')[0].firstChild.nodeValue,
					src: req.responseXML.getElementsByTagName('src')[0].firstChild.nodeValue,
					legende: req.responseXML.getElementsByTagName('legende')[0].firstChild.nodeValue
				}
				if(action == 'auto'){
					new Effect.Fade('photo_diapo', {
						afterFinish: function(){
							new Effect.Morph('div_diapo', {
								style: 'width: '+(parseInt(Rep.width)+10)+'px; height: '+(parseInt(Rep.height)+50)+'px; margin-left: -'+(Rep.width/2)+'px; margin-top: -'+(Rep.height/2)+'px;left:50%;top:50%;',
								afterFinish : function(){
									$('photo_diapo').setAttribute('src', 'photos/'+Rep.src);
									$('photo_diapo').setAttribute('width', Rep.width);
									$('photo_diapo').setAttribute('height', Rep.height);
									Element.setStyle('photo_diapo', {width: Rep.width, height: Rep.height});
									$('id_photo_courant').setAttribute('value', Rep.id);
									Element.update('diapo_legende', Rep.legende);
									new Event.observe('photo_diapo', "load", function(){
										new Effect.Appear('photo_diapo', {duration: 2});
									});
								}
							});
						}
					});
					
				}
				else{
					pe.stop();
					Element.hide('photo_diapo');
					$('photo_diapo').setAttribute('src', 'photos/'+req.responseXML.getElementsByTagName('src')[0].firstChild.nodeValue);
					$('photo_diapo').setAttribute('width', req.responseXML.getElementsByTagName('width')[0].firstChild.nodeValue);
					$('photo_diapo').setAttribute('height', req.responseXML.getElementsByTagName('height')[0].firstChild.nodeValue);
					Element.setStyle('photo_diapo', {width: req.responseXML.getElementsByTagName('width')[0].firstChild.nodeValue, height: req.responseXML.getElementsByTagName('height')[0].firstChild.nodeValue});
					$('id_photo_courant').setAttribute('value', req.responseXML.getElementsByTagName('id')[0].firstChild.nodeValue);
					Element.update('diapo_legende', req.responseXML.getElementsByTagName('legende')[0].firstChild.nodeValue);
					new Event.observe('photo_diapo', "load", function(){
						new Effect.Appear('photo_diapo', {duration: 2});
					});
					if(play)
						diaporama();	
				}
	
		}
	});
}

function diapo_precedente(){
	new Ajax.Request('xml/diapo.php',
	{
		postBody: $H({'album':$F('id_album_courant'),'photo':$F('id_photo_courant'),'sens':'prev'}).toQueryString(),
		onSuccess: function(req){
			pe.stop();
			Element.hide('photo_diapo');
			$('photo_diapo').setAttribute('src', 'photos/'+req.responseXML.getElementsByTagName('src')[0].firstChild.nodeValue);
			$('photo_diapo').setAttribute('width', req.responseXML.getElementsByTagName('width')[0].firstChild.nodeValue);
			$('photo_diapo').setAttribute('height', req.responseXML.getElementsByTagName('height')[0].firstChild.nodeValue);
			Element.setStyle('photo_diapo', {width: req.responseXML.getElementsByTagName('width')[0].firstChild.nodeValue, height: req.responseXML.getElementsByTagName('height')[0].firstChild.nodeValue});
			$('id_photo_courant').setAttribute('value', req.responseXML.getElementsByTagName('id')[0].firstChild.nodeValue);
			Element.update('diapo_legende', req.responseXML.getElementsByTagName('legende')[0].firstChild.nodeValue);
			new Event.observe(window, "load", function(){
				new Effect.Appear('photo_diapo', {duration: 2});
			});
			if(play)
				diaporama();
		}
	});
}

function fermer_diapo(){
	Element.hide('div_diapo');
	new Effect.Fade('darkenBackground');
	pe.stop();
	Event.stopObserving(window, 'keypress', function(e){
		if(e.keyCode == Event.KEY_ESC){
			fermer_diapo();
		}
	});
}
function appear(){
	new Effect.Appear('photo_aff', {duration: 2});
	$('loading_aff').hide();
}

function diaporama(){
	if(pe)
		pe.stop();
	pe = new PeriodicalExecuter(function(){diapo_suivante('auto')}, $F('vitesse_diapo'));
	if($('btn_diapo_play')){
		new Event.stopObserving('btn_diapo_play', 'click', diaporama);
		Element.replace('btn_diapo_play', '<a href="#" id="btn_diapo_pause">Pause</a>');
		new Event.observe('btn_diapo_pause', 'click', pause_diaporama);
	}
	play = true;
}
function pause_diaporama(){
	pe.stop();
	new Event.stopObserving('btn_diapo_pause', 'click', pause_diaporama);
	Element.replace('btn_diapo_pause', '<a href="#" id="btn_diapo_play">Play</a>');
	new Event.observe('btn_diapo_play', 'click', diaporama);
	play = false;
}

//fin diaporama

function loading(){
	if($('photo_aff')){
		new Effect.Appear('photo_aff', {duration: 2});
		$('loading_aff').hide();
	}
	if($('form_modif_album')){
		new Event.observe('nom_album', 'click', Album.edit_nom);
		new Event.observe('date_album', 'click', Album.edit_date);
		new Event.observe('pub_album', 'click', Album.edit_pub);
	}
	
	if($('upload_form')){
		new Event.observe('upload_field', 'change', function(){
			$('upload_form').submit();
			show_spinner();
			Form.disable('upload_form');
		})
		new Event.observe('upload_form', 'submit', show_spinner);
	}
	if($('btn_diapo_suiv')){
		new Event.observe('btn_diapo_suiv', 'click', diapo_suivante);
	}
	
	if($('photos')){
		Photos.activate();
	}
	if($('login_form')){
		Field.focus('pseudo');
	}
	if($('link_suppr_album')){
		new Event.observe('link_suppr_album', 'click', Confirm.suppr_album);
	}
	
	if($('principale')){
		$('principale').select('.alerte').each(
			function(elmt){
				close_alerte(elmt);
			}
		);
	}
	
	if($('page_selector')){
		new Event.observe('page_selector', 'change', function(e){
			window.location.href = 'galerie.php?album='+$F('album')+'&p='+$F('page_selector');
		})
	}
	
	//pour diaporama
	if($('btn_diapo')){
		new Event.observe('btn_diapo', 'click', function(){
			new Effect.Appear('darkenBackground', { to: 0.95, duration: 2, afterFinish: function(){
					//new Effect.Grow('div_photo_diapo', {direction: 'top-left'});
					new Effect.Appear('div_diapo', {duration: 2});
					new Event.observe(window, 'keypress', function(e){
						if(e.keyCode == Event.KEY_ESC){
							fermer_diapo();
						}
					});
					diaporama();
					new Form.Element.EventObserver('vitesse_diapo', diaporama);
				}
			});
		});
		new Event.observe('btn_diapo_suiv', 'click', diapo_suivante);
		new Event.observe('btn_diapo_prec', 'click', diapo_precedente);
		new Event.observe('btn_diapo_fermer', 'click', fermer_diapo);
		new Event.observe('btn_diapo_pause', 'click', pause_diaporama);
		
		
	}
	//devenir membre
	if($('membre')){
		Element.hide('part2');
		function step1(e){
			Element.show('part1');
			Element.hide('part2');
		}
		function step2(e){
			Event.stop(e);
			Element.hide('part1');
			Element.show('part2');
			Event.stopObserving('form_membre', 'submit', step2);
		}
		new Event.observe('form_membre', 'submit', step2);
		new Event.observe('step2', 'click', step2);
		new Event.observe('step1', 'click', step1);
	}
	
	$$(".puce_menu").each(function(elmt){
		new Event.observe(elmt, 'click', menu_open_close);
	});
}

function show_spinner(){
	Element.show($('spinner'));
}

new Event.observe(window, "load", loading);

