// JavaScript Document

// expandable
$(document).ready(function() {
  if($('td[query=surbrillance]') != null){
    $('td[query=surbrillance]').map(
      function(){
        $(this).hover(
          function(){
            $(this).attr('class', $(this).attr('hover'));
          },
          function(){
            $(this).attr('class', $(this).attr('out'));          
          }
        );
      }
    );
  }
  
  if($('img[rel=listeUser]') != null){
    $('img[rel=listeUser]').map(function(){
      $(this).click(function(){
        $('#'+ $(this).attr('destinataire')).toggle();
      });
    });
  }
  
  if($('img[query=expandable]') != null){
    $('img[query=expandable]').map(function () { $(this).click( function(){
      // ouverture/fermeture 
      var identifiant = '#' + $(this).attr('destinataire');
      $(identifiant).toggle();
      
      $('tr[aja=' + $(this).attr('destinataire') + ']').toggle();
      
      // on change l'image
      if($(identifiant).css("display") == "none"){
        $(this).attr('src','/images/icone/14_layer_lowerlayer.png');
      }
      else{
        $(this).attr('src','/images/icone/remove.png');
      }
      
        });
      });
  }
  
  
  /*if($('img[query=show-echeancier]') != null){
    $('img[query=show-echeancier]').map(function () { $(this).click( function(){
      // ouverture/fermeture 
      var identifiantDestTable = '#' + $(this).attr('destinataire') + '-table';
      var identifiantSourceTable = '#' + $(this).attr('source') + '-table';
      var identifiantDestTr = 'tr[target=' + $(this).attr('destinataire') + '-tr]';
      var identifiantSourceTr = 'tr[target=' + $(this).attr('source') + '-tr]';
      
      if($(identifiantSourceTable).css('display') != 'none'){
        $(identifiantDestTable).toggle();
        $(identifiantSourceTable).toggle();
        $(identifiantDestTr).toggle();
        $(identifiantSourceTr).toggle();
      }
      
    });
      });
    }*/
  
  if($('img[query=show-detail]') != null || $('span[query=show-detail]') != null){
    $('img[query=show-detail]').map(function () { $(this).click( function(){
      
      // on affiche les lignes
      $('tr[cible=' + $(this).attr('target') + '-left]').map(function (){    $(this).toggle()});
      $('tr[cible=' + $(this).attr('target') + '-right]').map(function (){    $(this).toggle()});
      
      // on modifie la source de l'image
      
      if($(this).attr('src') == '/images/icone/pastille-plus.png'){
        $(this).attr('src', '/images/icone/pastille-moins.png');  
      }
      else{
        $(this).attr('src', '/images/icone/pastille-plus.png');
      }
    });
      });
    
    $('span[query=show-detail]').map(function () { $(this).click( function(){
      
      $('tr[cible=' + $(this).attr('target') + '-left]').map(function (){    $(this).toggle()});
      $('tr[cible=' + $(this).attr('target') + '-right]').map(function (){    $(this).toggle()});
      
      // on modifie la source de l'image
      if($(this).parent().find('img:first').attr('src') == '/images/icone/pastille-plus.png'){
        $(this).parent().find('img:first').attr('src', '/images/icone/pastille-moins.png');  
      }
      else{
        $(this).parent().find('img:first').attr('src', '/images/icone/pastille-plus.png');
      }
      
    });
      });
    }
  
  if($('img[query=show-detail-variation]') != null || $('span[query=show-detail-variation]') != null){
    $('img[query=show-detail-variation]').map(function () { $(this).click( function(){
      
      // on affiche les lignes
      $('div[cible=' + $(this).attr('target') + ']').map(function (){    $(this).toggle()});
      
      // on modifie la source de l'image
      if($(this).attr('src') == '/images/icone/pastille-plus.png'){
        $(this).attr('src', '/images/icone/pastille-moins.png');  
      }
      else{
        $(this).attr('src', '/images/icone/pastille-plus.png');
      }
    });
      });
    
    $('span[query=show-detail-variation]').map(function () { $(this).click( function(){
      
      $('div[cible=' + $(this).attr('target') + ']').map(function (){    $(this).toggle()});
        
      // on modifie la source de l'image
      if($(this).parent().find('img:first').attr('src') == '/images/icone/pastille-plus.png'){
        $(this).parent().find('img:first').attr('src', '/images/icone/pastille-moins.png');  
      }
      else{
        $(this).parent().find('img:first').attr('src', '/images/icone/pastille-plus.png');
      }
      
    });
      });    
  }
  
  if($('div[query=show_detail_fiche_fournisseur]') != null){
    $('div[query=show_detail_fiche_fournisseur]').map(
      function () {
        var identifiant = '#' + $(this).attr('destinataire');                                               
        var bouton = '#' + $(this).attr('bouton');                                               
        $(identifiant).hide();
        $(bouton).click(
          function(){
            // ouverture/fermeture 
            $(identifiant).toggle(400);
            if($(this).find('.ouvrir').attr('class') == 'ouvrir'){
              $(this).find('.ouvrir').attr('class','fermer');
            }else{
              $(this).find('.fermer').attr('class','ouvrir');
            }
          }
        );
      }
    );
  }
  
  
  if(typeof page_echeancier != 'undefined'){
    initMessage();
  }
  
});

