var _reg = new RegExp("[_]", "g");
var currentAct = {};

var dialogButtons = {
  close: function(){
    $(this).dialog('close')
  },
  mp_send: function(){
  }
}

function round2(val){
  return Math.round(val * 100) / 100;
}

function debug(data){
  if (typeof(console) == 'object') {
    console.log(data);
  }
}

function ajaxIndicatorStart(target) {
  if(typeof(target) == 'string') target = $(target);
  if ($(target).find('hr:last').exists()) {
    $(target).find('hr:last').before('<div class="ajaxOverlay ui-widget-overlay"></div><div class="ajaxLoader">&nbsp;</div>');
  } else {
    $(target).append('<div class="ajaxOverlay ui-widget-overlay"></div><div class="ajaxLoader">&nbsp;</div>');
  }
}
function ajaxIndicatorStop(target) {
//$(target).find('.ajaxLoader').remove();
//$(target).find('.ajaxOverlay').remove();
}

function messageGlobal(style, msg, dest){
  style = style || '';
  dest = dest || 'ajaxMessageGlobal';
  if (dest != 'dialog') {
    dest = $('#' + dest);
    dest.className = 'msgbox';
    if (style != '') {
      dest.html(msg).addClass(style + 'box').show();
    } else {
      dest.hide().html('');
    }
  } else {
    dest = $('#globalDialog');
    dest.dialog('close');
    dest.className = '';
    $(dest).css({
      position: 'relative',
      borderWidth: 0
    });
    $('#globalDialog').html(msg).dialog({
      resizable: true,
      modal: true,
      title: '',
      buttons: {
        Ok: function(){
          $(this).dialog('close');
        }
      }
    });
  }
  return true;
}

function dialogSimple(title, msg, opts){
  var options = opts ||
  {
    width: 300,
    height: 200
  };
  $('#globalDialog').dialog('close').html(msg).dialog({
    title: title || '',
    modal: true,
    width: options.width,
    height: options.height,
    buttons: [{
      text: 'Ok',
      click: function(){
        $(this).dialog('close')
      }
    }]
  })
}

function dialogBox(url, optsAjax, optsDialog){
  optsAjax = optsAjax || {};
  optsDialog = optsDialog || {};
  // Requete Ajax + mise à jour dialog
  optsAjax['url'] = url;
  optsAjax['type'] = 'post';
  optsAjax['dataType'] = 'json';
  optsAjax['success'] = function(xhr){
    if (xhr === null) return false;

    $(xhr.buttons).each(function(key, val){
      xhr.buttons[key].click = dialogButtons[xhr.buttons[key]['click']];
    });
    var html = xhr.view || '';
    $('#globalDialog').html(html).dialog({
      title: xhr.title,
      open: optsDialog['open'] != 'undefined' ? eval(optsDialog['open']) : '',
      modal: optsDialog['modal'] != 'undefined' ? optsDialog['modal'] : true,
      autoOpen: true,
      width: parseInt(xhr.width) > 0 ? parseInt(xhr.width) : optsDialog['width'],
      height: parseInt(xhr.height) > 0 ? parseInt(xhr.height) : optsDialog['height'],
      buttons: xhr.buttons != 'undefined' && xhr.buttons !== null ? xhr.buttons : optsDialog['buttons']
    })
    return true;
  };

  $.ajax(optsAjax);
}

function map_selectCountryRegionDpt(regionNone, dptNone){
  $('select.country').live('change',function(e){
    map_updateRegion(e, regionNone);
  });
  $('select.region').live('change',function(e){
    map_updateDpt(e, dptNone);
  });
}

// update region
function map_updateRegion(e, none){
  var elt = $(e.target);
  var region = elt.closest('form').find('select.region');
  var dpt = elt.closest('form').find('select.departement');

  $.ajax({
    type: 'post',
    cache: false,
    url: _paths['site_url'] + 'members/regions.json',
    data: {
      data:{
        none: none ? 1 : 0,
        rname : region.attr('name'),
        dname : dpt.attr('name'),
        country: elt.val()
      }
    },
    success: function(xhr){
      region.replaceWith(xhr.region);
      if (dpt.exists())
        dpt.replaceWith(xhr.dpt);
    }
  });
}

