﻿//Au chargement de la page, on attribue les events
J(document).ready(function(){
    if(J('.askforedit')){
    	J('.askforedit').bind('click',{},onAskForEdit);
    }
    if(J('.trashit')){
    	J('.trashit').bind('click',{},onTrashIt);
    }
    if(J('.answer_askforedit')){
    	J('.answer_askforedit').bind('click',{},onAnswerAskForEdit);
    }
    if(J('#return_edit')){
        J('#return_edit').data('action','allow');
    	J('#return_edit').bind('click',{},onAnswerAskForEdit);
    }
    if(J('#no_return_edit')){
        J('#no_return_edit').data('action','deny');
    	J('#no_return_edit').bind('click',{},onAnswerAskForEdit);
    }

});

//Mise à jour du statut de l'article
function updateArticleState(pressbutton,url){
    reinitInputWhonotify();
    var url = url+'&action='+pressbutton;
    var notify = '&notify=0&who_notify[]=0';
    if(pressbutton=='refuse'){
    	J(location).attr('href',url+notify);
    }
    var isAdmin = eval(J('[name=isAdmin]').val());
    var isModerator = eval(J('[name=isModerator]').val());
    var isContrib = eval(J('[name=isContributor]').val());
    var isAuthor = eval(J('[name=isAuthor]').val());
    var q;
    J.alerts.okButton = 'Notifier';
    J.alerts.cancelButton = 'Ne pas notifier';
    if(J('[name=notified]').val()=='0'){
            // first time
            q = 'Qui souhaitez-vous informer ?\r\n';

            if(isModerator){
                    text = getLabels(new Array('contributors','moderators'), q);
            }else if(isAdmin){
                    text = getLabels(new Array('contributors','administrators'), q);
            }
    }else{
            // autre
            q = 'Qui souhaitez-vous informer ?\r\n';
            if(isModerator){
                    text = getLabels(new Array('author','contributors','moderators'), q);
            }else if(isAdmin){
                    text = getLabels(new Array('author','contributors','moderators','administrators'), q);
            }
    }
    jConfirm(J(text).html(),
        'Confirmation de notification',
        function(r){
            if(r){
                notify = '&notify=1&'+J('[name=who_notify[]]:checked').serialize();
            }
            J(location).attr('href',url+notify);
        });
    handleClickLabels();
}

//Demande d'édition
function onAskForEdit(event){
	J.alerts.okButton = '&nbsp;Ok&nbsp;';
	J(event.currentTarget).unbind('click',onAskForEdit);
	var href = event.currentTarget.href;
	J.get(href,{},function(data){
            if(data.info != undefined){
                    //success
                    var success = '';
                    if(data.info.maj != undefined){
                            success += data.info.maj;
                    }
                    if(data.info.notifs != undefined){
                            if(success != '') success += '<br/>';
                            success += data.info.notifs;
                    }
            }
            if(data.error != undefined){
                    //error
                    var error = '';
                    if(data.error.maj != undefined){
                            error += data.error.maj;
                    }
                    if(data.error.access != undefined){
                            if(error != '') error += '<br/>';
                            error += data.error.access;
                    }
                    if(data.error.notifs != undefined){
                            if(error != '') error += '<br/>';
                            error += data.error.notifs;
                    }
            }
            if(error!=''){
                    jAlert(error,"Résultat de demande d'édition");
            }
            if(success!=''){
                    jAlert(success,"Résultat de demande d'édition");
            }
            //remove icone ask for edit
            J(event.currentTarget).remove();
            J('.tool-tip').css('visibility','hidden');
	}, 'json');
}

