
var SITE_SCRIPT_URL = '/scripts';

var nlTimerid = null;
var listeTimerid = null;
var actusTimerid = null;

var produitsNb = 0;
var produitsStart = 0;
var produitsLimit = 8;
var produitsHeight = 374;

var compareItems = '';
var compareNb = 0;
var compareMax = 4;

var basketSize = 0;
var basketTotal = 0;


function completeDocument(bsize, btot) {
  //init
  echoParasites();
  if (bsize) basketSize = bsize;
  if (btot) basketTotal = btot;
  preloadImages('/images/menu-sel-bg.jpg', '/images/liste-panier-sel.png', '/images/liste-comparer-sel.png', '/images/comparer-sel.png', '/images/paiement-sel.png', '/images/commander-sel.png', '/images/cancel-sel.png', '/images/panier-bg-short-sel.png', '/images/devis-bg-short-sel.png');
  $('#compte').append('<div id="nlmes"></div>');
  produitsNb = $('div.liste div.item').length;
  // liste
  if ($('div.liste').length) {
    $('div.liste').append('<div id="listenav"></div><div id="listemes"></div>');
    $('#liste').html('<div>'+$('#liste').html()+'</div>');
    $('#liste div img:last').load(function(){
      if ($('#liste div').height() > $('#liste').height()) {
	$('#liste').height($('#liste div').height());
        $('#footer').css('top', ($('#liste div').height() + 210)+'px');
     }
    });
    $('#liste div:first').css({top: '0', left: '0', position: 'absolute'});
//    listeNavSet();
    $('#comparer').hover(menuOver, menuOut);
    $('#comparer a').click(listeCompare);
  }
  // compare and panier
  if ($('div.content table').length)
    $('div.content').append('<div id="listemes"></div>');
  // fiche
  if ($('div.fiche').length) {
    $('div.fiche').append('<div id="listemes" class="fichemes"></div>');
    $('div.thumbs img').wrapAll('<div></div>');
    $('body').append('<div class="zoom"></div>');
    $("div.zoom").css({opacity: '0'});
    $('div.fiche div.panier').click(listeItemBuy);
    $('div.fiche div.devis').click(devisForm);
    for (i = 1; i < images.length; i ++)
      preloadImages(mediums[i], images[i]);
    $('div.fiche div.thumbs img').mouseover(mediumShow);
    $('div.fiche div.thumbs img').click(imageShow);
    $('div.fiche img.medium').click(imageShow);
    $('div.fiche div.panier, div.fiche div.devis').hover(menuOver, menuOut);
    var i = 395 + $('div.description div').height();
    var j = 88 * Math.ceil($('div.thumbs img').length / 3) + 335 + 156;
    if (i < j) i = j;
    if (i > 566) $('#footer').css('top', i+'px');
    i = $('div.description div').height() + 395 - 156;
    if (i > 418) $('div.fiche').height(i);
  }
  resizeElements();
  // actions
  $('#butempty').click(panierEmpty);
  $('#butdevis').click(devisForm);
  $('#panier').click(function(){ window.location.href = '/panier.php'; });
  $('#butvalid, #butcancel, #butvalid2, #butcancel2, #butvalid3, #butvalid4, #butvalid5, #menus h2, #menus h3, #butempty, #abutvalid, #abutvalid2, #abutcancel, #butdevis, #codevalid').hover(menuOver, menuOut);
  $('#compte td.connect').click(userConnect2);
  $('#compte p.but').click(nlAdd);
  $('table.pan, table.com').hover(listeItemOver, listeItemOut);
  $('table.pan').click(listeItemBuy);
  $('table.com').click(listeItemCompare);
  $('div.content table.panier select').change(panierSet);
  $('div.content table.panier #butvalid').click(gotoCommande);
  $('div.content table.panier #codevalid').click(addCodePromo);
  $('div.content table.codepromo input').keypress(function(e){
    if (e.which == 13)
      addCodePromo();
  });
  $('#step01 a.sendpass, div.client a.sendpass').click(userSendPass);
  $('a.asendpass').click(affilieSendPass);
  $('#step01 a.register, #aplus').click(userRegisterForm);
  $('#step01 a.connect, div.client a.connect').click(userConnect);
  $('a.aconnect').click(affilieConnect);
  $('#step02 a.cancel, #step02 a.acancel').click(userRegisterCancel);
  $('#step02 a.validate').click(userRegisterCheck);
  $('#step1 a.cancel').click(function(){ window.location.href = '/panier.php'; });
  $('#step1 a.validate').click(userAddressCheck);
  $('#step1 a.clivalid').click(userEdit);
  $('div.zoom').click(imageHide);
  $('#butvalid4 a, #butvalid5 a').click(commandeValidate);
  $(window).load(resizeElements);
  $('#actus').hover(actusShow, actusHide);
  $('#abutvalid').click(affilieEdit);
  $('#abutvalid2').click(affilieAddCheck);
  $('#contact #butvalid a').click(sendMessage);
  $('#orders a.incident').click(incidentRegister);
}