// update select departement
function map_updateDpt(e, none){
  var elt = $(e.target);
  var country = elt.closest('form').find('select.country');
  var dpt = elt.closest('form').find('select.departement');

  $.ajax({
    type: 'post',
    cache: false,
    url: _paths['site_url'] + 'members/departements.json',
    data: {
      data:{
        country: country.exists() ? country.val() : 75,
        region: elt.val(),
        dname : dpt.attr('name'),
        none: none ? 1 : 0
      }
    },
    success: function(xhr){
      dpt.replaceWith(xhr.dpt);
    }
  });
}




function photos_upload(opts){
  opts = opts || {};

  currentAct['ajaxUpload'] = new AjaxUpload('#photoNew', {
    autoSubmit: false,
    action: opts['action'],
    name: 'file',
    data: {
      'data[mode]': 'ajax',
      'data[file_id]': isNaN(opts['file_id']) ? 0 : parseInt(opts['file_id']),
      'data[file_default]': isNaN(opts['file_default']) ? 0 : parseInt(opts['file_default'])
    },
    responseType: 'json',
    onChange: function(file){
      $('#photoNewName').text(file);
    },
    onSubmit: function(file, ext){
      currentAct['photos_upload'] = true;
      $('#ajaxLoader').show();
    },
    onComplete: function(file, xhr){
      currentAct['photos_upload'] = false;
      $('#ajaxLoader').hide();
      if (xhr.error == 1) {
        updateTips(xhr.msg);
      } else {
        eval(opts['completeOk']);
      }
    }
  });

// submit
//$('#submit_photoNew').click(function(){ currentAct['ajaxUpload'].submit()});
}

/**
 * Fonctions images
 */

/*
 * Passe une photo en "default"
 */
function picture_default(e){
  if (currentAct['picture_default'] === true) return false;
  currentAct['picture_default'] = true;

  var elt = $(e.target);
  var divImg = $(elt).closest('div.div_picture').children('div.photo_small:first');
  var infos = $(divImg).attr('id').split(_reg);

  $.ajax({
    url: _paths['site_url'] + 'members/photos_default.json',
    type: 'post',
    dataType: 'json',
    data: {
      data: {
        id: infos[1]
      }
    },
    success: function(xhr){
      currentAct['picture_default'] = false;
      if (xhr.error == 1) {

      } else {
        // Remplace l'ancien texte par un bouton
        $('.default_picture').replaceWith(xhr.button_default);

        // Change le bouton par le message "photo" profil
        elt.replaceWith(xhr.text_default);
      }
    }
  })
}

/*
 * Suppression d'une image
 */
function picture_delete(e){
  if (currentAct['picture_delete'] === true) return false;
  currentAct['picture_delete'] = true;

  var elt = $(e.target);
  var div = $(elt).closest('div.div_picture');
  var divImg = $(div).children('div.photo_small:first');
  var eltImg = $(divImg).children('img:first');
  var infos = $(divImg).attr('id').split(_reg);

  var moderation = divImg.hasClass('picture_moderate');

  // appel la confirmation ajax
  $.ajax({
    url: _paths['site_url'] + 'members/photos_delete.json',
    type: 'post',
    dataType: 'json',
    data: {
      data: {
        id: infos[1],
        type: divImg.hasClass('picture_moderate') ? 'moderation' : 'online'
      }
    },
    success: function(xhr){
      currentAct['picture_delete'] = false;
      if (xhr.error == 1) {
        dialogSimple(xhr.title, xhr.content, {
          width: 350,
          height: 280
        });
      } else {
        $('#globalDialog').dialog('close').html(xhr.content).dialog({
          title: xhr.title,
          modal: true,
          width: 350,
          height: 280,
          buttons: [{
            text: 'Fermer',
            click: function(){
              $(this).dialog('close')
            }
          }, {
            text: 'Supprimer',
            click: function(){
              if (currentAct['picture_delete'] === true) return false;
              currentAct['picture_delete'] = true;
              $.ajax({
                url: _paths['site_url'] + 'members/photos_delete.json',
                type: 'post',
                dataType: "json",
                data: {
                  data: {
                    id: infos[1],
                    type: divImg.hasClass('picture_moderate') ? 'moderation' : 'online',
                    ok: 1
                  }
                },
                success: function(xhr){
                  currentAct['picture_delete'] = false;
                  $('#globalDialog').dialog('close');
                  var oldId = null;
                  var newId = null;

                  var grep = new RegExp(/(\d)_(\d+)$/).exec($(divImg).attr('id'));

                  if (moderation) {
                    // Reset le texte
                    $(divImg).html("Envoyer une image");

                    // Image online existe pas, on passe à 0
                    if (!$('#pictureOnline' + grep[1] + '_' + grep[2]).exists()) {
                      oldId = 'pictureModerate' + grep[1] + '_' + grep[2];
                      newId = 'pictureModerate' + grep[1] + '_0';
                      $('#' + oldId).attr('id', newId);
                    }
                  } else {
                    // Supprime la photo
                    $(eltImg).remove();

                    // retire les boutons
                    $(div).children().not('div').remove();

                    // reset l'id de l'image de moderation correspondante
                    oldId = 'pictureModerate' + grep[1] + '_' + grep[2];
                    newId = 'pictureModerate' + grep[1] + '_0';
                    $('#' + oldId).attr('id', newId);
                    // Redéfini le bouton "par défaut"
                    if (xhr.newDefault) {
                      $('div.picture_online[id$="_' + xhr.newDefault + '"]').parent('div').find('button.picture_default:first').replaceWith('<b>photo du profil</b>');
                    }
                  }

                  // petit flash vert
                  $(divImg).effect('highlight', {
                    color: '#8BDF8F'
                  }, 800);

                }
              });
            }
          }]
        })
      }
    }
  })
}

