var reactions = {};

/* identifiant de l'article en question */
reactions.arti_id;
/* tableau des reactions prÃ©sentes sur l'article */
reactions.reactions = [];
/* url d'appel du PHP par ajax */
reactions.url = '/Inc/reactions/reactions.php';
/* page affichÃ©e */
reactions.current_page = 1;
/* infos utilisateur */
reactions.user = {};



/* ------------------------------------------- */



/* fonction qui verifie que la personne est bien identifiÃ©e wassup */
reactions.chkWassup = function( function_to_execute ) {
	var params = 'wassup=true&rand='+Math.random();
	new Json.Remote( reactions.url+'?'+params, { 
		'method':'get',
		'async':true,
		'onComplete':function(json) {
				if( json.multiple == "true" ) { reactions.updateProfile(json.accounts); return; }
				else if( json.auth == "false" ) { location.href = '/Inc/reactions/auth.php?arti_url='+location.pathname+'&reagir=true'; return; }
				else if( json.registered == "false" ) { reactions.create_new_blog(); return; }
				else { reactions.user = json; }

				if( function_to_execute ) {
					if (typeof function_to_execute == 'object') {
						var criterion = function_to_execute.constructor.toString().match(/array/i); 
						var is_array = ( criterion != null ) ? true : false;
					}
					else { var is_array = false; }
					if( is_array ) { for( var i = 0; i < function_to_execute.length; i++ ) { eval( function_to_execute[i] ); } }
					else { eval( function_to_execute ); }
				}
			},
		'onFailure':reactions.showProblemScreen() }).send();
};



/* ------------------------------------------- */



/* fonction qui rÃ©cupÃ¨re une page de rÃ©actions et la met dans l'attribut reactions.reactions */
reactions.getReactions = function(nb,max,arti_id) {
//	alert('nb : '+nb+' - max : '+max+' - arti_id : '+arti_id);
	switch(nb){case'-1':reactions.current_page=reactions.current_page==1?1:parseInt(reactions.current_page)-1;break;case'+1':reactions.current_page=reactions.current_page==max?max:parseInt(reactions.current_page)+1;break;default:reactions.current_page=parseInt(nb);break}
	/* on ne va chercher la page de rÃ©actions demandÃ©e en AJAX seulement si elle n'est pas dans le tableau */
	if(reactions.reactions[reactions.current_page] == undefined) {
		var params = 'id='+arti_id+'&page='+(reactions.current_page-1)+'&nb_per_page=5';
//		alert(reactions.url+'?'+params);
		new Json.Remote(reactions.url+'?'+params,{
			'method':'get', 
			'async':true, 
			'onComplete':function(json) { 
				reactions.reactions[reactions.current_page] = json; reactions.showReactions();
			}, 
			'onFailure': reactions.showProblemScreen() }).send();
	}
	else { reactions.showReactions(); }
};
	