function echoParasites() {
  $('.lab_mesures').prepend('Mesures : ');
  $('.lab_dimext').prepend('Dimensions externes : ');
  $('.lab_dimint').prepend('Dimensions internes : ');
  $('.lab_hautmin').prepend('Hauteur minimum des cloisons : ');
  $('.lab_hautmax').prepend('Hauteur maximum des cloisons : ');
  $('.lab_dep').prepend('Dépassement du toit / façade : ');
  $('.lab_nbp').prepend('Nombre de pièces : ');
  $('.lab_pe').prepend("Porte d'entrée : ");
  $('.lab_pi').prepend('Portes internes : ');
  $('.lab_fen').prepend('Fenêtres : ');
  $('.lab_parois').prepend('Parois : ');
  $('.lab_plan').prepend('Plancher : ');
  $('.lab_toit').prepend('Toit : ');
  $('.lab_toitraiter').prepend('Surface du toit à traiter : ');
  $('.lab_tuiles').prepend('Tuiles : ');
  $('.lab_sejour').prepend('Séjour : ');
  $('.lab_chambres').prepend('Chambres : ');
  $('.lab_wc').prepend('WC : ');
  $('.lab_montage').prepend('Montage : ');
  $('.lab_surface').prepend('Surface : ');
  $('.lab_madrier').prepend('Madrier : ');
  $('.lab_mcarre').append(' m²');
  $('.lab_panier').append(' panier');
}

function resizeElements() {
  if ($('#actus').length) {
    if (actusTimerid) clearTimeout(actusTimerid);
    actusTimerid = setTimeout('_actusHide()', 3000);
  }
  // compare and panier
  if (!$('#standard').length && $('div.content table').length && 
	($('div.content table').height() + 70 > $('div.content').height())) {
    $('div.content').height($('div.content table').height() + 70);
    var top = parseInt($('div.content').css('top').replace('px', ''));
    if ($('div.content table.comparer').length)
      $('#listemes').css('top', ($('div.content table').height() + 60)+'px');
    $('#footer').css({top: (top + $('div.content table').height() + 65)+'px', display: 'block'});
    return false;
  }
  if ($('div.client table').length && ($('div.client table').height() + 110 > $('div.client').height())) {
    $('div.client').height($('div.client table').height() + 110);
    var top = parseInt($('div.client').css('top').replace('px', ''));
    $('#footer').css({top: (top + $('div.client table').height() + 130)+'px', display: 'block'});
    return false;
  }
  if ($('#step2').length && ($('#step2 table').height() + 90 > $('div.form').height())) {
    $('div.form').height($('#step2 table').height() + 90);
    var top = parseInt($('div.form').css('top').replace('px', ''));
    $('#footer').css({top: (top + $('#step2 table').height() + 100)+'px', display: 'block'});
    return false;
  }
  if (!$('#standard').length || ($('#standard').height() + 50 <= $('div.content').height())) {
    $('#footer').css({display: 'block'});
    return false;
  }
  $('div.content').height($('#standard').height() + 50);
  var top = parseInt($('div.content').css('top').replace('px', ''));
  $('#footer').css({top: (top + $('#standard').height() + 70)+'px', display: 'block'});
}

function preloadImages() {
  var d=document;
  if(d.images){
    if (!d.MM_p) d.MM_p = new Array();
    var i, j = d.MM_p.length, a = preloadImages.arguments;
    for(i = 0; i < a.length; i ++)
      if (a[i].indexOf("#") != 0) {
	d.MM_p[j] = new Image;
	d.MM_p[j++].src = a[i];
      }
  }
}

function menuOver() {
  if (!$(this).hasClass('selected')) {
    if ($(this).hasClass('devis'))
      $(this).addClass('devisel');
    else
      $(this).addClass('sel');
  }
}

function menuOut() {
  if (!$(this).hasClass('selected')) {
    if ($(this).hasClass('devis'))
      $(this).removeClass('devisel');
    else
      $(this).removeClass('sel');
  }
}

function nlAdd() {
  var f = document.nlform;
  if (!f.nl_email.value || (f.nl_email.value == 'votre email'))
    return cnlAlert('adresse email manquante.');
  var e = emailIsValid(f.nl_email.value);
  if (e == null)
    return cnlAlert('adresse email incorrecte.');
  cnlAlert('patientez...');
  $('#compte p.but').unbind();
  $('#compte p.but').click(function(){return false;});
  $.ajax({
    type: "POST",
    url: SITE_SCRIPT_URL+'/nl-add.php',
    data: "nl_email="+e,
    success: function(data){
      if (data == '1')
	return cnlAlert('déjà enregistré.');
      cnlAlert('inscription enregistrée.');
      f.nl_email.value = 'votre email';
      $('#compte p.but').unbind();
      $('#compte p.but').click(nlAdd);
      return false;
    }
  });
  return false;
}

function cnlAlert(mes) {
  if (!mes.match('patiente')) {
    alert(mes);
    return false;
  }
  if (nlTimerid) clearTimeout(nlTimerid);
  $('#nlmes').html(mes);
  nlTimerid = setTimeout('cnlAlertClear()', 9000);
  return false;
}

function cnlAlertClear() {
  $('#nlmes').html('');
}