/**
* gestion des abus
*/
/*
 * Signaler un abus sur un membre
 */
function abuse_member(e, url){
  if (currentAct['abuse_member'] === true) return false;
  currentAct['abuse_member'] = true;

  var elt = $(e.target);

  $.getJSON(_paths['site_url'] + 'abuses/signal_member/'+jtr.member_id+'.json', function(xhr){
    currentAct['abuse_member'] = false;
    if (xhr.error == true) {
      dialogSimple(xhr.title, xhr.content, {
        width: 300,
        height: 210
      });
    } else {
      $('#globalDialog').dialog('close').html(xhr.content).dialog({
        title: xhr.title,
        modal: true,
        width: 'auto',
        height: 'auto',
        buttons: [{
          text: 'Fermer',
          click: function(){
            $(this).dialog('close')
          }
        }, {
          text: 'Envoyer',
          click: function(){
            if (currentAct['abuse_member'] === true) return false;
            currentAct['abuse_member'] = true;
            $.ajax({
              url: _paths['site_url'] + 'abuses/signal_member.json',
              type: 'post',
              dataType: "json",
              data: $('#form_abuse').serialize(),
              success: function(xhr){
                currentAct['abuse_member'] = false;
                if (xhr.error == 1) {
                  updateTips(xhr.msg);
                } else {
                  if (xhr.remove == true) $(elt).remove();
                  dialogSimple(xhr.title, xhr.content, {
                    width: 300,
                    height: 200
                  });
                }
              }
            })
          }
        }]
      });
    }
  });
  return false;
}

/*
 * Ajoute un membre en tant que favori
 */
function member_favorite(e){
  if (currentAct['member_favorite'] === true) return false;
  currentAct['member_favorite'] = true;

  var withPicture = false;
  var elt = $(e.target);

  if (elt.hasClass('btn')) {
    elt = $(e.target).closest('div.portrait');
    withPicture = true;
  } else {
    elt = !$(e.target).hasClass('member_favorite') ? $(e.target).closest('.member_favorite') : $(e.target);
  }

  var infos = $(elt).attr('id').split(_reg);
  var uid = parseInt(infos[1]);

  // Appel la boite de dialogue
  $.ajax({
    url: _paths['site_url'] + 'members/favorite.json',
    type: 'post',
    dataType: 'json',
    data: {
      data: {
        id: uid
      }
    },
    success: function(xhr){
      currentAct['member_favorite'] = false;
      if (xhr.error == 1 || xhr.action == 'max' || xhr.action == 'already') {
        // Affiche la confirmation
        dialogSimple(xhr.title, xhr.content, {
          width: 300,
          height: 200
        });
      } else {
        if (withPicture) {
          $(elt).effect("highlight", {
            color: xhr.color,
            mode: "hide"
          }, 500, function(){
            $(this).remove();
          });
        } else {
          // Si on a une image sous l'élément
          var img = elt.children('img:first');
          if (img.exists()) {
            img.attr('src',xhr.img);
          } else {
            iconChangeState(elt, xhr.state);
          }
        }
        $('#alert_favorite_span').text(xhr.total);
      }
    }
  });
}

/*
 * Bloquer un membre
 */