/* affiche la page de rÃ©action donnÃ©e par reactions.current_page */
reactions.showReactions = function() {
	$('liste_reactions').empty();
	var ul_liste = new Element('ul');
	
	reactions.reactions[reactions.current_page].each(function(item,i) {
		var li = new Element('li');
		new Element('span',{'class':'date'}).setHTML(item.reacts_Date_format).injectInside(li);
		var tmp = new Element('span',{'class':'commentaires'});
		var commentaires_txt = item.reactions_to > 1 ? item.reactions_to+' commentaires' : item.reactions_to+' commentaire';
		new Element('a',{'href':'/commentaires-reaction/'+item.reacts_id+'.html','title':'AccÃ©der au contenu complet de la rÃ©action'}).setHTML(commentaires_txt).injectInside(tmp);
		tmp.injectInside(li);
		new Element('br').injectInside(li);
		var tmp = new Element('div',{'class':'author'});
		new Element('a',{'href':'/journal-de-reactions/'+item.user_id+'.html','title':'AccÃ©der au journal de rÃ©action de '+item.user_nickname}).setHTML(item.user_nickname).injectInside(tmp);
		//tmp.appendText(' a Ã©crit :');


		tmp.injectInside(li);
		if (item.reacts_Contenu.length > 100) {
			item.reacts_Contenu = item.reacts_Contenu.substring(0,100)+'...';
		}
		new Element('a',{'href':'/commentaires-reaction/'+item.reacts_id+'.html','title':'AccÃ©der au contenu complet de la rÃ©action'}).setHTML(item.reacts_Contenu+" ").injectInside(li);
		new Element('span',{'class':'chevrons'}).setHTML('&gt;&gt;').injectInside(li);
		li.injectInside(ul_liste);
	});
	ul_liste.injectInside('liste_reactions');
	/* on trouve l'interval des pages Ã  afficher */
	var tab_pages = $$('#reactions span.numbers a');
	var nb_pages = tab_pages.length;
	
	if( tab_pages.length > 10 ) {
		var min = parseInt(reactions.current_page) - 5 < 0 ? 0 : reactions.current_page - 5;
		if( min + 9 > nb_pages ) { var max = nb_pages; min = nb_pages - 9; } else { var max = min + 9; }
		/* affichage des sÃ©parateurs */
		$$('#reactions span.sep').each(function(item,i) {
			item.setStyle('display',(min <= i && i < max) ? '' : 'none');
		});
		/* affichage des numÃ©ros */
		$$('#reactions span.numbers').each(function(item,i) {
			item.setStyle('display',(min <= i && i <= max) ? '' : 'none');
		});
	}
	/* colorisation du numÃ©ro de page courante */
	$$('#reactions span.numbers a').each(function(item,i) {
		item.setStyle('color',(i+1) == reactions.current_page ? '#F50' : '');
	});
	/* refresh pub */
	refreshAction.run({'pathSupB':'pagination/page'+ (reactions.current_page)});
};



/* ------------------------------------------- */

/* onclick pour reagir */
reactions.reagir = function( type, id, dossier ) {
	if (dossier == null) {dossier = 'ARTICLES';}
	var extra_params = '';
	switch(type){case'commentaire':extra_params='reacts_to='+id+'&dossier='+dossier;break;case'reaction':extra_params='arti_url='+location.pathname+'&arti_id='+id+'&dossier='+dossier;type='rÃ©action';break;case'billet':break}
	reactions.chkWassup('reactions.open_react_popup("'+extra_params+'","'+type+'")');
};

/* affiche la text box pour pouvoir entrer sa reaction */
reactions.open_react_popup = function(extra_params,type) {
	if($('formulaire_reaction')){$('formulaire_reaction').remove();}
	var form = new Element( 'form', { 'id':'formulaire_reaction' } );
	form.appendText("Entrez le titre de votre rÃ©action :");
	new Element('br').injectInside(form);
	new Element('input',{'type':'text','id':'titre_reaction','maxlength':'55','styles':{'margin-top':'5px','margin-bottom':'5px','font-weight':'700','font-size':'11px','width':'85%'}}).injectInside(form);
	new Element('br').injectInside(form);
	form.appendText("Entrez le texte de votre "+type+" :");
	new Element('br').injectInside(form);
	new Element('textarea',{'id':'contenu','styles':{'margin-top':'5px','margin-bottom':'5px','height':'85px','font-size':'11px','width':'85%'}}).injectInside(form);
	new Element('br').injectInside(form);
	new Element('a',{'id':'LnkClickSendReact','href':'javascript:void(0)','title':'Envoyer votre rÃ©action','notChanged':'true','events':{ 'click':function() { this.style.display='none';reactions.sendReaction(extra_params); } } } ).setHTML('<img src="/Icons/ico_envoyer.gif" />').injectInside(form);
	form.injectTop("reactions");
	scroll($('reactions').getPosition().x,$('reactions').getPosition().y);
};