function emailIsValid( email ) {
  var e = email.toLowerCase(); 
  e = e.replace( /(^\s+|\s+$)/g, '' );
  if (!e.match(/[a-z0-9\.\-]+@[a-z0-9\.\-]+\.[a-z]{2,4}/))
    return null;
  return e;
}

function listeAlert(mes) {
  if (!mes.match('patiente')) {
    alert(mes);
    return false;
  }
  if (listeTimerid) clearTimeout(listeTimerid);
  $('#listemes').html(mes);
  listeTimerid = setTimeout('listeAlertClear()', 9000);
  return false;
}

function listeAlertClear() {
  $('#listemes').html('');
}

function listeNavSet() {
  var html = '<table cellspacing="0" cellpadding="0"><tr>';
  if (produitsStart > 0)
    html += '<td><a href="/" class="listeprev"><img id="listeprev" src="/images/previous.png" /></a></td><td>&nbsp;<a href="/" class="listeprev">précédents</a>&nbsp;&nbsp;|&nbsp;&nbsp;</td>';
  html += '<td>Produits '+(produitsStart + 1)+' à ';
  if (produitsStart + produitsLimit > produitsNb)
    html += produitsNb;
  else
    html += produitsStart + produitsLimit;
  html += ' / '+produitsNb+'</td>';
  if (produitsStart + produitsLimit < produitsNb)
    html += '<td>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="/" class="listenext">suivants</a></td><td>&nbsp;<a href="/" class="listenext"><img id="listenext" src="/images/next.png" /></a></td>';
  html += '</tr></table>';
  $('#listenav').html(html);
  $('#listenav .listeprev').click(listePrev);
  $('#listenav .listenext').click(listeNext);
  $('#listenav .listeprev, #listenav .listenext').hover(listeNavOver, listeNavOut);
}

function listeNavOver() {
  $('#'+$(this).attr('class')).attr('src', $('#'+$(this).attr('class')).attr('src').replace('.png', '-sel.png'));
}

function listeNavOut() {
  $('#'+$(this).attr('class')).attr('src', $('#'+$(this).attr('class')).attr('src').replace('-sel', ''));
}

function listePrev() {
  var len = produitsHeight;
//  if (produitsStart + produitsLimit > produitsNb)
//    len = produitsHeight / 2;
  produitsStart -= produitsLimit;
  listeNavSet();
  $('#liste div:first').animate({top: '+='+len+'px'}, 800, 'easeOutExpo');
  return false;
}

function listeNext() {
  var len = produitsHeight;
//  if (produitsStart + produitsLimit > produitsNb)
//    len = produitsHeight / 2;
  produitsStart += produitsLimit;
  listeNavSet();
  $('#liste div:first').animate({top: '-='+len+'px'}, 800, 'easeOutExpo');
  return false;
}

function listeItemOver() {
  if ($(this).hasClass('selected'))
    return false;
  var id = $(this).attr('id');
  if ($('#'+id+' img').length)
    $('#'+id+' img').attr('src', 
  	$('#'+id+' img').attr('src').replace('.png', '-sel.png')
    );
  if ($('#'+id+' td').length)
    $('#'+id+' td').addClass('sel');
}

function _listeItemOut(obj) {
  if (obj.hasClass('selected'))
    return false;
  var id = obj.attr('id');
  if ($('#'+id+' img').length)
    $('#'+id+' img').attr('src', 
  	$('#'+id+' img').attr('src').replace('-sel', '')
    );
  if ($('#'+id+' td').length)
    $('#'+id+' td').removeClass('sel');
}

function listeItemOut() {
  _listeItemOut($(this));
}

function listeItemCompare() {
  if ($(this).hasClass('selected'))
    return listeItemCompareRemove($(this));
  return listeItemCompareAdd($(this));
}

function listeItemCompareAdd(obj) {
  if (compareNb == compareMax) {
    listeAlert('Vous ne pouvez pas comparer plus de '+compareMax+' produits simultanément.');
    return false;
  }
  obj.addClass('selected');
  if (!compareNb)
    compareItems = obj.attr('id').substr(3);
  else
    compareItems += 'A'+obj.attr('id').substr(3);
  compareNb ++;
  return false;
}

function listeItemCompareRemove(obj) {
  obj.removeClass('selected');
  _listeItemOut(obj);
  compareItems = compareItems.replace(obj.attr('id').substr(3), '');
  compareItems = compareItems.replace('AA', 'A');
  compareItems = compareItems.replace(/A$/, '');
  compareItems = compareItems.replace(/^A/, '');
  compareNb --;
  return false;
}

function listeCompare() {
  if (!compareNb) {
    listeAlert("Vous devez d'abord sélectionner les produits que vous souhaitez comparer.");
    return false;
  }
  $(this).attr('href', $(this).attr('href') + '?ids=' + compareItems);
  return true;
}

function listeItemBuy() {
  if ($(this).hasClass('addonly'))
    return listeItemBuyAdd($(this));
  if ($(this).hasClass('selected'))
    return listeItemBuyRemove($(this));
  return listeItemBuyAdd($(this));
}