function member_block(e, withPicture){
  if (currentAct['member_block'] === true) return false;
  currentAct['member_block'] = true;

  withPicture = withPicture || false;
  var elt = null;

  if (withPicture) {
    elt = $(e.target).closest('div.portrait');
  } else {
    elt = $(e.target);
  }

  var infos = $(elt).attr('id').split(_reg);
  var uid = parseInt(infos[1]);

  // Appel la boite de dialogue
  $.ajax({
    url: _paths['site_url'] + 'members/block.json',
    type: 'post',
    dataType: 'json',
    data: {
      data: {
        id: uid
      }
    },
    success: function(xhr){
      currentAct['member_block'] = false;
      if (xhr.error == true) {
        dialogSimple(xhr.title, xhr.content, {
          width: 300,
          height: 210
        });
      } else {
        // Suivant le retour xhr, on affiche ou non la demande de confirmation
        if (xhr.block == true) {
          $('#globalDialog').dialog('close').html(xhr.content).dialog({
            title: xhr.title,
            modal: true,
            width: 320,
            height: 252,
            buttons: [{
              text: 'Fermer',
              click: function(){
                $(this).dialog('close')
              }
            }, {
              text: 'Bloquer',
              click: function(){
                if (currentAct['member_block'] === true) return false;
                currentAct['member_block'] = true;
                $.ajax({
                  url: _paths['site_url'] + 'members/block.json',
                  type: 'post',
                  dataType: 'json',
                  data: {
                    data: {
                      block: true,
                      id: uid
                    }
                  },
                  success: function(xhr){
                    currentAct['member_block'] = false;
                    elt.text(xhr.text);
                    dialogSimple(xhr.title, xhr.content, {
                      width: 300,
                      height: 200
                    });
                  }
                })
              }
            }]
          });
        } else { // utilisateur débloqué
          if (withPicture) {
            $(elt).effect("highlight", {
              color: xhr.color,
              mode: "hide"
            }, 500, function(){
              $(this).remove();
            });
          } else {
            elt.text(xhr.text);
          }
          dialogSimple(xhr.title, xhr.content, {
            width: 300,
            height: 200
          });
          // on rafraichi la page pour faire tout réaparaitre
          window.location.href = window.location.href;
        }
      }
    }
  });
  return false;
}


// Change l'humeur
function member_mood(e){
  if (currentAct['member_mood'] === true) return false;
  currentAct['member_mood'] = true;

  var elt = $(e.target);

  var infos = $(elt).attr('id').split(_reg);
  var mood = infos[1];

  // Envoi le changement de statut
  $.ajax({
    url: _paths['site_url'] + 'members/mood.json',
    type: 'post',
    dataType: 'json',
    data: {
      data: {
        mood: mood
      }
    },
    success: function(xhr){
      currentAct['member_mood'] = false;
      if (xhr.error == 0) {
        $('#moods').html(xhr.content);
      /*
         $(elt).parent('p').find('.mood').each(function(k, item){
         infos = $(item).attr('id').split(_reg);
         mood = infos[1];
         $(item).attr('src', xhr[mood]);
         });
         */
      }
    }
  });
}


// Change le statut en ligne
function member_see_online(e){
  if (currentAct['member_see_online'] === true) return false;
  currentAct['member_see_online'] = true;

  var elt = $(e.target);
  if (elt.hasClass('online') || elt.hasClass('offline')) return false;

  // Envoi le changement de statut
  $.ajax({
    url: _paths['site_url'] + 'members/see_online.json',
    type: 'post',
    dataType: 'json',
    success: function(xhr){
      currentAct['member_see_online'] = false;
      if (xhr.error == 0) {
        // retire les statuts
        elt.parent().find('span').removeClass('online offline');
        elt.addClass(xhr.status == 1 ? 'online' : 'offline');
      }
    }
  });
}


// Changement de statut rapide
function member_quickstatus(e){
  if (currentAct['member_quickstatus'] === true) return false;
  currentAct['member_quickstatus'] = true;

  if ($('#QuickStatusAgeFrom').val() > $('#QuickStatusAgeTo').val()) {
    $('#quickStatusText').effect('highlight', {
      color: '#FF6F6F'
    }, 800);
    currentAct['member_quickstatus'] = false;
    return false;
  }

  var elt = $(e.target);

  var infos = $(elt).attr('id').split(_reg);
  var status = infos[1];
  var age = $('#QuickStatusAgeFrom').val() + '-' + $('#QuickStatusAgeTo').val();

  // Envoi le changement de statut
  $.ajax({
    url: _paths['site_url'] + 'members/quickstatus.json',
    type: 'post',
    dataType: 'json',
    data: {
      data: {
        status: status,
        age: age
      }
    },
    success: function(xhr){
      currentAct['member_quickstatus'] = false;
      if (xhr.error == 0) {
        $('#quick_hidden').hide('fast');
        $('#quickStatusText').html(xhr.msg).effect('highlight', {
          color: '#8BDF8F'
        }, 1000);
        if (elt.attr('nodeName') == 'A') {
          // Change la couleur des autres statut
          $('.quickstatus').not($(elt)).parent('li').removeClass('active');
          // Change la couleur de ce statut
          elt.parent('li').toggleClass('active');
        }
      }
    }
  });
  return false;
}

