
//-------------------------------------------------------------------------------
//--- Gestion du déroulement/enroulement des items de la FAQ (entre autres)   ---
//-------------------------------------------------------------------------------
function toggleFAQ(el)
{
liste = document.getElementsByTagName('li');
for (i = 0; i < liste.length; i++)
  if (liste[i].parentNode.className == 'faq')
  {
    var p = liste[i].getElementsByTagName('div');

    if (p.length && p[0])
      p = p[0];

    var h3 = liste[i].getElementsByTagName('h3');

    if (h3.length && h3[0])
      h3 = h3[0];

    if (liste[i] == el)
    {
      if (p.style.display != 'block')
        {
        target = $(p).height();
        $(p).height('0');
        $(p).css('opacity','0');
        $(p).animate(
            {opacity:1, height: target},
            500,
            'linear',
            function() {
                $(this).css('display','block');
                $(this).parent().find('h3')[0].className = 'open';
            });
        }
      else
        {
        target = $(p).height();
        $(p).animate(
            {opacity:0, height: 0},
            500,
            'linear',
            function() {
                $(this).css('display','none');
                $(this).height(target);
                $(this).parent().find('h3')[0].className = 'closed';
            });
        }
    }
    else
        if (p.style.display == 'block')
        {
        target = $(p).height();
        $(p).animate(
            {opacity:0, height: 0},
            500,
            'linear',
            function() {
                $(this).css('display','none');
                $(this).height(target);
                $(this).parent().find('h3')[0].className = 'closed';
            });
        }
  }
}
//-------------------------------------------------------------------------------
//--- Gestion des regroupements de lignes sur un tableau (à valeur identique) ---
//-------------------------------------------------------------------------------
// peudo-constants
_TR_SHOW_ = document.all?'block':'table-row';
_TR_HIDE_ = 'none';

GroupedTable = function(table_id, column){
    // for saving  purpose
        this._tblID = table_id;
        this._key_col = column;

        // main pointers
    this._tbl = $('#'+this._tblID);
        this._tblBody = null;

        // storage area
        this._mem_tbl = Array();
        }

// Loads a table into memory
GroupedTable.prototype._loadTable = function () {

        // load table in memory
        this._tblBody = $('#'+this._tblID+' > tbody:first');

        // fill up the rows
        var lig = 0;
        var mem_tbl = this._mem_tbl;

        this._tblBody.children('tr').each(function(){
                mem_tbl[lig++] = {meta:'', data:$(this).children('td')};
                });
}

// Unload a memory table back to it's DOM node
GroupedTable.prototype._unloadTable = function (key_col) {
        var disp = 'block';
        var current_meta = '';

        if (!key_col) key_col=this._key_col;

        // replace html data (DOM nodes)
        this._tblBody.empty();

        for (i = 0; i < this._mem_tbl.length; i++)
          {
          var tr = document.createElement('tr');

          // are we starting a group ?
          if (this._mem_tbl[i]['meta'] != '' && this._mem_tbl[i]['meta'] != current_meta)
            {
                // save the current group name
                current_meta = this._mem_tbl[i]['meta'];

                if (i < this._mem_tbl.length - 1 && this._mem_tbl[i]['meta'] != 'nogroup')
                        {
                        // then
                        var tr2 = document.createElement('tr');
                        var td2 = '';
                        if ($(this._mem_tbl[i]['data'][key_col]).attr('class') != '')
                            td2 += 'class="'+$(this._mem_tbl[i]['data'][key_col]).attr('class')+'"';

                        if ($(this._mem_tbl[i]['data'][key_col]).attr('style') != '')
                            td2 += 'style="'+$(this._mem_tbl[i]['data'][key_col]).attr('style')+'"';

                        if ($(this._mem_tbl[i]['data'][key_col]).attr('align') != '')
                            td2 += 'align="'+$(this._mem_tbl[i]['data'][key_col]).attr('align')+'"';

                        td2 += ' colspan="'+this._mem_tbl[i]['data'].length+'"';
                        td2 += ' onclick="toggleRowDisplay(this,\''+current_meta+'\')"';

                        $(tr2).addClass('group_header');
                        $(tr2).append('<td '+td2+'>[+] '+$(this._mem_tbl[i]['data'][key_col]).text()+'...</td>');

                        this._tblBody.append(tr2);

                        // set display mode for following rows
                        disp = _TR_HIDE_;
                        }
                else
                    disp = _TR_SHOW_;
                }

                if (i < this._mem_tbl.length - 1)
                {
                  $(tr).addClass(current_meta);
                  $(tr).css('display', disp);
                }
                else
                        $(tr).attr('display',_TR_SHOW_);

          for (j = 0; j < this._mem_tbl[i]['data'].length; j++)
                {
                td = $(this._mem_tbl[i]['data'][j]).clone(true);
                $(tr).append(td);
                }

                this._tblBody.append(tr);
          }

        delete(mem_tbl);
}