//Réponse à une demande d'édition
function onAnswerAskForEdit(event){
    reinitInputWhonotify();
    J(event.currentTarget).unbind('click',onAskForEdit);
    var articleRow = J(event.currentTarget).parent().parent();
    var articleId = parseInt(J('td:first',articleRow).html());
    
	var isAdmin = eval(J('[name=isAdmin]').val());
    
    var title = 'Répondre à la demande d\'édition';
    var text = 'Souhaitez-vous accepter ou refuser cette demande d\'édition ?';
    var title_notif = 'Confirmation de notification';
    var text_notif = (!isAdmin) ? 'L\'administrateur et l\'auteur ont été informés.\r\nSouhaitez-vous également informer :':'L\'auteur a été informé.\r\nSouhaitez-vous également informer :';
    text_notif = getLabels(new Array('contributors','moderators'), text_notif);
    var row = J(event.currentTarget).parent().parent().parent();
    var action = (J(event.currentTarget).data('action'))?J(event.currentTarget).data('action'):null;
    var id_article = (action)?J("[name=id]").val():parseInt(J("td:first",row).html());
    var accept_link = J('#accept_link_'+id_article).val();
    var deny_link = J('#deny_link_'+id_article).val();
    var link_to_get = '';
    function accept_edit(){
        //true : demander confirmation de notification
        J.alerts.okButton = 'Notifier';
        J.alerts.cancelButton = 'Ne pas notifier';
        jConfirm(J(text_notif).html(),title_notif,function(r){
                var notify = '0&who_notify=0';
                if(r){
                	notify = '1&'+J('[name=who_notify[]]:checked').serialize();
                }
                link_to_get = accept_link+'&notify='+notify;
                //envoi de la requête
                J.alerts.okButton = '&nbsp;Ok&nbsp;';
                J.get(link_to_get,{},function(data){
                        if(data.success){
                                if(!action){
                                    //delete icon
                                    J(event.currentTarget).parent().fadeOut('slow',function(){
                                            J(this).remove();
                                    });
                                    //icon status
                                    var td = J('td',row).eq(2);
                                    J('img',td).fadeOut('slow',function(){
                                            J(this).remove();
                                    });
                                    J(td).load(data.statusiconlink);
                                }
                                jAlert(data.success,'Succès',function(){
                                	if(action) window.location = J('[name=referer]').val();
                            	});
                        }
                        if(data.erreur){
                                jAlert(data.erreur,'Erreur');
                        }
                },'json');
        });
    }

    function deny_edit(){
        //false : on notifie seulement l'auteur donc pas d'option
        link_to_get = deny_link+'&notify=0';;
        J.alerts.okButton = '&nbsp;Ok&nbsp;';
        J.get(link_to_get,{},function(data){
                if(data.success){
                    if(!action){
                        //delete icon
                        J(event.currentTarget).parent().fadeOut('slow',function(){
                            J(this).remove();
                        });
                    }
                    jAlert(data.success,'Succès',function(){if(action) window.location = J('[name=referer]').val();});
                }
                if(data.erreur){
                    jAlert(data.erreur,'Erreur');
                }
        },'json');
    }

    J.alerts.okButton = '&nbsp;Accepter&nbsp;';
    J.alerts.cancelButton = '&nbsp;Refuser&nbsp;';

    if(action){
        if(action == 'allow')accept_edit();
        if(action == 'deny')deny_edit();
        handleClickLabels();
    }else{
        jConfirm(text,title,function(r){
            if(r){
        		accept_edit();
            }else{
        		deny_edit();
            }
            handleClickLabels();
        });
    }
}

//Lors d'une action sur "Supprimer" : 'Suppression' ou 'Restauration'
function onTrashIt(event){

	reinitInputWhonotify();
	J(event.currentTarget).unbind('click',onTrashIt);
    var articleRow = J(event.currentTarget).parent().parent();
    var articleId = parseInt(J('td:first',articleRow).html());
    var articleState = parseInt(J('[name=state_'+articleId+']').val());


	var confirmText = '';
	var _delete = J(event.currentTarget).hasClass('delete');

	var isAdmin = eval(J('[name=isAdmin]').val());
	var isModo = eval(J('[name=is_article_moderator_'+articleId+']').val());
    var isAuthor = eval(J('[name=is_article_author_'+articleId+']').val());
	var isContrib = eval(J('[name=is_article_contributor_'+articleId+']').val());

	var titreNotif;

	J.alerts.okButton = '&nbsp;Oui&nbsp;';
	J.alerts.cancelButton = '&nbsp;Non&nbsp;';
	var q = '';

    if(_delete){
        if(isAuthor){
            q = 'Qui souhaitez-vous informer de cette suppression ?';
            confirmText = getLabels(new Array('moderators','contributors'), q);
        }
        if(isAdmin){
            q = 'Le(s) modérateur(s) a/ont été informé(s).\r\nSouhaitez-vous également informer :\r\n';
            confirmText = (isAuthor) ? getLabels(new Array('contributors'), q):getLabels(new Array('author','contributors'),q);
        }
    	if(isModo){
            q = (isAuthor) ? 'L\'administrateur a été informé.\r\n':'L\'administrateur et l\'auteur ont été informés.\r\n';
            q += 'Souhaitez-vous également informer :\r\n';
            confirmText = getLabels(new Array('contributors','moderators'), q);
        }
        titreNotif = "Résultat de la suppression";
	}else{
            //Restauration
            if(isAdmin){
                q = 'Le(s) modérateur(s) a/ont été informé(s).\r\nSouhaitez-vous également informer :\r\n';
                confirmText = (isAuthor) ? getLabels(new Array('contributors'),q):getLabels(new Array('author','contributors'),q);
            }
            if(isModo){
                q = (isAuthor) ? 'Qui souhaitez-vous informer ?\r\n':'L\'auteur a été informé.\r\nSouhaitez-vous également informer :\r\n';
                confirmText = getLabels(new Array('contributors','moderators'),q);
            }
            titreNotif = "Résultat de la restauration";
	}
	jConfirm(J(event.currentTarget).attr('alt'), 
        'Demande de confirmation',
        function(r){
                if(r){
                    J.alerts.okButton = 'Notifier';
                    J.alerts.cancelButton = 'Ne pas notifier';
                    jConfirm(J(confirmText).html(),
                    'Confirmation de notification',
                    function(r){
                            var notify = '&notify=0&who_notify=0';
                            if(r){
                                    notify = '&notify=1&'+J('[name=who_notify[]]:checked').serialize();
                            }
                            var href = event.currentTarget.href+notify;
                            J.get(href,{},function(data){
                                    var _return = '';
                                    if(data.retour == 'success'){
                                            _return = data.message;
                                            var notifications = Boolean(data.notification);
                                            if(notifications){
                                                    if(J('[name=who_notify[]]:checked').length)_return += ' Les notifications ont été envoyées.';
                                            }else{
                                                    _return += ' Les notifications n\'ont pas été envoyées pour des raisons techniques.';
                                            }
                                    }else{
                                            _return = 'Une erreur est survenue. Rechargez votre page et réessayez svp.';
                                    }
                                    var trashiconlink = data.trashiconlink;
                                    var editiconlink = data.editiconlink;
                                    var statusiconlink = data.statusiconlink;
                                    J.alerts.okButton = '&nbsp;Ok&nbsp;';
                                    jAlert(_return,titreNotif);
                                    var parent = J(event.currentTarget).parent();
                                    //icon trash
                                    if(!isContrib){
                                            J(parent).load(trashiconlink,{},function(){
                                                    J('.trashit').bind('click',{},onTrashIt);
                                            });
                                    }
                                    var row = J(parent).parent();
                                    if(_delete){
                                            //delete icon edition
                                            J('.editlink',row).fadeOut('slow',function(){
                                                J(this).remove();
                                            });
                                    }else{
                                            J('td',row).eq(7).load(editiconlink);
                                    }
                                    //icon status
                                    J('td img',row).eq(2).fadeOut('slow',function(){
                                            J(this).remove();
                                    });
                                    J('td',row).eq(2).load(statusiconlink);
                                    J(event.currentTarget).fadeOut('slow',function(){
                                            J(this).remove();
                                    });
                            }, 'json');
                            //location.reload();
                    });
                    handleClickLabels();
                }else{
                    J(event.currentTarget).bind('click',onTrashIt);
                }
            });
}