// envoi photo
var imgDiv = null;
function member_picture(e){
  if (currentAct['member_picture'] === true) return false;
  currentAct['member_picture'] = true;

  imgDiv = $(e.target).hasClass('upload') ? $(e.target) : $(e.target).closest("div.upload");
  // Envoi le changement de statut

  $.ajax({
    url: _paths['site_url'] + 'members/photos_upload.json',
    type: 'post',
    dataType: 'json',
    success: function(xhr){
      $('#globalDialog').dialog('close').html(xhr.content).dialog({
        title: xhr.title,
        modal: false,
        width: 320,
        height: 252,
        buttons: [{
          text: 'Fermer',
          click: function(){
            currentAct['member_picture'] = false;
            $(this).dialog('close')
          }
        }, {
          text: 'Envoyer',
          click: function(){
            if (currentAct['photos_upload'] === true) return false;
            currentAct['ajaxUpload'].submit();
          }
        }]
      });

      // Initialise le plugin d'upload photo
      initUploadPhotos();

    }
  })
//open:'initUploadPhotos'
}

function initUploadPhotos(){
  var infos = imgDiv.attr('id').split(_reg);
  photos_upload({
    file_default: imgDiv.attr('id').match(/0_\d+$/) ? 1 : 0,
    file_id: infos[1],
    action: _paths['site_url'] + 'members/photos_upload.json',
    completeOk: 'afterUploadPhotos(xhr)'
  });
}

function afterUploadPhotos(xhr){
  var infos = imgDiv.attr('id').split(_reg);
  var eltImg = $(imgDiv).children('img');
  if (!$(eltImg).exists()) {
    $(imgDiv).html('<img src=""/>');
    eltImg = $(imgDiv).children('img');
  }
  // re fixe l'id (si nouveau)
  $(imgDiv).attr('id', infos[0] + '_' + xhr.pic_id);
  // Change la source de l'image
  $(eltImg).attr('src', xhr.pic_medium);

  $('#globalDialog').dialog('close');

  // après l'envoi on peut à nouveau ouvrir une fenêtre d'upload
  currentAct['member_picture'] = false;
}

/*
 * Prise de contact
 */
function contact_send(e){
  if (currentAct['contact_send'] === true) return false;
  currentAct['contact_send'] = true;

  var elt = !$(e.target).hasClass('contact_send') ? $(e.target).closest('.contact_send') : $(e.target);
  var infos = $(elt).attr('id').split(_reg);
  var uid = parseInt(infos[1]);

  $.ajax({
    url: _paths['site_url'] + 'members/contact_send.json',
    type: 'post',
    dataType: 'json',
    data: {
      data: {
        id: uid
      }
    },
    success: function(xhr){
      currentAct['contact_send'] = false;
      // trop de contact ou déjà contact
      if (xhr.error == 1 || xhr.action != 'ask') {
        // Affiche la confirmation
        dialogSimple(xhr.title, xhr.content, {
          width: 300,
          height: 200
        });
      } else {
        $('#globalDialog').dialog('close').html(xhr.content).dialog({
          title: xhr.title,
          modal: true,
          width: 350,
          height: 200,
          buttons: [{
            text: 'Fermer',
            click: function(){
              $(this).dialog('close')
            }
          }, {
            text: 'Envoyer',
            click: function(){
              if (currentAct['contact_send'] === true) return false;
              currentAct['contact_send'] = true;

              $.ajax({
                url: _paths['site_url'] + 'members/contact_send.json',
                type: 'post',
                dataType: "json",
                data: {
                  data: {
                    id: uid,
                    ok: 1
                  }
                },
                success: function(xhr){
                  currentAct['contact_send'] = false;
                  $('span.contact_left').text(xhr.contact_left);
                  dialogSimple(xhr.title, xhr.content, {
                    width: 300,
                    height: 200
                  });
                }
              })
            }
          }]
        });
      }
    }
  })
}

