var _reg = new RegExp("[_]", "g");
var currentAct = {};

jQuery.fn.exists = function(){ return jQuery(this).length > 0;}

function debug(data){
  if (typeof(console) == 'object') {
    console.log(data);
  }
}

function messageGlobal(style, msg, dest){
  hideAjaxIndicator();
  var id = dest || 'ajaxMessageGlobal';
  var target = $('#' + id);
  if (style != "") {
    target.html(msg);
    target.dialog({
      buttons: {
        'Ok': function(){
          target.dialog('close');
        }
      }
    });
  } else {
    target.html('');
  }
}

/**
 * Observe les champs input avec une classe date pour afficher le calendrier dessus
 * @param {Object} lang
 */
function calendar(){
  $.datepicker.setDefaults($.datepicker.regional['fr']);
  $('input.date').each(function(index){
    $(this).datepicker({
      changeMonth: true,
      changeYear: true
    });
  });
}

/* French initialisation for the jQuery UI date picker plugin. */
/* Written by Keith Wood (kbwood{at}iinet.com.au) and Stéphane Nahmani (sholby@sholby.net). */
jQuery(function($){
  $.datepicker.regional['fr'] = {
    closeText: 'Fermer',
    prevText: '&#x3c;Préc',
    nextText: 'Suiv&#x3e;',
    currentText: 'Courant',
    monthNames: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'],
    monthNamesShort: ['Jan', 'Fév', 'Mar', 'Avr', 'Mai', 'Jun', 'Jul', 'Aoû', 'Sep', 'Oct', 'Nov', 'Déc'],
    dayNames: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'],
    dayNamesShort: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'],
    dayNamesMin: ['Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa'],
    weekHeader: 'Sm',
    dateFormat: 'dd/mm/yy',
    firstDay: 1,
    isRTL: false,
    showMonthAfterYear: false,
    yearSuffix: ''
  };
  $.datepicker.setDefaults($.datepicker.regional['fr']);
});


/*
 * Special jQuery dialog
 */
function updateTips(t){
  var dest = $('.ui-dialog').find('.validateTips:first');
  dest.html(t).addClass('ui-state-error').show();
  setTimeout(function(){
    dest.removeClass('ui-state-error', 1500);
  }, 500);
}

function dialog_enterKey(buttonLabel){
  // Le bouton qui va bien
  var button = $('.ui-dialog').find('.ui-dialog-buttonpane button.ui-button').find(":contains('" + buttonLabel + "')");
  
  $('.ui-dialog').find('input').keypress(function(e){
    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
      button.click();
      return false;
    }
  });
}


// Display ajax wait
function showAjaxIndicator(){
  $('#ajax-indicator').show();
}

// Hide ajax wait
function hideAjaxIndicator(){
  $('#ajax-indicator').hide();
}


/**
 * highlight text
 */
function highlight(target, duration){
  $('#' + target).fadeOut(duration).fadeIn(duration).fadeOut(duration).fadeIn(duration).fadeOut(duration).fadeIn(duration);
}

/*
 * order jump
 */
function order_jump(e){
  var elt = $(e.currentTarget);
  if (elt.val() > 0) {
    var currentParams = {};
    currentParams['order_id'] = elt.val();
    var url = 'dossier.php?' + $.param(currentParams);
    window.location.href = url;
    return;
  }
}

function tb_open(){
  if ($('#tb_content').exists() && !$('#tb_content').hasClass('open')) {
    $('#tb_content').addClass('open');
    $('#tb_content').toggle(true);
  }
}

function tb_close(){
  if ($('#tb_content').exists() && $('#tb_content').hasClass('open')) {
    $('#tb_content').removeClass('open');
    $('#tb_content').toggle(false);
  }
}

/*
 * Fonction des dossiers / groupes
 */
function group_changeAlert(e){
  if (currentAct['changeAlert'] == true) return false;
  currentAct['changeAlert'] = true;
  var elt = $(e.currentTarget);
  var infos = elt.attr('id').split(_reg);
  var groupId = parseInt(infos[1]);
  
  $.ajax({
    type: 'post',
    cache: false,
    url: _paths['site_url'] + 'dossier.php',
    data: {
      mode: 'alert',
      group: groupId
    },
    beforeSend: showAjaxIndicator,
    complete: hideAjaxIndicator,
    dataType: 'json',
    success: function(xhr){
      currentAct['changeAlert'] = false;
      if (xhr.error == 1) {
        messageGlobal('error', xhr.msg);
      } else {
        var img = $('div.folder_alert div:first-child');
        if (xhr.status == 1) {
          img.removeClass('alert_off').addClass('alert_on')
        } else {
          img.removeClass('alert_on').addClass('alert_off')
        }
        img.next().html(xhr.title);
      }
    }
  });
}