// Sort a memory table using specified column key
GroupedTable.prototype._sortTable = function (key_col) {

        if (!key_col) key_col=this._key_col;

        // sort table by (global) key column
        function sortByColumn(a, b)
        {
        var lig1 = $(a['data'][key_col]).text();
        var lig2 = $(b['data'][key_col]).text();

        if (true)
                {
                if (lig1 > lig2)
                  return 1;
                if (lig1 < lig2)
                  return -1;
                else
                  return 0;
                }
        else
          return 0;
        }

        // if the table is already sorted, reverse the order
        sorted_class = 's_'+key_col;
    if (this._tbl.attr('class').indexOf(sorted_class) >= 0)
          {
          this._tbl.removeClass(sorted_class);
          this._mem_tbl.reverse();
          }
    else
          {
          this._mem_tbl = this._mem_tbl.sort(sortByColumn);
          this._tbl.addClass(sorted_class);
          }
}

// Groups rows with the same column value
GroupedTable.prototype._groupRows = function (key_col) {

var def_val='';
var group_id = 0;

if (!key_col) key_col=this._key_col;

for (i = 0; i < this._mem_tbl.length; i++)
        {
        for (j = 0; j < this._mem_tbl[i]['data'].length; j++)
          if (j == key_col && $(this._mem_tbl[i]['data'][j]).text() != '')
          {
           if ($(this._mem_tbl[i]['data'][j]).text() != def_val)
           {
           def_val = $(this._mem_tbl[i]['data'][j]).text();
           this._mem_tbl[i]['meta'] = 'nogroup';
           if (i < this._mem_tbl.length-1)
                   if ($(this._mem_tbl[i]['data'][j]).text() == $(this._mem_tbl[i+1]['data'][j]).text())
                   {
                   group_id++;
                   this._mem_tbl[i]['meta'] = '';
                   }
           }
           if (this._mem_tbl[i]['meta'] == '')
                this._mem_tbl[i]['meta'] = 'group_'+this._tblID+'_'+group_id;
          }
        }
}

// Groups rows with the same column value
GroupedTable.prototype._ungroupRows = function () {

var rows = this._tbl.children('tr');

for (var i = 0; i < rows.length; i++)
        {
    var cols = rows[i].children('td');
        for (var j = 0; j < cols.length; j++)
                {
                  var txt = $(cols[j]).val();
                        if (txt.indexOf('[+]') >=0 || txt.indexOf('[-]') >= 0)
                                $(rows[i]).remove(cols[j]);
                        else
                           $(rows[i]).css('display', _TR_SHOW_);
                }
        }
}

// public function for
function toggleRowDisplay(obj, id) {

var rows = $('tr[class*=\''+id+'\']');

rows.each(function(){ $(this).toggle(); });

if ($(obj).text().indexOf('[+]') >= 0)
        $(obj).text($(obj).text().replace('[+]','[-]'));
else
        $(obj).text($(obj).text().replace('[-]','[+]'));
}