function iconChangeState(elt, state){
  if (state == 'on') {
    if ($(elt).hasClass('off')) $(elt).removeClass('off');
  } else {
    if ($(elt).hasClass('on')) $(elt).removeClass('on');
  }
  $(elt).addClass(state);
}

/**
 * Gestion Ajax des MP
 */
/*
 * lecture d'un mp
 * suivant la réponse, on peut répondre ou non
 */
function mp_voir(url){
  // Récupère le contenu du message
  $.getJSON(url, function(xhr){
    // Si le MP n'est pas de moi, on peut répondre, sinon on ne peut que fermer
    var buttons = [{
      text: 'Fermer',
      click: function(){
        $(this).dialog('close')
      }
    }];
    if (xhr.canAnswer == true) {
      buttons.push({
        text: 'Répondre',
        click: function(){
          mp_send(xhr.answer.url)
        }
      })
    }

    // pop du dialog
    $('#globalDialog').dialog('close').html(xhr.content).dialog({
      title: xhr.title,
      modal: true,
      width: 350,
      height: 300,
      buttons: buttons
    });
  })
}

/*
 * envoi d'un MP
 * - si la personne est connecté, formulaire avec envoi
 * - sinon, message comme quoi il faut créer un compte
 */
function mp_send(url){
  if (currentAct['mp_send'] === true) return false;
  currentAct['mp_send'] = true;

  // contenu du dialog
  $.getJSON(url, function(xhr){
    currentAct['mp_send'] = false;
    if (xhr.error == true) {
      dialogSimple(xhr.title, xhr.content, {
        width: 300,
        height: 210
      });
    } else {
      $('#globalDialog').dialog('close').html(xhr.content).dialog({
        title: xhr.title,
        modal: true,
        width: 'auto',
        height: 380,
        buttons: [{
          text: 'Fermer',
          click: function(){
            $(this).dialog('close')
          }
        }, {
          text: 'Envoyer',
          click: function(){
            if (currentAct['mp_send'] === true) return false;
            currentAct['mp_send'] = true;
            $.ajax({
              url: url,
              type: 'post',
              dataType: "json",
              data: $('#form_mp_send').serialize(),
              success: function(xhr){
                currentAct['mp_send'] = false;
                if (xhr.error == 1) {
                  updateTips(xhr.msg);
                } else {
                  dialogSimple(xhr.title, xhr.content, {
                    width: 300,
                    height: 200
                  });
                }
              }
            })
          }
        }]
      });
    }
  })
}


/*
 * suppression de MP
 */
function mp_delete(e, checked){
  if (currentAct['mp_delete'] === true) return false;
  currentAct['mp_delete'] = true;

  $.ajax({
    url: _paths['site_url'] + 'messagerie/delete.json',
    type: 'post',
    dataType: 'json',
    data: checked,
    success: function(xhr){
      currentAct['mp_delete'] = false;
      $('#globalDialog').dialog('close').html(xhr.content).dialog({
        title: xhr.title,
        modal: true,
        width: 350,
        height: 200,
        buttons: [{
          text: 'Annuler',
          click: function(){
            $(this).dialog('close')
          }
        }, {
          text: 'Supprimer',
          click: function(){
            mp_deleteConfirm(checked)
          }
        }]
      });
    }
  })
}

function mp_deleteConfirm(checked){
  if (currentAct['mp_deleteConfirm'] === true) return false;
  currentAct['mp_deleteConfirm'] = true;

  var data = checked;
  data.push({
    name: 'data[delete_ok]',
    value: 1
  });

  $.ajax({
    url: _paths['site_url'] + 'messagerie/delete.json',
    type: 'post',
    dataType: 'json',
    data: data,
    success: function(xhr){
      currentAct['mp_deleteConfirm'] = false;
      $('#globalDialog').dialog('close');
      // Met à jour l'alerte
      $('#alert_mp_span').text(xhr.unread);
      $(xhr.ids).each(function(key, val){
        $('#row_' + val).effect("highlight", {
          color: "red",
          mode: "hide"
        }, 500, function(){
          $(this).remove();
        });
      });
    }
  });
  return false;
}

// Autoshaker
function mp_shaker(e) {
  var elt = $(e.target);
  if (isNaN(parseInt(elt.val()))) return false;
  if (currentAct['mp_shaker'] === true) return false;
  currentAct['mp_shaker'] = true;

  var infos = $(elt).attr('id').split(_reg);

  // Envoi le changement de statut
  $.ajax({
    url: _paths['site_url'] + 'messagerie/shaker.json',
    type: 'post',
    dataType: 'json',
    data: {
      data: {
        sid : elt.val()
      }
    },
    success: function(xhr){
      currentAct['mp_shaker'] = false;
      $('#PrivMsgBody').text(xhr.content);
    }
  });
}