function listeItemBuyAdd(obj) {
  obj.addClass('selected');
  obj.unbind();
  obj.click(function(){return false;});
  var id = obj.attr('id').substr(3);
  $.ajax({
    type: "POST",
    url: SITE_SCRIPT_URL+'/panier-add.php',
    data: "variante="+id,
    success: function(data){
      var arr = data.split('#');
      if (parseInt(arr[0]) > basketSize) {
	listeAlert('Produit ajouté à votre panier.');
//	basketRefresh( parseInt(arr[0]), arr[1] );
	window.location.href = '/panier.php';
	return false;
      }
      else
	listeAlert('Produit déjà présent dans votre panier.');
      obj.unbind();
      obj.click(listeItemBuy);
      return false;
    }
  });
  return false;
}

function listeItemBuyRemove(obj) {
  obj.removeClass('selected');
  _listeItemOut(obj);
  obj.unbind();
  obj.click(function(){return false;});
  var id = obj.attr('id').substr(3);
  $.ajax({
    type: "POST",
    url: SITE_SCRIPT_URL+'/panier-del.php',
    data: "variante="+id,
    success: function(data){
      var arr = data.split('#');
      if (parseInt(arr[0]) < basketSize) {
	listeAlert('Produit retiré de votre panier.');
	basketRefresh( parseInt(arr[0]), arr[1] );
      }
      obj.unbind();
      obj.click(listeItemBuy);
      return false;
    }
  });
  return false;
}

function devisPrint() {
  $(this).addClass('selected');
  $(this).unbind();
  $(this).click(function(){return false;});
  var id = $(this).attr('id').substr(3);
  $.ajax({
    type: "POST",
    url: SITE_SCRIPT_URL+'/panier-add.php',
    data: "variante="+id,
    success: function(data){
      window.location.href = '/devis.php';
      $('div.fiche div.devis').unbind();
      $('div.fiche div.devis').click(devisPrint);
      $('div.fiche div.devis').removeClass('selected');
      return false;
    }
  });
  return false;
}

function basketRefresh(nb, tot) {
  basketSize = nb;
  basketTotal = parseFloat(tot);
  var art = 'Article';
  if (nb > 1) art += 's';
  art += ' = '+nb;
  $('#nb_articles').html(art);
  tot = tot.replace('.', ',');
  if (tot.indexOf(',') == 4)
    tot = tot.substr(0, 1)+' '+tot.substr(1);
  $('#panier_total').html('Total = '+tot+' &euro;');
}

function mediumShow() {
  var id = $(this).attr('id').substr(3);
  $('div.fiche img.medium').attr('src', mediums[parseInt(id)]);
  $('div.fiche img.medium').attr('id', 'med'+id);
}

function imageShow() {
  var id = $(this).attr('id').substr(3);
  $('div.zoom').html('<table cellspacing="0" cellpadding="0"><tr><td><img src="'+images[parseInt(id)]+'" /></td></tr></table>');
  $('div.zoom').css({opacity: '0', display: 'block'});
  $('div.zoom').animate({opacity: '1'}, 600);
  return false;
}

function imageHide() {
  $("div.zoom").css({display: 'none'});
  $("div.zoom").empty();
  return false;
}

function panierSet() {
  var act = $(this).attr('name').substr(0, 1);
  var id = $(this).attr('name').substr(1);
  var q = document.panierform[$(this).attr('name')].options[document.panierform[$(this).attr('name')].selectedIndex].value;
  if (act == 'm')
    return panierUpdateMontage(id, q);
  if ((act == 'u') || (act == 'o'))
    return panierUpdate(id, q);
  return panierAdd(id, q);
}

function panierUpdate(id, q) {
  var option = '';
  listeAlert('Veuillez patienter...');
  $.ajax({
    type: "POST",
    url: SITE_SCRIPT_URL+'/panier-update.php',
    data: "variante="+id+'&q='+q,
    success: function(data){
      window.location.href = window.location.href;
      return false;
    }
  });
  return false;
}

function panierUpdateMontage(id, q) {
  var option = '';
  listeAlert('Veuillez patienter...');
  $.ajax({
    type: "POST",
    url: SITE_SCRIPT_URL+'/panier-update-montage.php',
    data: "variante="+id+'&q='+q,
    success: function(data){
      window.location.href = window.location.href;
      return false;
    }
  });
  return false;
}

function panierAdd(id, q) {
  listeAlert('Veuillez patienter...');
  $.ajax({
    type: "POST",
    url: SITE_SCRIPT_URL+'/panier-add.php',
    data: "variante="+id+'&q='+q,
    success: function(data){
      window.location.href = window.location.href;
      return false;
    }
  });
  return false;
}

function panierEmpty() {
  listeAlert('Veuillez patienter...');
  $(this).unbind();
  $(this).click(function(){return false;});
  $.ajax({
    type: "GET",
    url: SITE_SCRIPT_URL+'/panier-empty.php',
    success: function(data){
      window.location.href = window.location.href;
      return false;
    }
  });
  return false;
}