//Changement de couleur au survol d'une ligne d'un tableau (page rapprochement) 
$(function()
{
  $(".tab-rapprochement tr").mouseover(function() {
    $(this).addClass("trover");
  }).mouseout(function() {
    $(this).removeClass("trover");
  })
});

//Changement de couleur au survol d'une ligne d'un tableau (page liste des fournisseurs) 
$(function()
{
  $(".tab-fiche-liste tr").mouseover(function() {
    $(this).addClass("trover");
  }).mouseout(function() {
    $(this).removeClass("trover");
  })
});

//Changement de couleur au survol d'une ligne d'un tableau (page variation) 
$(function()
{
  $(".table-variation tr").mouseover(function() {
    $(this).addClass("trover");
  }).mouseout(function() {
    $(this).removeClass("trover");
  })
});

//Changement de couleur au survol d'une ligne d'un tableau (page table de correspondance) 
$(function()
{
  $(".tab-correspondance tr").mouseover(function() {
    $(this).addClass("trover");
  }).mouseout(function() {
    $(this).removeClass("trover");
  })
});

/**
 * Met a jour les différents éléments de la page en fonction de la sélection
 * faite par l'utilisateur
 *
 * @param   int     id              l'identifiant de l'echeancier
 * @param   bool    fournisseur     Vrai si l'utilisateur est un fournisseur
 * @param   bool    retard          Vrai s'il y a un avance retard négatif
 * @param   bool    valide          Vrai si la ligne a été validé
 */
function updateMessageId(id, fournisseur, retard, valide)
{
  var select  = document.getElementById('select_message_id_' + id);
  var input   = document.getElementById('message_id' + id);
  var image   = document.getElementById('img_aja-commentaire' + id);
  
  input.value = select.options[select.selectedIndex].value;
  
  if(input.value == 1){
    document.getElementById('tr_partielle_' + id).style.display = 'none';
  } else {
    document.getElementById('tr_partielle_' + id).style.display = '';
  }
  
  if(afficheMessage(fournisseur, retard, valide)){
    image.style.display = '';
  } else {
    image.style.display = 'none';
  }
  
  showImageMessage(id, input.value);
}


function showImageMessage(id, id_message)
{
  var new_icone;
  
  switch(id_message){
    case '1':
      new_icone = 'icone/confirmation-livraison';
      break;
    
    case '2':
      new_icone = 'icone/pas-reponse';
      break;
    
    case '3':
      new_icone = 'icone/livraison-partielle';
      break;
    
    case '4':
      new_icone = 'icone/livraison-retard';
      break;
    
    default:
      new_icone = 'icone/pas-reponse';
      break;
  }
  
  var image   = document.getElementById('icone_message_' + id);
  var source  = image.getAttribute('src');
  var re      = new RegExp("icone/([-a-z]+)", "g");
  source = source.replace(re, new_icone);
  image.setAttribute('src', source);
}


/**
 * Permet de savoir si on doit ou non afficher le message
 *
 * @param   bool    fournisseur     Vrai si l'utilisateur est un fournisseur
 * @param   bool    retard          Vrai s'il y a un avance retard négatif
 * @param   bool    valide          Vrai si la ligne a été validé
 * @return  bool                    Vrai si on doit afficher le message, faux sinon
 */
function afficheMessage(fournisseur, retard, valide)
{
  return true;
}


var error_id_message = 'Veuillez mettre une réponse.';
var error_date_retard = 'Veuillez indiquer un date pour le retard';
var error_quantite_partielle = 'Veuillez indiquer une quantité pour le retard';
var error_date = 'Veuillez indiquer un date pour le retard';
var error_avance_retard = 'Veuillez indiquer une quantite pour le retard';
var error_reponse = 'Veuillez indiquer une réponse pour le retard';