//Dans le cas d'une erreur Ajax
J(document).ajaxError(function(evt,request,settings){
	J.alerts.okButton = '&nbsp;Ok&nbsp;';
	jAlert('Une erreur technique est survenue.\r\nMerci de recharger votre page et de réessayer.','Erreur');
});

//Active la gestion du click sur les labels
function handleClickLabels(){
    J('#popup_ok').attr('disabled','disabled');
    J('#popup_ok').css('cursor','default').css('opacity','.5');
    J('.notify_labels').click(function(){
        J(this).toggleClass('selectedLabel');
        var value = J(this).hasClass('selectedLabel') ? J('[name=who_notify[]]:checked').length+1:J('[name=who_notify[]]:checked').length-1;
        if(value > 0){
            J('#popup_ok').attr('disabled','');
            J('#popup_ok').css('cursor','pointer').css('opacity','1');
        }else{
            J('#popup_ok').attr('disabled','disabled');
            J('#popup_ok').css('cursor','default').css('opacity','.5');
        }
    });
}

var profiles = new Array('author','contributors','moderators','administrators');
profiles['author'] = new Array();
profiles['contributors'] = new Array();
profiles['moderators'] = new Array();
profiles['administrators'] = new Array();
profiles['author']['inputid'] = 'notify_author';
profiles['author']['name'] = 'l\'auteur';
profiles['contributors']['inputid'] = 'notify_contributors';
profiles['contributors']['name'] = 'le(s) contributeur(s)';
profiles['moderators']['inputid'] = 'notify_moderators';
profiles['moderators']['name'] = 'le(s) modérateur(s)';
profiles['administrators']['inputid'] = 'notify_administrators';
profiles['administrators']['name'] = 'le(s) administrateur(s)';

//Retourne les labels des groupes à notifier
function getLabels(array,textValue){
	//si la chaine ne comporte pas de "?", on en met un à chaque label  
	var suffixe = '';
	if(textValue.indexOf('?')===-1) suffixe = ' ?';
	var p = J(document.createElement('p'));
    p.text(textValue);
    if(array.constructor != Array) return false;
    J.each(array, function(i,v){
    	var label = J(document.createElement('label'));
    	J(label).attr('for',profiles[v]['inputid']).text(profiles[v]['name']+suffixe);
    	J(label).addClass('notify_labels');
    	J(p).append(J(label));
    });
    return J(p);
}

//Réinitialise les champs cachés
function reinitInputWhonotify(){
	J('[name=who_notify[]]:checked').each(function(){
		J(this).attr('checked','');
	});
}

//libère l'article
function checkinArticle(){
	href = J('[name=checkin_article]').val();
	J.get(href,{},function(data){});
}