// Création d'un dossier
function group_new(){
  var name = $('#group_new_name');
  
  tb_close();
  
  $("#dialog_groupNew").dialog({
    autoOpen: true,
    resizable: false,
    height: 230,
    width: 350,
    modal: true,
    open: function(){
      name.removeClass('ui-state-error');
      name.val('');
      $('.ui-dialog').find('.validateTips').hide();
      name.focus();
      dialog_enterKey('Créer');
    },
    buttons: {
      'Créer': function(){
        name.removeClass('ui-state-error');
        $('.ui-dialog').find('.validateTips').hide();
        if (currentAct['createFolder']) return false;
        currentAct['createFolder'] = true;
        
        var datas = $('#form_groupNew').serializeArray(true);
        datas.push({
          name: 'ajax',
          value: 1
        });
        datas.push({
          name: 'mode',
          value: 'manipulation'
        });
        datas.push({
          name: 'action',
          value: 'create_group'
        });
        
        $.ajax({
          type: 'post',
          cache: false,
          url: _paths['site_url'] + 'dossier.php',
          data: datas,
          dataType: 'json',
          success: function(xhr){
            currentAct['createFolder'] = false;
            if (xhr.error == 1) {
              updateTips(xhr.msg);
            } else {
              // Ferme la boite de dialogue
              $(this).dialog('close');
              // Recharge la page
              window.location.href = xhr.data;
            }
          }
        });
      },
      'Annuler': function(){
        $(this).dialog('close');
      }
    }
  });
}

// Création d'un sous-dossier
function folder_new(){
  var name = $('#folder_new_name');
  
  tb_close();
  
  $("#dialog_folderNew").dialog({
    autoOpen: true,
    resizable: false,
    height: 230,
    width: 350,
    modal: true,
    open: function(){
      name.removeClass('ui-state-error');
      name.val('');
      $('.ui-dialog').find('.validateTips').hide();
      name.focus();
      dialog_enterKey('Créer');
    },
    buttons: {
      'Créer': function(){
        name.removeClass('ui-state-error');
        $('.ui-dialog').find('.validateTips').hide();
        if (currentAct['createFolder']) return false;
        currentAct['createFolder'] = true;
        
        $.ajax({
          type: 'post',
          cache: false,
          url: _paths['site_url'] + 'dossier.php',
          data: {
            mode: 'manipulation',
            action: 'create',
            folder: _folderId,
            name: name.val()
          },
          dataType: 'json',
          success: function(xhr){
            currentAct['createFolder'] = false;
            if (xhr.error == 1) {
              updateTips(xhr.msg);
            } else {
              // Ferme la boite de dialogue
              $(this).dialog('close');
              // Recharge la page
              window.location.href = xhr.data;
            }
          }
        });
      },
      'Annuler': function(){
        $(this).dialog('close');
      }
    }
  });
}

function folder_delete(){

  tb_close();
  
  $("#dialog_folderDelete").dialog({
    autoOpen: true,
    resizable: false,
    height: 220,
    width: 350,
    modal: true,
    open: function(){
      $('.ui-dialog').find('.validateTips').hide();
    },
    buttons: {
      'Supprimer': function(){
      
        if (currentAct['createFolder']) return false;
        currentAct['createFolder'] = true;
        
        $.ajax({
          type: 'post',
          cache: false,
          url: _paths['site_url'] + 'dossier.php',
          data: {
            mode: 'manipulation',
            action: 'delete',
            type: 'folder',
            id: _folderId
          },
          dataType: 'json',
          success: function(xhr){
            currentAct['createFolder'] = false;
            if (xhr.error == 1) {
              updateTips(xhr.msg);
            } else {
              // Ferme la boite de dialogue
              $(this).dialog('close');
              // Recharge la page
              window.location.href = xhr.data;
            }
          }
        });
      },
      'Annuler': function(){
        $(this).dialog('close');
      }
    }
  });
}

function file_observe(){
  if (currentAct['file_observe']) return false;
  currentAct['file_observe'] = true;
  
  $('#folderFiles').click(function(e){
    var elt = $(e.target);
    var node = elt.attr('nodeName');
    if (node == 'IMG' && elt.hasClass('plus')) file_toggleVersion(elt);
    else if (node == 'IMG' && elt.hasClass('comment')) file_comment(elt);
    else if (node == 'IMG' && elt.hasClass('delete')) file_delete(elt);
    else if (node == 'IMG' && elt.hasClass('new')) file_upload(elt);
  });
}