function _sendPass(obj, form, func) {
  var f = document.logform;
  f[form+'_email'].value = f[form+'_email'].value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f[form+'_email'].value) {
    listeAlert('Merci de bien vouloir indiquer votre adresse email.');
    return false;
  }
  var e = emailIsValid(f[form+'_email'].value);
  if (e == null) {
    listeAlert("L'adresse email indiquée est incorrecte.");
    return false;
  }
  f[form+'_email'].value = e;
  obj.unbind();
  obj.click(function(){return false;});
  listeAlert('Veuillez patienter...');
  $.ajax({
    type: "POST",
    url: SITE_SCRIPT_URL+'/'+form+'-passe.php',
    data: form+"_email="+f[form+'_email'].value,
    success: function(data){
      obj.unbind();
      obj.click(func);
      listeAlert(data);
      return false;
    }
  });
  return false;
}

function userSendPass() {
  return _sendPass($(this), 'user', userSendPass);
}

function affilieSendPass() {
  return _sendPass($(this), 'affilie', affilieSendPass);
}

function userRegisterForm() {
  $('#step01, #step02').animate({top: '-=418px'}, 800, 'easeOutExpo');
  return false;
}

function _userConnect(obj, alertfunc, redir) {
  var f = document.logform;
  f.user_email.value = f.user_email.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.user_email.value) {
    alertfunc('Adresse email manquante.');
    return false;
  }
  var e = emailIsValid(f.user_email.value);
  if (e == null) {
    alertfunc("Adresse email incorrecte.");
    return false;
  }
  f.user_email.value = e;
  f.user_passe.value = f.user_passe.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.user_passe.value) {
    alertfunc('Mot de passe manquant.');
    return false;
  }
  obj.unbind();
  obj.click(function(){return false;});
  var obj2 = obj;
  alertfunc('Veuillez patienter...');
  $.ajax({
    type: "POST",
    url: SITE_SCRIPT_URL+'/user-login.php',
    data: "user_email="+f.user_email.value+'&user_passe='+f.user_passe.value,
    success: function(data){
      if (!data || (data == '0')) {
	if (redir) window.location.href = '/client.php';
	else window.location.href = window.location.href;
	return false;
      }
      obj2.unbind();
      obj2.click(userConnect);
      if (data == '1')
	alertfunc('Adresse email inconnue.');
      else if (data == '2')
	alertfunc('Mot de passe incorrect.');
      else if (data == '3')
	alertfunc('Reconnectez-vous SVP.');
      return false;
    }
  });
  return false;
}

function userConnect() {
  return _userConnect($(this), listeAlert, false);
}

function userConnect2() {
  if (document.logform.user_email.value == 'votre email')
    document.logform.user_email.value = '';
  return _userConnect($(this), cnlAlert, true);
}

function affilieConnect() {
  var f = document.logform;
  f.affilie_email.value = f.affilie_email.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.affilie_email.value) {
    listeAlert('Adresse email manquante.');
    return false;
  }
  var e = emailIsValid(f.affilie_email.value);
  if (e == null) {
    listeAlert("Adresse email incorrecte.");
    return false;
  }
  f.affilie_email.value = e;
  f.affilie_passe.value = f.affilie_passe.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.affilie_passe.value) {
    listeAlert('Mot de passe manquant.');
    return false;
  }
  $(this).unbind();
  $(this).click(function(){return false;});
  var obj = $(this);
  listeAlert('Veuillez patienter...');
  $.ajax({
    type: "POST",
    url: SITE_SCRIPT_URL+'/affilie-login.php',
    data: "affilie_email="+f.affilie_email.value+'&affilie_passe='+f.affilie_passe.value,
    success: function(data){
      if (!data || (data == '0')) {
	window.location.reload();
	return false;
      }
      obj.unbind();
      obj.click(affilieConnect);
      if (data == '1')
	listeAlert('Adresse email inconnue.');
      else if (data == '2')
	listeAlert('Mot de passe incorrect.');
      else if (data == '3')
	listeAlert('Reconnectez-vous SVP.');
      return false;
    }
  });
  return false;
}

function userRegisterCancel() {
  $('#step01, #step02').animate({top: '+=418px'}, 800, 'easeOutExpo');
  return false;
}

function userCheck(fname) {
  var f = document[fname];
  if (!f.civil.selectedIndex) {
    listeAlert('Merci de bien vouloir indiquer votre civilité.');
    return false;
  }
  if (f.prenom.value) f.prenom.value = f.prenom.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.prenom.value) {
    listeAlert('Merci de bien vouloir indiquer votre prénom.');
    return false;
  }
  if (f.nom.value) f.nom.value = f.nom.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.nom.value) {
    listeAlert('Merci de bien vouloir indiquer votre nom.');
    return false;
  }
  if (f.adresse_livraison.value) f.adresse_livraison.value = f.adresse_livraison.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.adresse_livraison.value) {
    listeAlert('Merci de bien vouloir indiquer l\'adresse de livraison.');
    return false;
  }
  if (f.cp_livraison.value) f.cp_livraison.value = f.cp_livraison.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.cp_livraison.value) {
    listeAlert('Merci de bien vouloir indiquer votre code postal.');
    return false;
  }
  if (f.ville_livraison.value) f.ville_livraison.value = f.ville_livraison.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.ville_livraison.value) {
    listeAlert('Merci de bien vouloir indiquer votre ville.');
    return false;
  }
  if (f.tel.value) f.tel.value = f.tel.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.tel.value) {
    listeAlert('Merci de bien vouloir indiquer votre téléphone.');
    return false;
  }
  if (f.mobile.value) f.mobile.value = f.mobile.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.mobile.value) {
    listeAlert('Merci de bien vouloir indiquer votre mobile pour la livraison.');
    return false;
  }
  if (f.email.value) f.email.value = f.email.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.email.value) {
    listeAlert('Merci de bien vouloir indiquer votre adresse email.');
    return false;
  }
  var e = emailIsValid(f.email.value);
  if (e == null) {
    listeAlert('Email incorrect. Merci de bien vouloir corriger.');
    return false;
  }
  f.email.value = e;
  e2 = emailIsValid(f.confirme.value);
  if (e != e2) {
    listeAlert('Les deux emails sont différents. Merci de corriger.');
    return false;
  }
  return true;
}