function portraitMove(portrait,dest) {
  var eltDest = $(dest);
  var lastItems = $(dest+'>div>div:last');

  var recptElt = null;

  if (lastItems.children().length >= 6) {
    // Besoin d'un nouveau conteneur
    lastItems.closest('div.items').append('<div></div>');
    recptElt = $(dest+'>div>div:last');
  } else {
    recptElt = lastItems;
  }

  $(recptElt).append($(portrait));
}

function portraitInsert(html,dest) {
  var eltDest = $(dest);
  var lastItems = $(dest+'>div>div:last');

  var recptElt = null;

  if (lastItems.children().length >= 6) {
    // Besoin d'un nouveau conteneur
    lastItems.closest('div.items').append('<div></div>');
    recptElt = $(dest+'>div>div:last');
  } else {
    recptElt = lastItems;
  }

  $(recptElt).append(html);
}


/**
 * Relations
 */

/*
* passe le portrait d'une étape à l'autre
*/
function relation_portrait(portrait,xhr) {
  $(portrait).effect("highlight", {
    color: xhr.color,
    mode: "hide"
  }, 500, function(){
    $(this).remove();
  });
  // Ajoute la vignette à l'étape suivante
  portraitInsert(xhr.content,'#'+xhr.dest);
  return true;
}

/*
 * Appelé depuis un click bouton, envoi l'id de la relation a accepter ou refuser
 */
function relation_acceptRefuse(){
  if (currentAct['relation_acceptRefuse'] === true) return false;
  currentAct['relation_acceptRefuse'] = true;

  var div = $(this).closest('div.portrait');
  var infos = $(div).attr('id').split(_reg);

  var data = {
    data: {
      mode: $(this).hasClass('yes') ? 'yes' : 'no',
      id: parseInt(infos[1])
    }
  }

  $.ajax({
    url: _paths['site_url'] + 'relations/accept_refuse.json',
    type: 'post',
    dataType: 'json',
    data: data,
    success: function(xhr){
      currentAct['relation_acceptRefuse'] = false;

      // supprime la vignette
      $(div).effect("highlight", {
        color: xhr.color,
        mode: "hide"
      }, 500, function(){
        $(this).remove();
      });

      if (xhr.mode == 'yes') {
        // Ajoute la vignette à l'étape suivante
        portraitInsert(xhr.content,'#relation_etape1')
      }
    }
  })
}

/*
 * Passe la relation à l'étape suivante
 */
function relation_next() {
  if (currentAct['relation_next'] === true) return false;
  currentAct['relation_next'] = true;

  var portrait = $(this).closest('div.portrait');
  var infos = $(portrait).attr('id').split(_reg);

  var data = {
    data: {
      id: parseInt(infos[1])
    }
  }

  $.ajax({
    url: _paths['site_url'] + 'relations/next.json',
    type: 'post',
    dataType: 'json',
    data: data,
    success: function(xhr){
      if (xhr.error == 1) {
        dialogSimple(xhr.title, xhr.content, {
          width: 300,
          height: 210
        });
      } else if (xhr.action == 'coord') {
        relation_coord(xhr,portrait);
      } else if (xhr.action == 'date') {
        relation_date(xhr,portrait);
      } else if (xhr.action == 'portrait') {
        currentAct['relation_next'] = false;
        relation_portrait(portrait,xhr);
      }
    }
  })
}

// demande les coordonnées de la fille et transmet au garçon
function relation_coord(xhr,portrait) {
  $('#globalDialog').dialog('close').html(xhr.content).dialog({
    title: xhr.title,
    modal: true,
    width: 350,
    height: 250,
    buttons: [{
      text: 'Fermer',
      click: function(){
        $(this).dialog('close')
      }
    }, {
      text: 'Envoyer',
      click: function(){
        if (currentAct['relation_coord'] === true) return false;
        currentAct['relation_coord'] = true;
        $.ajax({
          url: _paths['site_url'] + 'relations/next.json',
          type: 'post',
          dataType: "json",
          data: $('#dialogForm').serialize(),
          success: function(xhr){
            currentAct['relation_coord'] = false;
            if (xhr.error == 1) {
              updateTips(xhr.content);
            } else {
              $('#globalDialog').dialog('close');
              relation_portrait(portrait,xhr);
            }
          }
        })
      }
    }]
  });
}