function file_toggleVersion(e){
  var elt = typeof(e) == 'object' ? e : $('#' + e);
  var master = elt.attr('id').split(_reg);
  
  var show = elt.hasClass('minus') ? false : true;
  
  $('#affichList .subs').each(function(v, k){
    var infos = $(k).attr('id').split(_reg);
    if (infos[1] == master[1]) {
      $(k).toggle(show);
    }
  });
  
  if (show) {
    elt.attr('src', _paths['css'] + 'treeview/minus.gif');
    elt.addClass('minus');
  } else {
    elt.removeClass('minus');
    elt.attr('src', _paths['css'] + 'treeview/plus.gif');
  }
}

function file_comment(e){
  var elt = typeof(e) == 'object' ? e : $('#' + e);
  var infos = elt.attr('id').split(_reg);
  
  // Load dialog from ajax
  $('#dialog_fileComment').load(_paths['site_url'] + 'dossier.php?mode=comment&action=list_file&file=' + infos[1]).dialog({
    autoOpen: true,
    resizable: false,
    height: 500,
    width: 650,
    modal: true,
    open: function(){
      $('.ui-dialog').find('.validateTips').hide();
    },
    close: function(){
      $('#dialog_fileComment').html('');
    },
    buttons: {
      'Valider': function(){
        var comment = $('#file_new_comment');
        comment.removeClass('ui-state-error');
        $('.ui-dialog').find('.validateTips').hide();
        
        if (currentAct['comment_file'] == true) return false;
        currentAct['comment_file'] = true;
        
        $.ajax({
          type: 'post',
          cache: false,
          url: _paths['site_url'] + 'dossier.php',
          data: {
            mode: 'comment',
            action: 'new_file',
            file: infos[1],
            comment: comment.val()
          },
          dataType: 'json',
          success: function(xhr){
            currentAct['comment_file'] = false;
            comment.val('');
            
            if (xhr.error == 1) {
              updateTips(xhr.msg);
            } else {
              $('#file_commentsDetail').html(xhr.data);
              
              // Ferme la boite de dialogue
              //$(this).dialog('close');
              // Recharge la page
              //window.location.href = xhr.data;
            }
          }
        });
      },
      'Fermer': function(){
        $(this).dialog('close');
      }
    }
  });
}

function file_delete(e){
  var elt = typeof(e) == 'object' ? e : $('#' + e);
  var infos = elt.attr('id').split(_reg);
  
  $("#dialog_fileDelete").dialog({
    autoOpen: true,
    resizable: false,
    height: 220,
    width: 350,
    modal: true,
    open: function(){
      $('.ui-dialog').find('.validateTips').hide();
    },
    buttons: {
      'Supprimer': function(){
        if (currentAct['deleteFile']) return false;
        currentAct['deleteFile'] = true;
        
        $.ajax({
          type: 'post',
          cache: false,
          url: _paths['site_url'] + 'dossier.php',
          data: {
            mode: 'manipulation',
            action: 'delete',
            type: 'file',
            id: infos[1]
          },
          dataType: 'json',
          success: function(xhr){
            currentAct['deleteFile'] = false;
            if (xhr.error == 1) {
              updateTips(xhr.msg);
            } else {
              // Ferme la boite de dialogue
              $(this).dialog('close');
              // Recharge la page
              window.location.href = xhr.data;
            }
          }
        });
      },
      'Annuler': function(){
        $(this).dialog('close');
      }
    }
  });
}

function file_upload(e){
  var elt = typeof(e) == 'object' ? e : $('#' + e);
  var infos = elt.attr('id').split(_reg);
  
  $("#dialog_fileUpload").dialog({
    autoOpen: true,
    resizable: false,
    height: 250,
    width: 350,
    modal: false,
    open: function(){
			// nettoyage
			$('#file_new_name').text('');
			$('.ui-dialog').find('.validateTips').text('');
			
      currentAct['ajaxUpload'] = new AjaxUpload('file_new_version', {
        autoSubmit: false,
        action: _paths['site_url'] + 'upload/upload.php',
        name: 'file',
        data: {
          mode: 'single',
          file_id: infos[1],
          folder: _folderId,
          group: _groupId,
          token: _tokenMail
        },
        responseType: 'xml',
        onChange: function(file){
          $('#file_new_name').text(file);
        },
        onSubmit: function(file, ext){
          $('#submit_file_new_version').val('Envoi en cours ...');
        },
        onComplete: function(file, xml){
					var xhr = {
						error : $(xml).find("error").text(),
						msg : $(xml).find("msg").text(),
						data : $(xml).find("data").text()
					}
          //$('#submit_file_new_version').val('value','Envoyer');
          if (xhr.error == 1) {
            updateTips(xhr.msg);
          } else {
            window.location.href = xhr.data;
          }
        }
      });
      
      $('#file_new_version').button();
      $('#submit_file_new_version').click(function(){
        currentAct['ajaxUpload'].submit()
      });
    }
  });
}