/* fonction qui envoie la reaction au back end */
reactions.sendReaction = function(extra_params) {
	if( $("titre_reaction").getValue() == "" || $("contenu").getValue() == "" ) {
		alert("Veuillez remplir les champs vides");
		$('LnkClickSendReact').style.display='';
	}
	else {
		/* parametre communs aux trois types de reactions */
		var params = 'titre='+$("titre_reaction").getValue()+'&text='+$("contenu").getValue().replace(new RegExp("(\r\n|\r|\n)","g"),"<br/>")+'&user_id='+reactions.user.user_info.user_id;
		if( typeof(extra_params) != '' ) { params += '&'+extra_params; }
		$$('#formulaire_reaction input','#formulaire_reaction textarea').each(function(item,i){item.disabled=true;});
		new Json.Remote( reactions.url+'?'+params, { 'method':'get', 'async':true, 'onComplete':reactions.onCompleteSendReaction, 'onFailure':reactions.showProblemScreen }).send();
	}
};
reactions.onCompleteSendReaction = function(json) {
	$('formulaire_reaction').remove();
	if( json.status == "OK" ) {
		new Element( 'div', { 'styles':{'background':'#eee','padding':'10px','margin':'10px','width':'85%','font-weight':'700'}, 'id':'info' } ).setHTML("Votre billet a bien Ã©tÃ© pris en compte. Il sera validÃ© sous peu par notre Ã©quipe de modÃ©ration.<br/>").setOpacity(0).injectBefore('reactions');
		scroll($('info').getPosition().x,$('info').getPosition().y);
		new Fx.Style("info","opacity",{	'onComplete':function() { setTimeout(function(){$('info').remove()},2000); }, duration:1000, transition:Fx.Transitions.linear }).start(0,1);
	}
};


/* ------------------------------------------- */


reactions.bad = function(id_reaction,nickname) {
// MODIFIE : AUTHENTIFICATION NON OBLIGATOIRE POUR CONTENU ILLICITE
//	reactions.chkWassup('reactions.open_inappropriate_popup("'+id_reaction+'","'+nickname+'")');
	reactions.open_inappropriate_popup(id_reaction,nickname);
};

/* fonction qui affiche un text box pour signaler une reaction innapropriÃ©e */
reactions.open_inappropriate_popup = function(id_reaction,nickname) {
	if($('formulaire_reaction')){$('formulaire_reaction').remove();}
	var form = new Element('form', { 'id':'formulaire_reaction' } );
	new Element('br').injectInside(form);
// MODIFIE : AUTHENTIFICATION NON OBLIGATOIRE POUR CONTENU ILLICITE
//	form.appendText('Entrez la raison de votre mÃ©contentement pour la rÃ©action de ');
//	new Element('em').setHTML(nickname).injectInside(form);
//	form.appendText(' :');
	form.appendText('Veuillez renseigner votre e-mail :');
	new Element('input',{'id':'userMail','styles':{'font-size':'11px','border':'1px solid #CCC'}}).injectInside(form);
	new Element('br').injectInside(form);
	form.appendText('Indiquez les raison pour lesquelles ce contenu vous paraÃ®t illicite :');
	new Element('br').injectInside(form);
	new Element('textarea',{'id':'contenu','styles':{'height':'78px','font-size':'11px','width':'85%','border':'1px solid #CCC'}}).injectInside(form);
	new Element('br').injectInside(form);
	form.appendText('NB : Votre adresse IP sera jointe Ã  votre demande');
	new Element('br').injectInside(form);
	new Element('a',{'href':'javascript:void(0)','title':'Envoyer votre dÃ©claration de contenu illicite','notChanged':'true','events':{ 'click':function() { reactions.sendInappropriate(id_reaction); } } } ).setHTML('<img src="/Icons/ico_envoyer.gif" />').injectInside(form);
	form.injectBefore('reactions');
	scroll($('formulaire_reaction').getPosition().x,$('formulaire_reaction').getPosition().y);
};