/**
 * Validation du formulaire
 *
 * @param     int   id    L'identifiant de l'écheancier permettant de retrouver les différents formulaires
 * @returns   bool        Vrai si le formulaire est bon, Faux sinon
 */
function checkData(id, global, id_echeancier_livraison, verification_globale_allege)
{
  if(global == true){
    
    // MAJ 09/12/2009
    // On ne fait plus de vérification pour la validation globale
    
    if (verification_globale_allege  == true) {
    
      return true;
    
    }
    
    var selected = $('#select_message_global_id_' + id_echeancier_livraison).selectedValues();
  } else {
    var selected = $('#select_message_id_' + id).selectedValues();
  }
  if(selected.length == 1){
    var selected_value = selected[0];
  } else {
    return false;
  }
  // On doit sélectionner une réponse
  if(selected_value == '2'){
    alert(error_id_message);
    return false;
  }
  
  var retard, date_retard, quantite_partielle, date, avance_retard, reponse;
  try {
    retard = $('#retard_' + id)[0].value;
  } catch (e) {
    retard = 0;
  }
  try {
    date_retard = $('#date_retard_' + id)[0].value;
  } catch (e) {
    date_retard = null;
  }
  try {
    quantite_partielle = $('#quantite_livraison_partielle_' + id)[0].value;
  } catch (e) {
    quantite_partielle = null;
  }
  try {
    date = $('#date_' + id)[0].value;
  } catch (e) {
    date = null;
  }
  try {
    avance_retard = $('#avance_retard_' + id)[0].value;
  } catch (e) {
    avance_retard = null;
  }
  try {
    reponse = $('#reponse_' + id)[0].value;
  } catch (e) {
    reponse = null;
  }
  
  if(retard < 0){
    if(selected_value == '1'){
      if(date_retard == null || date_retard == '' || !check_date(date_retard) || !isDateFutur(date_retard)){
        alert(error_date_retard);
        try {$('#date_retard_' + id)[0].focus();} catch (e) {}
        return false;
      }
      if(quantite_partielle == null || quantite_partielle == '' || !is_numeric(quantite_partielle)){
        alert(error_quantite_partielle);
        try {$('#quantite_partielle_' + id)[0].focus();} catch (e) {}
        return false;
      }
    }
    if(selected_value == '3'){
      if(date_retard == null || date_retard == '' || !check_date(date_retard) || !isDateFutur(date_retard)){
        alert(error_date_retard);
        try {$('#date_retard_' + id)[0].focus();} catch (e) {}
        return false;
      }
      if(quantite_partielle == null || quantite_partielle == '' || !is_numeric(quantite_partielle)){
        alert(error_quantite_partielle);
        try {$('#quantite_partielle_' + id)[0].focus();} catch (e) {}
        return false;
      }
      if(date == null || date == '' || !check_date(date) || !isDateFutur(date)){
        alert(error_date);
        try {$('#date_' + id)[0].focus();} catch (e) {}
        return false;
      }
      if(avance_retard == null || avance_retard == '' || !is_numeric(avance_retard)){
        alert(error_avance_retard);
        try {$('#avance_retard_' + id)[0].focus();} catch (e) {}
        return false;
      }
      if(reponse == null || reponse == ''){
        alert(error_reponse);
        try {$('#reponse_' + id)[0].focus();} catch (e) {}
        return false;
      }
    }
  } else {
    if(selected_value == '1'){
    }
    if(selected_value == '3'){
      if(date == null || date == '' || !check_date(date) || !isDateFutur(date)){
        alert(error_date);
        try {$('#date_' + id)[0].focus();} catch (e) {}
        return false;
      }
      if(avance_retard == null || avance_retard == '' || !is_numeric(avance_retard)){
        alert(error_avance_retard);
        try {$('#avance_retard_' + id)[0].focus();} catch (e) {}
        return false;
      }
      if(reponse == null || reponse == ''){
        alert(error_reponse);
        try {$('#reponse_' + id)[0].focus();} catch (e) {}
        return false;
      }
    }
  }
  
  return true;
}


/**
 * Vérifie que la donnée est une date au format 00/00/0000
 *
 * @param     string    mixed_var     La variable à vérifier
 * @returns   bool                    Vrai si la chaine est une date, Faux sinon
 */