// demande la date de rendez-vous
function relation_date(xhr,portrait) {
  $('#globalDialog').dialog('close').html(xhr.content).dialog({
    title: xhr.title,
    modal: true,
    width: 350,
    height: 220,
    buttons: [{
      text: 'Fermer',
      click: function(){
        $(this).dialog('close')
      }
    }, {
      text: 'Envoyer',
      click: function(){
        if (currentAct['relation_date'] === true) return false;
        currentAct['relation_date'] = true;
        $.ajax({
          url: _paths['site_url'] + 'relations/next.json',
          type: 'post',
          dataType: "json",
          data: $('#dialogForm').serialize(),
          success: function(xhr){
            currentAct['relation_date'] = false;
            if (xhr.error == 1) {
              updateTips(xhr.content);
            } else {
              $('#globalDialog').dialog('close');
              relation_portrait(portrait,xhr);
            }
          }
        })
      }
    }]
  });
}


/*
 * Arrête la relation (archive)
 */
function relation_stop(){
  if (currentAct['relation_stop'] === true) return false;
  currentAct['relation_stop'] = true;

  var div = $(this).closest('div.portrait');
  var infos = $(div).attr('id').split(_reg);

  var data = {
    data: {
      id: parseInt(infos[1])
    }
  }

  $.ajax({
    url: _paths['site_url'] + 'relations/stop.json',
    type: 'post',
    dataType: 'json',
    data: data,
    success: function(xhr){
      currentAct['relation_stop'] = false;
      data['data']['stop'] = true;

      $('#globalDialog').dialog('close').html(xhr.content).dialog({
        title: xhr.title,
        modal: true,
        width: 350,
        height: 200,
        buttons: [{
          text: 'Fermer',
          click: function(){
            $(this).dialog('close')
          }
        }, {
          text: 'Arrêter',
          click: function(){
            if (currentAct['relation_stop'] === true) return false;
            currentAct['relation_stop'] = true;
            $.ajax({
              url: _paths['site_url'] + 'relations/stop.json',
              type: 'post',
              dataType: "json",
              data: data,
              success: function(xhr){
                currentAct['relation_stop'] = false;
                // Supprime le portrait
                $(div).effect("highlight", {
                  color: xhr.color,
                  mode: "hide"
                }, 500, function(){
                  $(this).remove();
                });

                portraitInsert(xhr.content,'#relation_archive')

                // Affiche la confirmation
                dialogSimple(xhr.title, xhr.msg, {
                  width: 300,
                  height: 200
                });
              }
            })
          }
        }]
      });
    }
  })
  return false;
}


/**
 * parrainage
 */
function parrainage_get_contacts_gmail(e){
  if (currentAct['parrainage_get_contacts'] === true) return false;
  //currentAct['parrainage_get_contacts'] = true;

  $('#contactsListGMail').html('').show();
  $('#divButtonSendGmail').show();

  $.ajax({
    url: _paths['site_url'] + 'parrainages/get_contacts.json',
    type: 'post',
    dataType: 'json',
    data: $('#autoParrainageFormGmail').serialize(),
    beforeSend: function(){
      ajaxIndicatorStart('#contactsListGMail');
    },
    complete : ajaxIndicatorStop('#contactsListGMail'),
    success: function(xhr){
      currentAct['parrainage_get_contacts'] = false;
      if (xhr.error == 0) {
        $('#contactsListGMail').html(xhr.content);
        $('#divButtonSendGmail').show();
      } else {
        $('#divButtonSendGmail').hide();
        messageGlobal('error', xhr.msg, 'dialog');
      }
    }
  });

  return false;
}


/**
 * Recherches
 */
function search_refresh(e,target,recreate) {
  if (currentAct['search_refresh'] === true) return false;
  currentAct['search_refresh'] = true;

  recreate = recreate ||false;

  var button = $(e.target);

  $.ajax({
    data:button.closest("form").serialize(),
    dataType:"html",
    beforeSend: ajaxIndicatorStart(target),
    success:function (data, textStatus) {
      currentAct['search_refresh'] = false;
      ajaxIndicatorStop(target);
      $(target).html(data);
      if (recreate) createScrollable (target);
    },
    type:"post",
    url:_paths['site_url'] + 'searches/refresh'
  });
  return false;
}

function createScrollable(target){
  currentAct[$(target).attr('id')] = null;
  currentAct[$(target).attr('id')] = $(target).scrollable({
    mousewheel: false
  })
};