/* fonction qui signale une reaction innapropriÃ©e au back end */
reactions.sendInappropriate = function(id_reaction) {
	if($('contenu').getValue() == "") { alert("Veuillez saisir le texte de votre mÃ©contentement"); }
	else {
		var modele = /^[a-zA-Z0-9\.\-_]+@[a-zA-Z0-9\.\-_]+(\.[a-zA-Z]{2,5}){1,2}$/i;
		if(!modele.test($('userMail').getValue())) {
			alert("E-mail invalide.");
			return (false);
		}
// MODIFIE : AUTHENTIFICATION NON OBLIGATOIRE POUR CONTENU ILLICITE
	var userId = 0;
	try {
		userId = reactions.user.user_info.user_id;
	}
	catch (err) {
		userId = 0;
	}
//		var params = 'inappropriate='+id_reaction+'&contenu='+$('contenu').getValue()+'&user_id='+reactions.user.user_info.user_id;
		var params = 'inappropriate='+id_reaction+'&contenu='+$('contenu').getValue()+'&mail='+$('userMail').getValue()+'&user_id=' + userId;
		new Json.Remote( reactions.url+'?'+params, { 'method':'get', 'async':true, 'onComplete':reactions.onCompleteSendInappropriate, 'onFailure':reactions.showProblemScreen }).send(); 
	}
};
reactions.onCompleteSendInappropriate = function(json) {
	$('formulaire_reaction').remove();
	new Element( 'div', {'styles':{'background':'#eee','padding':'10px','margin':'10px','width':'85%','font-weight':'700'}, 'id':'info'}).setHTML("Nous avons prÃ©venu les modÃ©rateurs, merci!<br/>").setOpacity(0).injectBefore('reactions');
	scroll($('info').getPosition().x,$('info').getPosition().y);
	new Fx.Style( "info", "opacity", { 'onComplete':function() { setTimeout(function(){$('info').remove()},2000); }, 'duration':1000, 'transition':Fx.Transitions.linear }).start(0,1);
};



/* ------------------------------------------- */
/* affiche la text box pour pouvoir crÃ©er un nouveau journal */
reactions.create_new_blog = function() {
	if($('formulaire_reaction')){$('formulaire_reaction').remove();}
	var form = new Element( 'form', { 'id':'formulaire_reaction','styles':{'padding-top':'25px'} } );
	new Element('div',{'id':'CGU','styles':{'overflow':'auto','color':'#333','font-size':'10px','height':'300px','padding-right':'20px','width':'460px'}}).injectInside(form);
	new Element('input', { 'type':'checkbox', 'name':'OK_check', 'id':'OK_check', 'events':{'click':function() { reactions.chkNick(); } } } ).injectInside(form);
	form.appendText(" J'accepte les conditions d'utilisation du service RÃ©actions");
	new Element('br').injectInside(form); new Element('br').injectInside(form);
	form.appendText('Choisissez un pseudonyme : ');
	new Element('input', { 'type':'text', 'name':'nick', 'id':'nick', 'events':{ 'keyup':function() { reactions.chkNick(); } } } ).injectInside(form);
	new Element('span',{'id':'nick_disponibility','styles':{'padding-left':'5px'}}).injectInside(form);
	new Element('br').injectInside(form); new Element('br').injectInside(form);
	var submit_button = new Element('a',{'href':'javascript:void(0)','title':'Envoyer votre demande de crÃ©ation de journal','id':'submit_button','notChanged':'true'} );
	new Element('img',{'src':'/Icons/ico_envoyer.gif'}).injectInside(submit_button);
	submit_button.injectInside(form); form.injectBefore("reactions");
	new Ajax('/Inc/reactions/cgu.html',{'update':'CGU','method':'get'}).request();
	scroll($('formulaire_reaction').getPosition().x,$('formulaire_reaction').getPosition().y);
};

/* fonction qui vÃ©rifie la disponibilitÃ© d'un pseudo */
reactions.chkNick = function() {
	if( $('nick').getValue().length > 3 ) {
		new Element('img',{'src':'/Icons/ajax-loader.gif'}).injectInside('nick_disponibility');
		var params = 'nick='+$('nick').getValue();
		new Json.Remote( reactions.url+'?'+params, { 'method':'get', 'async':true, 'onComplete':reactions.onCompleteChkNick, 'onFailure':reactions.showProblemScreen }).send();
	}
	else { $('nick_disponibility').setHTML('pseudo trop court').setStyle({'color':'black'}); $('submit_button').disabled = true; }
};
reactions.onCompleteChkNick = function(json) {
	$('nick_disponibility').setHTML(json.status == 'OK' ? 'pseudo disponible' : 'pseudo indisponible').setStyles({ 'color':json.status == 'OK' ? 'green' : 'red' });
	if( json.status == 'OK' && $('OK_check').checked ) { $('submit_button').onclick = function() { reactions.sendNewBlogRequest(); }; }
	else {
		if( !$('OK_check').checked ) { $('submit_button').onclick =  function() { alert("Veuillez valider les conditions generales d'utilisation"); }; }
		else { $('submit_button').onclick =  function() { alert('Veuillez choisir un pseudo'); }; }
	}
};