function check_date(mixed_var)
{
  var expr = new RegExp("^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$");
  if(!expr.test(mixed_var)){
    return false;
  }
  
  return true
}


/**
 * Vérifie que la variable est un nombre
 * 
 * @param     string    mixed_var     La variable à vérifier
 * @returns   bool                    Vrai si la chaine est un numerique, Faux sinon 
 */
function is_numeric( mixed_var ) {
  // Finds whether a variable is a number or a numeric string
  // 
  // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_is_numeric/
  // +       version: 804.1712
  // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   improved by: David
  // *     example 1: is_numeric(186.31);
  // *     returns 1: true
  // *     example 2: is_numeric('Kevin van Zonneveld');
  // *     returns 2: false
  // *     example 3: is_numeric('+186.31e2');
  // *     returns 3: true
  return !isNaN( mixed_var );
}

// {{{ mktime
function mktime() {
    // Get Unix timestamp for a date
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_mktime/
    // +       version: 807.1807
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: baris ozdil
    // +      input by: gabriel paderni 
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: FGFEmperor
    // +      input by: Yannoo
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: jakes
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: mktime(14, 10, 2, 2, 1, 2008);
    // *     returns 1: 1201871402
    // *     example 2: mktime(0, 0, 0, 0, 1, 2008);
    // *     returns 2: 1196463600
    
    var no, ma = 0, mb = 0, i = 0, d = new Date(), argv = arguments, argc = argv.length;
    d.setHours(0,0,0); d.setDate(1); d.setMonth(1); d.setYear(1972);
 
    var dateManip = {
        0: function(tt){ return d.setHours(tt); },
        1: function(tt){ return d.setMinutes(tt); },
        2: function(tt){ set = d.setSeconds(tt); mb = d.getDate() - 1; return set; },
        3: function(tt){ set = d.setMonth(parseInt(tt)-1); ma = d.getFullYear() - 1972; return set; },
        4: function(tt){ return d.setDate(tt+mb); },
        5: function(tt){ return d.setYear(tt+ma); }
    };
    
    for( i = 0; i < argc; i++ ){
        no = parseInt(argv[i]*1);
        if (isNaN(no)) {
            return false;
        } else {
            // arg is number, let's manipulate date object
            if(!dateManip[i](no)){
                // failed
                return false;
            }
        }
    }

    return Math.floor(d.getTime()/1000);
}// }}}

// {{{ time
function time() {
    // Return current Unix timestamp
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_time/
    // +       version: 807.1808
    // +   original by: GeekFG (http://geekfg.blogspot.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: time();
    // *     returns 1: 1216363871
    
    var d = new Date();
    return Math.round(d.getTime()/1000);
}// }}}


function isDateFutur(date)
{
  // suite à une demande de Pascal, on accepte les dates qui ne sont pas dans le futur
  return true;
  
  // On a déjà vérifié la date donc on tape dedans
  var jour, mois, annee, date_voulue;
  
  jour = substr(date, 0, 2);
  mois = substr(date, 3, 2);
  annee = substr(date, 6, 4);
  date_voulue = mktime(0, 0, 0, mois, jour, annee);
  
  if(date_generation > date_voulue){
    return false;
  } else {
    return true;
  }
}


function check_periode_fermeture()
{
  var date_debut, date_fin;
  
  try {
    date_debut = $('#date_debut')[0].value;
  } catch (e) {
    date_debut = null;
  }
  try {
    date_fin = $('#date_fin')[0].value;
  } catch (e) {
    date_fin = null;
  }
  
  if(date_debut == null || date_debut == '' || !check_date(date_debut)){
    alert(error_date_retard);
    try {$('#date_debut')[0].focus();} catch (e) {}
    return false;
  }
  
  if(date_fin == null || date_fin == '' || !check_date(date_fin)){
    alert(error_date_retard);
    try {$('#date_fin')[0].focus();} catch (e) {}
    return false;
  }
  
  return true;
}


function changeVehicule(select)
{
  var index;
  var code, qte;
  
  index = select.selectedIndex;
  code  = document.getElementById('code_vehicule');
  qte   = document.getElementById('qte_vehicule');
  
  try {
    code.innerHTML  = data_vehicule[index][0];
    qte.innerHTML   = data_vehicule[index][1];
  } catch (e){ alert(e); }
}