/*
 * Fonction utilisateur
 */
function user_createQuick(e){
  currentAct['createUser'] = true;
  
  $.ajax({
    beforeSend: showAjaxIndicator,
    complete: hideAjaxIndicator,
    type: 'post',
    dataType: 'json',
    cache: false,
    url: _paths['site_url'] + 'dossier.php',
    data: {
      ajax: 1,
      mode: 'share',
      action: 'create_user',
      gender: $('#user_gender').val(),
      firstname: $('#user_firstname').val(),
      lastname: $('#user_lastname').val(),
      sct: $('#user_sct').val(),
      email: $('#user_email').val(),
      type: $('#user_type').val()
    },
    success: function(xhr){
      currentAct['createUser'] = false;
      if (xhr.error == 1) {
        messageGlobal('error', xhr.msg);
      } else {
        // Ajout du user
        $('#select_users').append($('<option></option>').val(xhr.user_id).html(xhr.user_text));
        
        // selection du dernier
        $('#select_users').attr('options').selectedIndex = $('#select_users').attr('length') - 1;
        
        // Et mise à jour du tableau de droit
        user_folderShare($('#select_users'));
        //messageGlobal('valid', xhr.msg);
      
      
        /*
         // ajout à la fin
         var newOption = document.createElement('option');
         newOption.text = json.user_text;
         newOption.value = json.user_id;
         $('select_users').options.add(newOption);
         
         // selection du dernier
         $('select_users').options.selectedIndex = $('select_users').options.length - 1;
         
         // Et mise à jour du tableau de droit
         share_folderUser($('select_users'));
         */
      }
    }
  });
}

function user_folderShare(elt){
  if (elt.val() <= 0) {
    $('#submit_share').attr('disabled', 'disabled').hide()
    return false;
  }
  
  $('#submit_share').attr('disabled', null).show()
  
  // met à jour la table
  $('#td_userText').html(elt.find(':selected').text());
}

/**
 * Jumploader
 */
//supprime les fichiers une fois envoyés
function uploaderFileStatusChanged(uploader, file){
  if (file.getStatus() == 2) {
    uploader.removeFile(file);
  }
}

function uploaderStatusChanged(uploader){
  if (uploader.isReady()) {
    $('#warnUpload').switchClass('on', 'off', 'fast');
    
    $.ajax({
      beforeSend: showAjaxIndicator,
      complete: hideAjaxIndicator,
      type: 'post',
      dataType: 'json',
      cache: false,
      url: _paths['site_url'] + 'dossier.php',
      data: {
        ajax: 1,
        mode: 'content',
        action: 'list-ajax',
        folder_id: _folderId
      },
      success: function(xhr){
        if (xhr.error == 1) {
          messageGlobal('error', xhr.msg);
        } else {
          tb_close();
          $('#folderFiles').html(xhr.data);
          if ($('#progress_bar').exists()) {
            $('#quotaMax').html(xhr.quotaMax);
            $('#quotaUsed').html(xhr.quotaUsed);
            $('#quotaPercent').html(xhr.quotaPercent);
            $('#progress_bg').css('width', xhr.quotaPercent + '%');
          }
        }
      }
    });
    
    $.ajax({
      dataType: 'json',
      type: 'post',
      cache: false,
      url: _paths['site_url'] + 'upload/upload.php',
      data: {
        'mode': 'email',
        'token': _tokenMail,
        'group': _groupId,
        'folder': _folderId
      }
    });
  } else {
    $('#warnUpload').switchClass('off', 'on', 'fast');
    //highlight('warnUpload',400);
  }
}

var _menuObj = null;
function submenu(){
  $('#menu_top > li').hover(function(){
    if (_menuObj) {//si l'objet est présent, il est déroulé, donc on le fait disparaitre
      _menuObj.children('ul').hide();
      _menuObj = null;
    } //sinon, on le fait apparaitre lorsque l'on passe la souris dessus
    $(this).children('ul').show();
  }, function(){ //on fait disparaitre si on est plus sur l'élément au bout de 0 seconde
    _menuObj = $(this);
    _menuObj.children('ul').hide();
  }), $('.submenu > li').hover(function(){//fonction qui fait "clignoter une fois" l'entrée du menu au passage de la souris
    //$(this).fadeTo('slow', 0.3);
    //$(this).fadeTo('normal', 1);
  });
}