/* fonction qui crÃ©e un nouveau journal */
reactions.sendNewBlogRequest = function() {
	var params = 'new_blog='+$('nick').getValue();
	new Json.Remote( reactions.url+'?'+params, { 'method':'get', 'async':true, 'onComplete':reactions.onCompleteSendNewBlogRequest, 'onFailure':reactions.showProblemScreen }).send();
};
reactions.onCompleteSendNewBlogRequest = function(json) {
	if( json.status == "OK" ) {
		$("formulaire_reaction").setOpacity(0).setHTML("Votre demande vient d'Ãªtre effectuÃ©e, vous pouvez maintenant rÃ©agir sur le site mais ce n'est que lorsque votre pseudonyme sera validÃ© que vous verrez vos rÃ©actions apparaÃ®tre.<br/><br/>" + '<input type="button" onClick="window.location.reload()" value="OK"/>').setStyles({ 'background':'#eee','padding':'10px','margin':'10px','height':'80px','float':'left','width':'85%','font-weight':'700' });
		scroll($('formulaire_reaction').getPosition().x,$('formulaire_reaction').getPosition().y);
		new Fx.Style("formulaire_reaction","opacity",{ duration:1000, transition:Fx.Transitions.linear }).start(0,1);
	}
	else { reactions.showProblemScreen(); }
};
			


/* ------------------------------------------- */



/* fonction d'affichage du texte d'erreur */
reactions.showProblemScreen = function() {
	new Element( 'div', {'styles':{'background':'#eee','padding':'10px','margin':'10px','width':'85%','font-weight':'700'}, 'id':'reagir'}).setHTML("Notre serveur de rÃ©actions rencontre actuellement des difficultÃ©s. Merci de rÃ©-essayer ultÃ©rieurement.<br/>").setOpacity(0).injectBefore('reactions');
	scroll($('reagir').getPosition().x,$('reagir').getPosition().y);
	new Fx.Style( "reagir", "opacity", { 'onComplete':function() { setTimeout(function(){$('reagir').remove()},2000); }, 'duration':1000, 'transition':Fx.Transitions.linear }).start(0,1);
};

/* affichage de l'aide */
reactions.showHelp = function() {
	if( $('help') != null ) { new Fx.Style("help","opacity",{'duration':500,'transition':Fx.Transitions.linear,'onComplete':function() { $('help').remove(); } }).start(1,0); }
	else {
		var liste = $$('div.liste');
		new Element('div', {'styles':{'padding':'10px','border-bottom':'1px solid #EEE','border-left':'1px solid #EEE','margin-bottom':'15px','height':'300px','overflow':'auto','z-index':'1000','background-color':'#FFF'},'id':'help'}).setOpacity(0).injectBefore(liste[0]);
		new Ajax('/Inc/reactions/aide.html',{'update':'help','method':'get'}).request();
		new Fx.Style("help","opacity",{'duration':1000,'transition':Fx.Transitions.linear}).start(0,1);
	}
};



/* ------------------------------------------- */




function sendUpdateRequest() {
	if (!$('milieu')) {$$('DIV.BlocCenterArticle')[0].id = 'milieu';}
	var qs='';
	$$('#jdr input').each(function(item,i){ 
		if( item.type == 'checkbox' ) { qs+=item.name+'='+item.checked+'&'; } 
		else if( item.type == 'text' || item.type == 'hidden' || item.type == "textarea" ) { qs+=item.name+'='+item.value.replace(new RegExp("(\r\n|\r|\n)","g"),"<br/>")+'&'; }
	}); 
	qs += qs.substr(0,qs.length-1);
	alert('/Inc/reactions/reactions.php?'+qs);
	new Ajax( '/Inc/reactions/reactions.php?'+qs, 
		{
		'method':'get', 'async':true,
		'onComplete':function(text,xml) {
			eval("var json = "+ text);
			if( json.status == "ok" ) {
				$('milieu').empty();
				new Element('div',{'class':'waiting_infos'}).setHTML('Votre profil est parti en modÃ©ration, vos rÃ©actions rÃ©apparaitront seulement si votre nouveau profil est validÃ©.').injectInside('milieu');
				scroll(0,0); setTimeout( function() { location.href = '/'; }, 5000);
			}
			else { if( json.status == "KO" ) {
				alert("Ce pseudo ne peut Ãªtre utilisÃ©, veuillez renouveler l'operation avec un autre pseudo Merci"); 
					}
				else {
				alert("Un problÃƒÂ¨me est survenu, veuillez renouveler l'operation ultÃƒÂ©rieurement"); 
					}
			}
		},
		'onFailure':function(text,xml) { alert("Un problÃ¨me est survenu, veuillez renouveler l'opÃ©ration ultÃ©rieurement"); }
		}
	).request();
};