function userCheck2(fname) {
  var f = document[fname];
  f.passe.value = f.passe.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.passe.value) {
    listeAlert('Merci de bien vouloir choisir un mot de passe (6 caractères minimum).');
    return false;
  }
  if (f.passe.value.length < 6) {
    listeAlert('Le mot de passe doit comporter 6 caractères au minimum.');
    return false;
  }
  f.confirmp.value = f.confirmp.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (f.passe.value != f.confirmp.value) {
    listeAlert('Les deux mots de passe sont différents. Merci de corriger.');
    return false;
  }
  return true;
}

function userRegisterCheck() {
  var f = document.regform;
  if (!userCheck('regform'))
    return false;
  if (!userCheck2('regform'))
    return false;
  if (!f.cgv.checked) {
    listeAlert('Merci de bien vouloir lire et accepter les conditions générales.');
    return false;
  }
  var obj = $(this);
  $(this).unbind();
  $(this).click(function(){return false;});
  listeAlert('Veuillez patienter...');
  $.ajax({
    type: "POST",
    url: SITE_SCRIPT_URL+'/user-check.php',
    data: "email="+f.email.value,
    success: function(data){
      if (data == '0')
	return userRegister();
      listeAlert('Un utilisateur avec la même adresse email existe déjà.');
      obj.unbind();
      obj.click(userRegisterCheck);
      return false;
    }
  });
  return false;
}

function userRegister() {
  var f = document.regform;
  $.ajax({
    type: "POST",
    url: SITE_SCRIPT_URL+'/user-edit.php',
    data: "civil="+f.civil.options[f.civil.selectedIndex].value+'&prenom='+f.prenom.value+'&nom='+
	f.nom.value+'&societe='+f.societe.value+'&adresse='+f.adresse.value+'&cp='+f.cp.value+'&ville='+
	f.ville.value+'&pays='+f.pays.selectedIndex+'&tel='+f.tel.value+'&mobile='+f.mobile.value+'&email='+
	f.email.value+'&passe='+f.passe.value+'&adresse_livraison='+f.adresse_livraison.value+
	'&cp_livraison='+f.cp_livraison.value+'&ville_livraison='+f.ville_livraison.value+
	'&pays_livraison='+f.pays_livraison.selectedIndex,
    success: function(data){
      window.location.href = '/commander.php?register=1&tot='+f.tot.value;
      return false;
    }
  });
  return false;
}

function userAddressCheck() {
  var f = document.checkform;
  if (!userCheck('checkform'))
    return false;
  $(this).unbind();
  $(this).click(function(){return false;});
  listeAlert('Veuillez patienter...');
  $.ajax({
    type: "POST",
    url: SITE_SCRIPT_URL+'/user-edit.php',
    data: "mode=partiel&id="+f.id.value+"&civil="+f.civil.options[f.civil.selectedIndex].value+
	'&prenom='+f.prenom.value+'&nom='+f.nom.value+'&societe='+f.societe.value+'&adresse='+f.adresse.value+
	'&cp='+f.cp.value+'&ville='+f.ville.value+'&pays='+f.pays.selectedIndex+'&tel='+f.tel.value+
	'&mobile='+f.mobile.value+'&email='+f.email.value+'&adresse_livraison='+f.adresse_livraison.value+
	'&cp_livraison='+f.cp_livraison.value+'&ville_livraison='+f.ville_livraison.value+
	'&pays_livraison='+f.pays_livraison.selectedIndex,
    success: function(data){
      window.location.href = '/commander.php?step=2&tot='+f.tot.value+'&remarques='+f.remarques_livraison.value;
      return false;
    }
  });
  return false;
}

function userEdit() {
  var f = document.editform;
  if (!userCheck('editform'))
    return false;
  if (!userCheck2('editform'))
    return false;
  var obj = $(this);
  $(this).unbind();
  $(this).click(function(){return false;});
  listeAlert('Veuillez patienter...');
  $.ajax({
    type: "POST",
    url: SITE_SCRIPT_URL+'/user-edit.php',
    data: "mode=strict&id="+f.id.value+"&civil="+f.civil.options[f.civil.selectedIndex].value+'&prenom='+
	f.prenom.value+'&nom='+f.nom.value+'&societe='+f.societe.value+'&adresse='+f.adresse.value+'&cp='+
	f.cp.value+'&ville='+f.ville.value+'&pays='+f.pays.selectedIndex+'&tel='+f.tel.value+'&mobile='+
	f.mobile.value+'&email='+f.email.value+'&passe='+f.passe.value+'&adresse_livraison='+
	f.adresse_livraison.value+'&cp_livraison='+f.cp_livraison.value+'&ville_livraison='+f.ville_livraison.value+
	'&pays_livraison='+f.pays_livraison.selectedIndex,
    success: function(data){
      window.location.href = '/client.php';
      return false;
    }
  });
  return false;
}