function updateMessageGlobalId(id)
{
  var selected = $('#select_message_global_id_' + id)[0].options[$('#select_message_global_id_' + id)[0].selectedIndex].value;
  
  $('.el_' + id).selectOptions(selected, true);
  
  var select = $('.el_' + id);
  var nb_select = select.length;
  var id_select = '';
  
  for(var i = 0; i < nb_select; i++){
    id_select = select[i].id;
    
    // On récupère l'identifiant de l'echeancier
    id_select = id_select.replace(/(select_message_id_)/, '');
    
    // On met à jour la liste
    updateMessageId(id_select);
  }
}


function validationGlobale(form, verification_globale_allegee)
{
  try {
    var echeancier_id;
    var parent = form;
    var id_echeancier_livraison = parent.id;
    id_echeancier_livraison = id_echeancier_livraison.replace(/(form_echeancier_livraison_id_)/, '');
    
    var message_id = $('.el_' + id_echeancier_livraison);
    var nb_message_id = message_id.length;
    for(var i = 0; i < nb_message_id; i++){
      echeancier_id = message_id[i].id.replace(/(select_message_id_)/, '');
      removeAllInput(echeancier_id, parent);
      addInputHidden(parent, message_id[i].name + '[' + echeancier_id + ']', message_id[i].id + '_global', message_id[i].value);
      recupRetard(parent, echeancier_id);
      recupDate(parent, echeancier_id);
      recupAvanceRetard(parent, echeancier_id);
      recupReponse(parent, echeancier_id);
      recupDateRetard(parent, echeancier_id);
      recupQuantiteLivraisonPartielle(parent, echeancier_id);
      
      // on vérifie le formulaire
      if(checkData(echeancier_id + '_global', true, id_echeancier_livraison, verification_globale_allegee) == false) {
        return false;
      }
    }
    
    return true;
  } catch (e) {
    return false;
  }
}


function removeAllInput(echeancier_id, parent)
{
  removeInput('select_message_id_' + echeancier_id + '_global', parent);
  removeInput('retard_' + echeancier_id + '_global', parent);
  removeInput('date_' + echeancier_id + '_global', parent);
  removeInput('date_retard_' + echeancier_id + '_global', parent);
  removeInput('avance_retard_' + echeancier_id + '_global', parent);
  removeInput('quantite_livraison_partielle_' + echeancier_id + '_global', parent);
  removeInput('reponse_' + echeancier_id + '_global', parent);
}


function recupRetard(parent, echeancier_id)
{
  var retard = document.getElementById('retard_' + echeancier_id);
  
  if(retard){
    addInputHidden(parent, retard.name + '[' + echeancier_id + ']', retard.id + '_global', retard.value);
  }
}


function recupDate(parent, echeancier_id)
{
  var date = document.getElementById('date_' + echeancier_id);
  
  if(date){
    addInputHidden(parent, date.name + '[' + echeancier_id + ']', date.id + '_global', date.value);
  }
}


function recupDateRetard(parent, echeancier_id)
{
  var date = document.getElementById('date_retard_' + echeancier_id);
  
  if(date){
    addInputHidden(parent, date.name + '[' + echeancier_id + ']', date.id + '_global', date.value);
  }
}


function recupAvanceRetard(parent, echeancier_id)
{
  var avance_retard = document.getElementById('avance_retard_' + echeancier_id);
  
  if(avance_retard){
    addInputHidden(parent, avance_retard.name + '[' + echeancier_id + ']', avance_retard.id + '_global', avance_retard.value);
  }
}


function recupQuantiteLivraisonPartielle(parent, echeancier_id)
{
  var quantite = document.getElementById('quantite_livraison_partielle_' + echeancier_id);
  
  if(quantite){
    addInputHidden(parent, quantite.name + '[' + echeancier_id + ']', quantite.id + '_global', quantite.value);
  }
}


function recupReponse(parent, echeancier_id)
{
  var reponse = document.getElementById('reponse_' + echeancier_id);
  
  if(reponse){
    addInputHidden(parent, reponse.name + '[' + echeancier_id + ']', reponse.id + '_global', reponse.value);
  }
}


function addInputHidden(parent, name, id, value)
{
  input = document.createElement('input');
  input.setAttribute('type', 'hidden');
  input.setAttribute('name', name);
  input.setAttribute('id', id);
  input.setAttribute('value', value);
  parent.appendChild(input);
}


function removeInput(id, parent)
{
  try { parent.removeChild(document.getElementById(id)); } catch (e) {}
}