function change_middle_content(url) {
	/* on récupère la page courante */
	if (!$('milieu')) {$$('DIV.BlocCenterArticle')[0].id = 'milieu';}
	mon_journal = $('milieu').innerHTML;
	new Fx.Style('milieu','opacity',
	{
		'onComplete':function() { 
//			$('milieu').empty(); 
			new Ajax(url, { 'update':'milieu', 'onComplete':	function() { new Fx.Style('milieu','opacity').start(0,1); }, 'method':'get' }).request(); 
		} 
	}).start(1,0);
}

function go_back() {
	if (!$('milieu')) {$$('DIV.BlocCenterArticle')[0].id = 'milieu';}
	new Fx.Style('milieu','opacity',{'onComplete':function(){$('milieu').empty();$('milieu').innerHTML=mon_journal;new Fx.Style('milieu','opacity').start(0,1)}}).start(1,0);
}

function agree() {
	$('agreement').setProperty( 'src', $('agreement').getProperty('src').match(/on.gif$/) ? '/Icons/coche_off.gif' : '/Icons/coche_on.gif' );
}

function valid_update_request() {
	if( $('agreement').getProperty('src').match(/on.gif$/) ) { sendUpdateRequest(); }
	else { alert("Veuillez accepter les conditions generales d'utilisation"); }
}

/* mise en cache de l'image pour ie6 */
var tmp = new Image();
tmp.src = '/Icons/coche_on.gif';


reactions.updateProfile = function( $JDRs ) {
	document.body.empty();
	var content = new Element('div',{'styles':{'textAlign':'justify','border':'1px solid #F50','margin':'50px 10px','padding':'10px 50px','background':'transparent url(/Icons/info.gif) no-repeat 10px center'}}).setHTML("Votre profil a subit une altÃ©ration suite Ã  un problÃ¨me technique, nous en sommes navrÃ©s.<br/><br/>Rassurez-vous, aucunes donnÃ©es n'ont Ã©tÃ© perdues.<br/><br/>Vous pouvez rÃ©cupÃ©rer votre Journal de rÃ©actions en choisissant parmis les pseudos que nous avons trouvÃ© vous concernant :<br/><br/>");
	var select_nick = new Element('select',{'id':'select_profile'});
	$JDRs.each(function(item,i) {
		new Element('option',{'value':item.user_id}).setHTML(item.user_nickname).injectInside(select_nick);
	});
	select_nick.injectInside(content);
	new Element('input',{'type':'button','value':'OK','events':{'click':function() {
		var qs = 'maj='+$('select_profile').options[$('select_profile').selectedIndex].value;
		new Ajax( '/Inc/reactions/reactions.php?'+qs, 
		{
		'method':'get',
		'async':false,
		'onComplete':function(text,xml) {
			eval("var json = "+ text);
			alert( json.status == "OK" ? "Votre profil a Ã©tÃ© mis Ã  jour, merci." : "Un problÃ¨me est survenu, veuillez renouveller l'opÃ©ration ultÃ©rieurement, merci" );
			location.href = '/';
		},
		'onFailure':function(text,xml) { alert("Un probleme est survenue, veuillez renouveler l'operation ulterieurement"); }
		}
	).request();
	}}}).injectInside(content);
	new Element('br').injectInside(content);new Element('br').injectInside(content);
	content.appendText("Si aucun de ces journaux ne vous appartiennent, vous pouvez en crÃ©er un nouveau en cliquant ");
	new Element('a',{'href':'javascript:void(0)','events':{'click':function(){ new reaction().create_new_blog(); }}}).setHTML('<strong>ici</strong>').injectInside(content);
	new Element('div',{'id':'reactions'}).injectInside(content);
	content.injectInside(document.body);
}