function affilieCheck(fname) {
  var f = document[fname];
  if (f.nom.value) f.nom.value = f.nom.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.nom.value) {
    listeAlert('Merci de bien vouloir indiquer le nom de votre société.');
    return false;
  }
  if (f.contact.value) f.contact.value = f.contact.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.contact.value) {
    listeAlert('Merci de bien vouloir indiquer vos prénom et nom.');
    return false;
  }
  if (f.adresse.value) f.adresse.value = f.adresse.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.adresse.value) {
    listeAlert('Merci de bien vouloir indiquer votre adresse.');
    return false;
  }
  if (f.tel.value) f.tel.value = f.tel.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.tel.value) {
    listeAlert('Merci de bien vouloir indiquer votre téléphone.');
    return false;
  }
  if (!f.passe.value) {
    listeAlert('Merci de bien vouloir indiquer votre mot de passe.');
    return false;
  }
  if (f.email.value) f.email.value = f.email.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.email.value) {
    listeAlert('Merci de bien vouloir indiquer votre adresse email.');
    return false;
  }
  var e = emailIsValid(f.email.value);
  if (e == null) {
    listeAlert('Email incorrect. Merci de bien vouloir corriger.');
    return false;
  }
  f.email.value = e;
  sites = f.sites.value.split("\n");
  var ss = ""; var sep = "";
  for (i = 0; i < sites.length; i ++) {
    var s = siteIsValid( sites[i] );
    if (s == null) {
      listeAlert('Le site ' + sites[i] + ' est incorrect. Merci de corriger.');
      return false;
    }
    ss += sep + s;
    sep = "\n";
  }
  f.sites.value = ss;
  return true;
}

function affilieAddCheck() {
  var f = document.regform;
  if (!affilieCheck('regform'))
    return false;
  if (!f.cgv.checked) {
    listeAlert('Merci de bien vouloir lire et accepter les conditions générales d\'affiliation.');
    return false;
  }
  var obj = $(this);
  $(this).unbind();
  $(this).click(function(){return false;});
  listeAlert('Veuillez patienter...');
  $.ajax({
    type: "POST",
    url: SITE_SCRIPT_URL+'/affilie-check.php',
    data: "email="+f.email.value,
    success: function(data){
      if (data == '0')
	return affilieAdd();
      listeAlert('Un affilié avec la même adresse email existe déjà.');
      obj.unbind();
      obj.click(affilieAddCheck);
      return false;
    }
  });
  return false;
}

function affilieAdd() {
  var f = document.regform;
  $.ajax({
    type: "POST",
    url: SITE_SCRIPT_URL+'/affilie-edit.php',
    data: 'nom='+f.nom.value+'&contact='+f.contact.value+'&adresse='+f.adresse.value+
	'&tel='+f.tel.value+'&mob='+f.mob.value+'&fax='+f.fax.value+'&email='+
	f.email.value+'&passe='+f.passe.value+'&sites='+f.sites.value,
    success: function(data){
      window.location.href = '/affilie.php';
      return false;
    }
  });
  return false;
}
function affilieEdit() {
  var f = document.editform;
  if (!affilieCheck('editform'))
    return false;
  $(this).unbind();
  $(this).click(function(){return false;});
  listeAlert('Veuillez patienter...');
  $.ajax({
    type: "POST",
    url: SITE_SCRIPT_URL+'/affilie-edit.php',
    data: "id="+f.id.value+'&nom='+f.nom.value+'&contact='+f.contact.value+'&adresse='+f.adresse.value+
	'&tel='+f.tel.value+'&mob='+f.mob.value+'&fax='+f.fax.value+'&email='+
	f.email.value+'&passe='+f.passe.value+'&sites='+f.sites.value,
    success: function(data){
      window.location.href = '/affilie.php';
      return false;
    }
  });
  return false;
}