// public function for sorting data
function sortTable(table_id, column) {

 var grpTbl = new GroupedTable(table_id, column);

 grpTbl._ungroupRows();

 grpTbl._loadTable();

 grpTbl._sortTable();

// group rows using the specified column
 grpTbl._groupRows();

 grpTbl._unloadTable();
}

$().ready(function(){
  // Fonctions appelées au chargement de la page
  // pour actualiser l'interface

  // -- Actualiser l'état de connexion au compte client
  function checkConnected()
  {
  $.ajax({
    type: 'GET',
    url: '/compte/check',
    data: 'page='+escape(window.location.search),
    success: function(ret_string){
      if (ret_string != '') // nom-prénom du client
        {
        $('#non_connecte').css('display','none');
        $('#txt_compte').text(ret_string);
        $('#connecte').css('display','block');
        $('#section_compte').css('display','block');
        $('#section_client').css('display','block');
        $('#section_commandes').css('display','block');
        }
      else // sinon rien
        {
        $('#non_connecte').css('display','block');
        $('#txt_compte').text('Me connecter');
        $('#connecte').css('display','none');
        $('#section_compte').css('display','none');
        $('#section_client').css('display','none');
        $('#section_commandes').css('display','none');
        }
    },
    error: function(xhr, msg, exception){
      $('#non_connecte').css('display','block');
      $('#txt_compte').text('Me connecter');
      $('#connecte').css('display','none');
      $('#section_compte').css('display','none');
      $('#section_commandes').css('display','none');

      //alert('(app~compte:check)Erreur interne au fonctionnement du site. Merci de le signaler à Isabelle CHOPLIN via le formulaire de contact.');
    }
    });
  }

  // -- Actualiser l'état du panier
  function refreshCart()
  {
  $.ajax({
    type: 'GET',
    url: '/panier/refresh',
    data: '',
    dataType : 'json',
    success: function(json){
      var infos = json;
      if (infos)
        {
        if (infos.articles > 0)
          {
          $('#articles').html(infos.articles+'&nbsp;'+'article(s)'+'&nbsp;=&nbsp;');
          $('#montant').html(infos.montant);
          }
        else
          {
          $('#articles').html('Panier vide');
          $('#montant').html('');
          }
        }
    },
    error: function(xhr, msg, exception){
      //alert('(app~panier:refresh)Erreur interne au fonctionnement du site. Merci de le signaler à Isabelle CHOPLIN via le formulaire de contact.');
    }
    });
  }

  // -- Vérifier les nouveaux tickets
  function checkTickets()
  {
  $.ajax({
    type: 'GET',
    url: '/ticket/check',
    data: '',
    success: function(nb){
          if (nb > 0)
            {
            $('#txt_tickets').html(parseInt(nb)+'&nbsp; Mes messages');
            $('#txt_tickets').css('opacity', '1');
            }
          else
            {
            $('#txt_tickets').html('Aucun message');
            $('#txt_tickets').css('opacity', '0.7');
            }
    },
    error: function(xhr, msg, exception){
      //alert('(app~ticket:check)Erreur interne au fonctionnement du site. Merci de le signaler à Isabelle CHOPLIN via le formulaire de contact.');
    }
    });
  }

  function checkUserprefs()
  {
  $.ajax({
    type: 'GET',
    url: '/default/check',
    data: '',
    success: function(locale){

      if (!locale) locale = 'fr_FR';

      $('.locale[id!='+locale+']').each(function(){
        $(this).css('opacity',0.5);
        $(this).attr('class','locale');
      });

      $('#'+locale).css('opacity',1);
      $('#'+locale).attr('class','locale current');
    },
    error: function(xhr, msg, exception){
      //alert('(app~panier:refresh)Erreur interne au fonctionnement du site. Merci de le signaler à Isabelle CHOPLIN via le formulaire de contact.');
    }
    });
  }

  // Initialisation, c'est parti
    function onMenuOver(){
    $('.dropdown_menu').hide();
    $(this).find('a').first().focus();
    $(this).find('.dropdown_menu').stop().slideDown('600');
    }

    function onMenuOut(){
    $(this).find('a').first().blur();
    $(this).find('.dropdown_menu').hide();
    }

    var settings = {
        sensitivity: 2,
        interval: 100,
        over: onMenuOver,
        out: onMenuOut,
        timeout: 500
    };

    $('.mainmenu').hoverIntent(settings);


  // -- Initialiser la zone de recherche
  $('#texte').attr('autocomplete','off');
  $('#texte').val('Veuillez entrer le texte recherché');
  $('#suggestion').html('');

  // -- Initialiser les champs de contrôles si présents
  $('#motpasse').val('');
  $('#motpasse').attr('autocomplete','off');
  $('#email2').val('');
  $('#email2').attr('autocomplete','off');
  $('#motpasse2').val('');
  $('#motpasse2').attr('autocomplete','off');

  // -- Vérifier l'état des paramètres
  checkUserprefs();
  checkConnected();
  refreshCart();
  checkTickets();

  // -------------Gestion évènementielle------------------
  // -- Liens extérieurs
  $('a.externe').each(function(){
    var target = $(this).attr('href');
    
    $(this).removeAttr('target');
    $(this).attr('title', 'ouvre le lien dans une nouvelle fenêtre');

    $(this).bind('click', function() { window.open($(this).attr('href'), '_blank'); return false; });
  });
  
  // -- Boutons de gestion de la police
  $('#grand').live('mouseup', function(){
    $('body').css('font-size', (parseFloat($('body').css('font-size')) *1.1)+'px');
  });

  $('#petit').live('mouseup', function(){
    $('body').css('font-size', (parseFloat($('body').css('font-size')) *0.9)+'px');
  });

  // -- Survol de la langue
  $('.locale').live('mouseover', function(){
    if ($(this).attr('class').indexOf('current') == -1)
    {
        $(this).stop();
        $(this).fadeTo('fast', 1);
    }
  });
  $('.locale').live('mouseout', function(){
    if ($(this).attr('class').indexOf('current') == -1)
    {
        $(this).stop();
        $(this).fadeTo('fast', 0.5);
    }
  });

  // -- Changement de devise
  $('#prefs_devise').bind($.browser.msie?'change':'change', function(){
    $.ajax({
      type: 'GET',
      url: '/default/change_ui',
      data: 'prefs_devise='+this.value,
      success: function(msg){
        $('#prefs_form').submit();
      }
     });
  });

  // Fonctions relatives au compte client

  // -- Mot de passe perdu
  $('#perdu').live('click',function(e){
            e.stopPropagation();
    if ($('#email').val() == '')
      alert('Vous devez au moins indiquer votre e-mail !');
    else
      {
      $.ajax({
        type: 'GET',
        url: '/compte/password',
        data: 'email='+$('#email').val(),
        success: function(msg){
          alert("Un nouveau mot passe vous a été envoyé.");
        },
        error: function(xhr, msg, exception){
          alert("(app~compte:password)Erreur interne au fonctionnement du site. Merci de le signaler à Isabelle CHOPLIN via le formulaire de contact.");
        }
        });
      }
                return false;
  });

  // -- Suppresion du compte
  $('#supprimer').live('click',function(){
    if (confirm("Etes-vous certain de vouloir supprimer votre compte ?"))
      {
      $.ajax({
        type: 'GET',
        url: '/compte/delete',
        data: '',
        success: function(msg){
          setTimeout("$('#logout').click()", 1000);
          alert("Compte supprimé");
        },
        error: function(xhr, msg, exception){
          alert("(app~compte:delete)Erreur interne au fonctionnement du site. Merci de le signaler à Isabelle CHOPLIN via le formulaire de contact.");
        }
        });
      }
  });

  // -- Déconnexion
  $('#logout').live('click',function(){
    $.ajax({
      type: 'GET',
      url: '/compte/logout',
      data: 'email='+$('#email').val(),
      success: function(msg){
      if (msg != 'ERREUR')
        {
        $('#non_connecte').css('display','block');
        $('#txt_compte').text('Me connecter');
        $('#connecte').css('display','none');
        $('#section_compte').css('display','none');
        $('#section_client').css('display','none');
        $('#section_commandes').css('display','none');
        }
      },
      error: function(xhr, msg, exception){
        alert("(app~compte:logout)Erreur interne au fonctionnement du site. Merci de le signaler à Isabelle CHOPLIN via le formulaire de contact.");
      }
      });
  });

  // -- Fermeture de l'espace client
  $('#close').live('click', function() {
    $('#compte').click();
  });

  // -- Ouverture de l'espace client
  $('#compte').bind('click', function(){
    if ($('#detail_compte').css('display') == 'block')
      $('#detail_compte').css('display','none');
    else
      $('#detail_compte').css('display','block');
    });

// Fonction de base pour un appel ajax
function doAjaxCall(id, service, params, destination, redirect)
{
    if (!id || !service || !destination)
      return;

    $(destination).stop();
    $(destination).fadeTo('fast', 0.5);

    $.ajax({
        type: 'GET',
        url: service,
        data: params,
        success: function(response){
            if (response.substr(0, 8) == 'message:')
                alert(response.substring(8));
            else
                $(destination).html(response);

            $(destination).fadeTo('slow', 1);

            if (redirect) setTimeout(redirect, 500);
        },
        error: function(xhr, msg, exception){
            alert("("+id+")Erreur interne au fonctionnement du site. Merci de le signaler à Isabelle CHOPLIN via le formulaire de contact.");
        }
    });

    // Revérifier l'état
    checkTickets();
}

// -- Onglets de la nouvelle interface client
$('.tab_bar li.tab').live('mouseover', function(){
    if ($(this).attr('class').indexOf('active') == -1)
    {
        $(this).stop();
        $(this).attr('class','tab current');
    }
});

$('.tab_bar li.tab').live('mouseout', function(){
    if ($(this).attr('class').indexOf('active') == -1)
    {
        $(this).stop();
        $(this).attr('class','tab');
    }
});

$('.tab_bar li.tab a').live('click', function(){
    this.blur();

    $('.tab_bar li.tab a[id!='+this.id+']').each(function(){
        $(this).parent().attr('class','tab');
    });

    $(this).parent().attr('class','tab current active');

    var service = '';

    switch (this.id)
    {
    case 'compte_compte':
        service = '/compte/index';
    break;
    case 'compte_telechargements':
        service = '/commande/compilation';
    break;
    case 'compte_offerts':
        service = '/offerts/index';
    break;
    case 'compte_commandes':
        service = '/commande/index';
    break;
    case 'compte_tickets':
        service = '/ticket/index';
    break;
    }

    if (service != '')
        doAjaxCall(this.id, service, 'partial=1', '#compte_data', '');
    else
        $('#compte_data').html('');
});

$('#compte_data #compte_ok').live('click', function(e){
        e.stopPropagation();

        var formfields = new Array('nom','prenom', 'email','email2','motpasse','motpasse2','code_postal','ville','adresse1','adresse2','region','pays','anniversaire','telephone','langue','devise','format','machine','newsletter');

        var formdata = '';

        var selector = '';

        for (var i=0; i < formfields.length; i++)
        {
            selector = '#compte_'+formfields[i];
            if (typeof($(selector).val()) != 'undefined')
            {
                if ($(selector).attr('type') == 'checkbox' || $(selector).attr('type') == 'radio')
                    formdata += '&'+formfields[i]+'='+( ($(selector).attr('checked')!='')?'on':'off' );
                else
                    formdata += '&'+formfields[i]+'='+escape($(selector).val());
            }
        }

        doAjaxCall('app~ticket:open', '/compte/update', 'partial=1&OK=1&'+formdata, '#compte_data', '');

        return false;
});

$('#compte_data a.detail_commande').live('click', function(e){
        e.stopPropagation();

        var infos = this.id.split('_');
        var id_commande = infos[2];

        doAjaxCall('app~commande:detail', '/commande/detail', 'partial=1&id_commande='+id_commande, '#compte_data', '');

        return false;
});

$('#compte_data #commande_global').live('click', function(e){
        e.stopPropagation();

        var infos = this.id.split('_');
        var id_commande = infos[2];

        doAjaxCall('app~commande:compilation', '/commande/compilation', 'partial=1&id_commande='+id_commande, '#compte_data', '');

        return false;
});

$('#compte_data #commande_retour').live('click', function(e){
        e.stopPropagation();

        doAjaxCall('app~commande:index', '/commande/index', 'partial=1', '#compte_data', '');

        return false;
});

$('#compte_data #ticket_open').live('click', function(e){
        e.stopPropagation();

        doAjaxCall('app~ticket:open', '/ticket/open', 'partial=1', '#compte_data', '');

        return false;
});

$('#compte_data #ticket_create').live('click', function(e){
        e.stopPropagation();

        var formfields = new Array('titre', 'message');

        var formdata = '';

        var selector = '';

        for (var i=0; i < formfields.length; i++)
        {
            selector = '#ticket_'+formfields[i];

            if (typeof($(selector).val()) != 'undefined')
            {
                if ($(selector).attr('type') == 'checkbox' || $(selector).attr('type') == 'radio')
                    formdata += '&ticket_'+formfields[i]+'='+( ($(selector).attr('checked')!='')?'on':'off' );
                else
                    formdata += '&ticket_'+formfields[i]+'='+escape($(selector).val());
            }
        }

        doAjaxCall('app~ticket:post', '/ticket/post', 'partial=1'+formdata, '#compte_data', "$('#compte_tickets').click()");

        return false;
});

$('#compte_data #ticket_update').live('click', function(e){
        e.stopPropagation();

        var formfields = new Array('id', 'etat', 'message');

        var formdata = '';

        var selector = '';

        for (var i=0; i < formfields.length; i++)
        {
            selector = '#ticket_'+formfields[i];

            if (typeof($(selector).val()) != 'undefined')
            {
                if ($(selector).attr('type') == 'checkbox' || $(selector).attr('type') == 'radio')
                    formdata += '&ticket_'+formfields[i]+'='+( ($(selector).attr('checked')!='')?'on':'off' );
                else
                    formdata += '&ticket_'+formfields[i]+'='+escape($(selector).val());
            }
        }

        doAjaxCall('app~ticket:post', '/ticket/post', 'partial=1'+formdata, '#compte_data', "$('#compte_tickets').click()");

        return false;
});

$('#compte_data #ticket_append').live('click', function(e){
        e.stopPropagation();

        doAjaxCall('app~ticket:append', '/ticket/append', 'partial=1&ticket_id='+$('#ticket_id').val(), '#compte_data', '');

        return false;
});

$('#compte_data .ticket_detail').live('mouseover', function(){
    $(this).css('opacity', '0.8');
    $(this).css('background-color', '#7AAA1D');
    $(this).css('cursor', 'pointer');
});

$('#compte_data .ticket_detail').live('mouseout', function(){
    $(this).css('opacity', '1');
    $(this).css('background-color', 'transparent');
    $(this).css('cursor', 'default');
});

$('#compte_data .ticket_detail').live('click', function(e){
        e.stopPropagation();

        var infos = this.id.split('_');
        var id_ticket = infos[2];

        doAjaxCall('app~ticket:index', '/ticket/index', 'partial=1&id_ticket='+id_ticket, '#compte_data', '');

        return false;
});

$('#compte_gerer #compte_ok').live('click', function(e){
        var msg = '';

        $('label>span[class="required"]').each(function(){
            var id = $(this).parent().attr('for');

            if ($('#'+id).val() == '')
                msg += '- '+$(this).parent().text().replace('*','')+"\n";
        }
        );

        if (msg != '') {
            e.stopPropagation();

                                msg = "Les champs suivants sont obligatoires :\n \n" + msg;

            alert(msg+' ');

            return false;
        }

        return true;
});

  // Fonctions relatives au panier

  // Fonctions relatives aux articles

  // -- Choix d'une dimension
  $('.dimensions').live($.browser.msie?'click':'change', function(){
    var id = this.id.substring(this.id.indexOf('dimensions')+10);
    if (this.value < 0)
      {
      $('#prix'+id).css('display','none');

      $('#acheter'+id).css('display','none');

      $('#telecharger'+id).css('display','inline');
      $('#telecharger'+id).css('visibility','visible');
      }
    else
      {
      $('#prix'+id).css('display','inline');

      $('#acheter'+id).css('display','inline');
      $('#acheter'+id).css('visibility','visible');

      $('.ajouter').each(function(){this.style.visibility='hidden'});
      $('#ajouter'+id+'_'+this.value).css('visibility','visible');

      $('#telecharger'+id).css('display','none');
      }
          });

  // -- Ajout au panier
  $('.acheter').live('click', function(){
    var id = this.id.substring(this.id.indexOf('acheter')+8);
    var choice = document.getElementsByName('dimensions_'+id);
    var dim = $('#dimensions_'+id).val();

    if (choice.length > 0 && !dim)
      {
      for (i=0; i < choice.length; i++)
        if (choice[i].checked)
          dim = choice[i].value;
      }

    if (!dim)
      {
      alert('Vous devez choisir une dimension avant !');
      return false;
      }

    $.ajax({
      type: 'GET',
      url: '/panier/add',
      data: 'id_produit='+id+'&id_dimension='+dim,
      success: function(msg){
        $.ajax({
          type: 'GET',
          url: '/panier/refresh',
          data: '',
          dataType : 'json',
          success: function(json){
            var infos = json;
            if (infos)
              {
              //alert("Article ajouté au panier");

              if (infos.articles > 0)
                {
                $('#articles').html(infos.articles+'&nbsp;'+"article(s)"+'&nbsp;=&nbsp;');
                $('#montant').html(infos.montant);
                }
              else
                {
                $('#articles').html("Panier vide");
                $('#montant').html('');
                }
              $('#article_ok').lightbox_me({
                centered: true,
                overlayCSS: {background:'black', opacity:0.3},
                onLoad: function() {
                $('#article_ok').find('input:first').focus();
                }
              });
              }
          },
          error: function(xhr, msg, exception){
            alert("(app~panier:refresh)Erreur interne au fonctionnement du site. Merci de le signaler à Isabelle CHOPLIN via le formulaire de contact.");
          }
          });
      },
      error: function(xhr, msg, exception){
        alert("(app~panier:add)Erreur interne au fonctionnement du site. Merci de le signaler à Isabelle CHOPLIN via le formulaire de contact.");
      }
      });
    });


  // -- Suppression d'un article
  $('.suppr').live('click', function(){
    var suppr = this.id.substring(this.id.indexOf('suppr')+6);
    var id = suppr.substring(0,suppr.indexOf('_'));
    var dim = suppr.substring(suppr.indexOf('_')+1);
    $.ajax({
      type: 'GET',
      url: '/panier/del',
      data: 'id_article='+id+'&id_dimension='+dim,
      success: function(msg){
        $('#prefs_form').submit();
      },
      error: function(xhr, msg, exception){
        alert("(app~panier:del)Erreur interne au fonctionnement du site. Merci de le signaler à Isabelle CHOPLIN via le formulaire de contact.");
      }
      });
  });

  // -- Clic sur le bouton Paypal

  $('#btpaypal, #btcheque').live('click', function(e){
        var moyen = this.value;
        var format = $('#conf_format').val();
        var code_promo = $('#code_promo').val();
        e.stopPropagation();
    $.ajax({
      type: 'GET',
      url: '/panier/commande',
      data: 'moyen='+moyen+'&format='+format+'&code_promo='+code_promo,
      success: function(msg){
        $('#frm_'+moyen).submit();
      }
     });
        return false;
  });


  // Fonctions relatives à la recherche

  // -- Envoi d'une recherche
  $('#recherche').bind('submit', function(){
    if ($('#texte').val() == 'Veuillez taper votre recherche' || $('#texte').val() == '')
      return false;
    else
      return true;
  });

  // -- Effacer le contenu du champ texte quand on y clique
  $('#texte').bind('click', function(){
    if (this.value == "Veuillez entrer le texte recherché")
      this.value = '';
  });

  // -- Suggestions selon le texte tapé
  $('#texte').bind('keyup', function(){
    $.ajax({
      type: 'GET',
      url: '/recherche/filter',
      data: 'texte='+this.value,
      dataType : 'json',
      success: function(json){
        var msg = '';
        json.resultats = JSON.stringify(json[1]);
        json.resultats = json.resultats.replace(/\[/g,'');
        json.resultats = json.resultats.replace(/\]/g,'');
        json.resultats = json.resultats.replace(/"/g,'');
        json.resultats = json.resultats.split(',');
        for (var i=0; i < json.resultats.length; i++)
            if (json.resultats[i].indexOf(':') >= 0)
            {
              var result = json.resultats[i].split(':');
              msg += '<li><a class="suggest" href="#"><strong>'+result[0]+'</strong>:'+result[1]+'</a></li>';
            }

        $('#suggestion').html('<ul>'+msg+'</ul>');
        $('.suggest').bind('click', function(){
              var txt = $(this).text();

              $('#texte').val(txt);
              $('#suggestion').html('');
              $('#recherche').submit();
           });
      }
     });
  });

  // -- Formulaire de contact
  $('#btcontact').live('click', function(e){
    // vérifier ?
    if ($('#contact_nom').val() == '')
      {
      alert('Vous devez remplir le nom SVP');
      e.stopPropagation();
      return false;
      }
    if ($('#contact_prenom').val() == '')
      {
      alert('Vous devez remplir le prenom SVP');
      e.stopPropagation();
      return false;
      }
    if ($('#contact_email').val() == '')
      {
      alert('Vous devez remplir l\'adresse e-mail SVP');
      e.stopPropagation();
      return false;
      }
    if ($('#contact_message').val() == '')
      {
      alert('Vous devez indiquer un message SVP');
      e.stopPropagation();
      return false;
      }

    alert("Votre demande a été prise en compte. Nous allons vous répondre le plus vite possible.");

    return true;
  });

  // -- Formulaire de newsletter
  $('#btnewsletter').live('click', function(e){
    // vérifier ?
    if ($('#newsletter_nom').val() == '' && $('input[type=radio][name="newsletter_objet"]:checked').val() == 'INSCRIPTION')
      {
      alert('Vous devez remplir le nom SVP');
      e.stopPropagation();
      return false;
      }
    if ($('#newsletter_prenom').val() == '' && $('input[type=radio][name="newsletter_objet"]:checked').val() == 'INSCRIPTION')
      {
      alert('Vous devez remplir le prenom SVP');
      e.stopPropagation();
      return false;
      }
    if ($('#newsletter_email').val() == '')
      {
      alert('Vous devez remplir l\'adresse e-mail SVP');
          e.stopPropagation();
      return false;
      }

    alert("Votre demande a été prise en compte.");

    return true;
  });

  $('#add_file').live('click', function(){
        var nb = $('.contact_file').size();

        var file = $('#contact_fichier'+nb).clone();
        file.attr('id', 'contact_fichier'+(nb+1));
        file.attr('name','contact_fichier'+(nb+1));
        file.attr('value','');

        $('#contact_fichier'+nb).after(file);
  });

  $('.faq li').live('click', function(){
    toggleFAQ(this);
  });
});
        