function siteIsValid( site ) {
  var e = site.toLowerCase();
  e = e.replace( /(^\s+|\s+$)/, '' );
  if (!e.match(/(http:\/\/)*(www\.)*[a-z0-9\.\-]+\.[a-z]{2,4}/))
    return null;
  e = e.replace(/^http:\/\//, '');
  return e;
}

function commandeValidate() {
  var paiement = $(this).attr('id').substr(1, 1);
  var id = $(this).attr('id').substr(2);
  var step = 5;
  if (paiement == 'c')
    step = 6;
  $(this).unbind();
  $(this).click(function(){return false;});
  listeAlert('Veuillez patienter...');
  $.ajax({
    type: "POST",
    url: SITE_SCRIPT_URL+'/commande-validate.php',
    data: "paiement="+paiement+"&id="+id,
    success: function(data){
      window.location.href = '/commander.php?step='+step+'&order_ref='+id;
      return false;
    }
  });
  return false;
}

function gotoCommande() {
  var tot = 0;
  if (document.panierform.totalite[1].checked) tot = 1;
  window.location.href = "/commander.php?tot="+tot;
  return false;
}

function addCodePromo() {
  listeAlert('Veuillez patienter...');
  $.ajax({
    type: "POST",
    url: SITE_SCRIPT_URL+'/panier-add-code.php',
    data: "code="+document.panierform.code_promo.value,
    success: function(data){
      window.location.href = window.location.href;
      return false;
    }
  });
  return false;
}

function actusShow() {
  if (actusTimerid) clearTimeout(actusTimerid);
  $('#actus').animate({left: '0px'}, 400);
}

function actusHide() {
  if (actusTimerid) clearTimeout(actusTimerid);
  actusTimerid = setTimeout('_actusHide()', 800);
}

function _actusHide() {
  $('#actus').animate({left: '-405px'}, 200);
}

function sendMessage() {
  var f = document.conform;
  if (f.nom.value) f.nom.value = f.nom.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.nom.value) {
    alert('Merci de bien vouloir indiquer vos nom et prénom.');
    return false;
  }
  if (f.email.value) f.email.value = f.email.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.email.value) {
    alert('Merci de bien vouloir indiquer votre adresse email.');
    return false;
  }
  var e = emailIsValid(f.email.value);
  if (e == null) {
    alert('Email incorrect. Merci de bien vouloir corriger.');
    return false;
  }
  f.email.value = e;
  if (f.tel.value) f.tel.value = f.tel.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.tel.value) {
    alert('Merci de bien vouloir indiquer un numéro de téléphone.');
    return false;
  }
  if (f.region.value) f.region.value = f.region.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.region.value) {
    alert('Merci de bien vouloir indiquer votre région.');
    return false;
  }
  if (f.message.value) f.message.value = f.message.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.message.value) {
    alert('Merci de bien vouloir rédiger votre message.');
    return false;
  }
  $(this).unbind();
  $(this).click(function(){return false;});

  $('#conform').ajaxSubmit({
    type: "POST",
    url: SITE_SCRIPT_URL+'/send-message.php',
    success: function(data){
      alert('Message envoyé !');
      window.location.href = '/';
      return false;
    }
  });
  return false;
}

function devisForm() {
  var id = 0;
  if ($(this).attr('id'))
    id = $(this).attr('id').substr(3);
  $.ajax({
    type: "GET",
    data: "variante="+id,
    url: '/templates/devis-form.php',
    success: function(data){
      $('body').append(data);
      popupShow();
      $('#cancel').click(devisCancel);
      $('#validate').click(devisEdit);
    }
  });
}

function popupShow() {
  $('#popup').css({ display: 'block' });
  w = $('#popup table:first').width();
  h = $('#popup table:first').height() + 15;
  if (h > $(window).height()) {
    $('#popup').css({ width: w+'px', height: h+'px', 
	marginLeft: '-'+Math.floor(w/2)+'px', top: '10px', left: '50%' });
    return false;
  }
  $('#popup').css({ width: w+'px', height: h+'px', marginTop: Math.floor(-h/2 + $(document).scrollTop())+'px', 
	marginLeft: '-'+Math.floor(w/2)+'px', top: '50%', left: '50%' });
  var sid = $("#popup").shadowId();
  if (sid) {
    $('#'+sid).css({ display: 'block' });  
    $('#popup').redrawShadow();
  }
  else $("#popup").dropShadow();
}

function devisCancel() {
  $('#popup').removeShadow();
  $('#popup').remove();
}

function devisEdit() {
  var f = document.myform;
  if (f.nom.value) f.nom.value = f.nom.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.nom.value) {
    alert("Merci d'indiquer vos nom et prénom.");
    return false;
  }
  if (f.adresse.value) f.adresse.value = f.adresse.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.adresse.value) {
    alert("Merci d'indiquer votre adresse.");
    return false;
  }
  if (f.cp.value) f.cp.value = f.cp.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.cp.value) {
    alert("Merci d'indiquer votre code postal.");
    return false;
  }
  if (f.ville.value) f.ville.value = f.ville.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.ville.value) {
    alert("Merci d'indiquer votre ville.");
    return false;
  }
  f.submit();
  $('#popup').removeShadow();
  $('#popup').remove();
}

function incidentRegister() {
  var f = document.myform;
  if (f.produit.options && !f.produit.selectedIndex) {
    alert("Merci de bien vouloir sélectionner le produit concerné.");
    return false;
  }
  if (!f.type.selectedIndex) {
    alert("Merci de bien vouloir indiquer le type de problème rencontré.");
    return false;
  }
  if ((f.type.selectedIndex > 2) && !f.reference.value) {
    alert("Merci de bien vouloir indiquer  la référence de la pièce (colonne POS).");
    return false;
  }
  if (!f.description.value) {
    alert("Merci de bien vouloir décrire le problème rencontré.");
    return false;
  }
  if (!f.quantite.value) {
    alert("Merci de bien vouloir indiquer la quantité de produit ou pièce concerné.");
    return false;
  }
  f.submit();
  return false;
}

