
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');
  $('#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() + 10);
        $('#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>');
    $('body').append('<div class="zoom"></div>');
    $("div.zoom").css({opacity: '0'});
    $('div.fiche div.panier').click(listeItemBuy);
    for (i = 1; i < images.length; i ++)
      preloadImages(mediums[i], images[i]);
    $('div.fiche div.thumbs img').mouseover(mediumShow);
    $('div.fiche img.medium').click(imageShow);
    $('div.fiche div.devis').click(devisForm);
    $('div.fiche div.panier, div.fiche div.devis').hover(menuOver, menuOut);
    var i = 365 + $('div.description div').height();
    if (i < $('div.thumbs div').height() + 335 + 156)
      i = $('div.thumbs div').height() + 335 + 156;
    if (i > 566) $('#footer').css('top', i+'px');
    i = $('div.description div').height() + 365 - 156;
    if (i > 418) $('div.fiche').height(i);
  }
  resizeElements();
  // actions
  $('#butempty').click(panierEmpty);
  $('#butdevis').click(devisForm);
  $('#panier').click(function(){ window.location.href = '/carrello.php'; });
  $('#butvalid, #butcancel, #butvalid2, #butcancel2, #butvalid3, #butvalid4, #butvalid5, #menus h2, #menus h3, #butempty, #abutvalid, #abutvalid2, #abutcancel, #butdevis').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);
  $('#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 = '/carrello.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('Misure : ');
  $('.lab_dimext').prepend('Dimensioni esterne : ');
  $('.lab_dimint').prepend('Dimensioni interne : ');
  $('.lab_hautmin').prepend('Altezza minima pareti : ');
  $('.lab_hautmax').prepend('Altezza massima pareti : ');
  $('.lab_dep').prepend('Sporgenza tetto frontale : ');
  $('.lab_nbp').prepend('Vani : ');
  $('.lab_pe').prepend("Porta d'ingresso : ");
  $('.lab_pi').prepend('Porte interne : ');
  $('.lab_fen').prepend('Finestre : ');
  $('.lab_parois').prepend('Pareti : ');
  $('.lab_plan').prepend('Pavimento : ');
  $('.lab_toit').prepend('Tetto : ');
  $('.lab_toitraiter').prepend('Superficie del tetto da trattare : ');
  $('.lab_tuiles').prepend('Tegole : ');
  $('.lab_sejour').prepend('Soggiorno : ');
  $('.lab_chambres').prepend('Camere : ');
  $('.lab_wc').prepend('WC : ');
  $('.lab_montage').prepend('Montaggio : ');
  $('.lab_surface').prepend('Superficie : ');
  $('.lab_madrier').prepend('Pareti : ');
  $('.lab_mcarre').append(' mq');
  $('.lab_panier').append(' carrello');
}

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');
    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');
    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');
    return false;
  }
  if (!$('#standard').length || ($('#standard').height() + 50 <= $('div.content').height()))
    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');
}

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'))
    $(this).addClass('sel');
}

function menuOut() {
  if (!$(this).hasClass('selected'))
    $(this).removeClass('sel');
}

function nlAdd() {
  var f = document.nlform;
  if (!f.nl_email.value || (f.nl_email.value == 'email'))
    return cnlAlert('indrizzo e-mail mancante.');
  var e = emailIsValid(f.nl_email.value);
  if (e == null)
    return cnlAlert('indrizzo e-mail sbagliato.');
  cnlAlert('Attendere...');
  $('#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('già registrato.');
      cnlAlert('iscrizione registrata.');
      f.nl_email.value = 'email';
      $('#compte p.but').unbind();
      $('#compte p.but').click(nlAdd);
      return false;
    }
  });
  return false;
}

function cnlAlert(mes) {
  if (!mes.match('Attendere')) {
    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('Attendere')) {
    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">precedenti</a>&nbsp;&nbsp;|&nbsp;&nbsp;</td>';
  html += '<td>prodotti '+(produitsStart + 1)+' a ';
  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">successivi</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('Non si possono confrontare pù da '+compareMax+' prodotti simultaneamente.');
    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("Bisogna prima selezionare i prodotti che si desidera confrontare.");
    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('Prodotto aggiunto al carrello.');
//	basketRefresh( parseInt(arr[0]), arr[1] );
	window.location.href = '/carrello.php';
	return false;
      }
      else
	listeAlert('Prodotto già presente nel carrello.');
      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('Prodotto ritirato dal carrello.');
	basketRefresh( parseInt(arr[0]), arr[1] );
      }
      obj.unbind();
      obj.click(listeItemBuy);
      return false;
    }
  });
  return false;
}

function basketRefresh(nb, tot) {
  basketSize = nb;
  basketTotal = parseFloat(tot);
  var art = 'Articoli';
  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('Totale = '+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('Attendere prego...');
  $.ajax({
    type: "POST",
    url: SITE_SCRIPT_URL+'/panier-update.php',
    data: "variante="+id+'&q='+q,
    success: function(data){
      window.location.reload();
      return false;
    }
  });
  return false;
}

function panierUpdateMontage(id, q) {
  var option = '';
  listeAlert('Attendere prego...');
  $.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('Attendere prego...');
  $.ajax({
    type: "POST",
    url: SITE_SCRIPT_URL+'/panier-add.php',
    data: "variante="+id+'&q='+q,
    success: function(data){
      window.location.reload();
      return false;
    }
  });
  return false;
}

function panierEmpty() {
  listeAlert('Attendere prego...');
  $(this).unbind();
  $(this).click(function(){return false;});
  $.ajax({
    type: "GET",
    url: SITE_SCRIPT_URL+'/panier-empty.php',
    success: function(data){
      window.location.reload();
      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('Indica indirizzo e-mail.');
    return false;
  }
  var e = emailIsValid(f[form+'_email'].value);
  if (e == null) {
    listeAlert("Email sbagliato. Si prega di correggere.");
    return false;
  }
  f[form+'_email'].value = e;
  obj.unbind();
  obj.click(function(){return false;});
  listeAlert('Attendere prego...');
  $.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('Indrizzo e-mail mancante.');
    return false;
  }
  var e = emailIsValid(f.user_email.value);
  if (e == null) {
    alertfunc("Indrizzo e-mail sbagliato.");
    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('Password mancante.');
    return false;
  }
  obj.unbind();
  obj.click(function(){return false;});
  var obj2 = obj;
  alertfunc('Attendere prego...');
  $.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 = '/clienti.php';
	else window.location.reload();
	return false;
      }
      obj2.unbind();
      obj2.click(userConnect);
      if (data == '1')
	alertfunc('Indirizzo e-mail sconosciuto.');
      else if (data == '2')
	alertfunc('Password sbagliata.');
      else if (data == '3')
	alertfunc('Riconnettersi prego.');
      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('Indrizzo e-mail mancante.');
    return false;
  }
  var e = emailIsValid(f.affilie_email.value);
  if (e == null) {
    listeAlert("Indrizzo e-mail sbagliato.");
    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('Password mancante.');
    return false;
  }
  $(this).unbind();
  $(this).click(function(){return false;});
  var obj = $(this);
  listeAlert('Attendere prego...');
  $.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('Indirizzo e-mail sconosciuto.');
      else if (data == '2')
	listeAlert('Password sbagliata.');
      else if (data == '3')
	listeAlert('Riconnettersi prego.');
      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('Indica lo stato civile.');
    return false;
  }
  if (f.prenom.value) f.prenom.value = f.prenom.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.prenom.value) {
    listeAlert('Indica il nome.');
    return false;
  }
  if (f.nom.value) f.nom.value = f.nom.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.nom.value) {
    listeAlert('Indica il cognome.');
    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('Indica l\'indirizzo di consegna.');
    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('Indica il Cap.');
    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('Indica la città.');
    return false;
  }
  if (!f.region_livraison.selectedIndex) {
    listeAlert('Indica la regione.');
    return false;
  }
  if (f.tel.value) f.tel.value = f.tel.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.tel.value) {
    listeAlert('Indica il numero di telefono.');
    return false;
  }
  if (f.mobile.value) f.mobile.value = f.mobile.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.mobile.value) {
    listeAlert('Indica il numero di cellulare per la consegna.');
    return false;
  }
  if (f.email.value) f.email.value = f.email.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.email.value) {
    listeAlert('Indica indirizzo e-mail.');
    return false;
  }
  var e = emailIsValid(f.email.value);
  if (e == null) {
    listeAlert('Email sbagliato. Si prega di correggere.');
    return false;
  }
  f.email.value = e;
  e2 = emailIsValid(f.confirme.value);
  if (e != e2) {
    listeAlert('Le due e-mail sono diverse. Si prega di correggere.');
    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('Scegli una password (minimo 6 caratteri).');
    return false;
  }
  if (f.passe.value.length < 6) {
    listeAlert('La password deve contenere minimo 6 caratteri.');
    return false;
  }
  f.confirmp.value = f.confirmp.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (f.passe.value != f.confirmp.value) {
    listeAlert('Le due password sono diverse. Si prega di correggere.');
    return false;
  }
  return true;
}

function userRegisterCheck() {
  var f = document.regform;
  if (!userCheck('regform'))
    return false;
  if (!userCheck2('regform'))
    return false;
  if (f.code_fiscal.value) f.code_fiscal.value = f.code_fiscal.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.code_fiscal.value) {
    listeAlert('Indica il codice fiscale o P. IVA.');
    return false;
  }
  if (!f.cgv.checked) {
    listeAlert('Si prega di leggere e accettare le condizioni generali.');
    return false;
  }
  var obj = $(this);
  $(this).unbind();
  $(this).click(function(){return false;});
  listeAlert('Attendere prego...');
  $.ajax({
    type: "POST",
    url: SITE_SCRIPT_URL+'/user-check.php',
    data: "email="+f.email.value,
    success: function(data){
      if (data == '0')
	return userRegister();
      listeAlert('Esiste già un utilizzatore con lo stesso indirizzo e-mail.');
      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+'&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+
	'&region_livraison='+f.region_livraison.value+'&region='+f.region.value+
	'&code_fiscal='+f.code_fiscal.value,
    success: function(data){
      window.location.href = '/ordina.php?register=1&tot='+f.tot.value+'&retrait='+f.retrait.value;
      return false;
    }
  });
  return false;
}

function userAddressCheck() {
  var f = document.checkform;
  if (!userCheck('checkform'))
    return false;
  $(this).unbind();
  $(this).click(function(){return false;});
  listeAlert('Attendere prego...');
  $.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+'&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+'&region_livraison='+f.region_livraison.value+
	'&region='+f.region.value,
    success: function(data){
      window.location.href = '/ordina.php?step=2&tot='+f.tot.value+'&retrait='+f.retrait.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('Attendere prego...');
  $.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+'&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+'&region_livraison='+f.region_livraison.value+'&region='+f.region.value+
	'&code_fiscal='+f.code_fiscal.value,
    success: function(data){
      window.location.href = '/clienti.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('Indica il nome della società.');
    return false;
  }
  if (f.contact.value) f.contact.value = f.contact.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.contact.value) {
    listeAlert('indica il nome y cognome.');
    return false;
  }
  if (f.adresse.value) f.adresse.value = f.adresse.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.adresse.value) {
    listeAlert('Indica indirizzo.');
    return false;
  }
  if (f.tel.value) f.tel.value = f.tel.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.tel.value) {
    listeAlert('Indica il numero di telefono.');
    return false;
  }
  if (!f.passe.value) {
    listeAlert('Indica il password.');
    return false;
  }
  if (f.email.value) f.email.value = f.email.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.email.value) {
    listeAlert('Indica indirizzo email.');
    return false;
  }
  var e = emailIsValid(f.email.value);
  if (e == null) {
    listeAlert('e-mail sbagliato. Si prega di correggere.');
    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('Sito ' + sites[i] + ' sbagliato. Si prega di correggere.');
      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('Si prega di leggere e accettare le condizioni generali di affiliazione.');
    return false;
  }
  var obj = $(this);
  $(this).unbind();
  $(this).click(function(){return false;});
  listeAlert('Attendere prego...');
  $.ajax({
    type: "POST",
    url: SITE_SCRIPT_URL+'/affilie-check.php',
    data: "email="+f.email.value,
    success: function(data){
      if (data == '0')
	return affilieAdd();
      listeAlert('Esiste già un utilizzatore con lo stesso indirizzo e-mail.');
      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 = '/affiliazione.php';
      return false;
    }
  });
  return false;
}
function affilieEdit() {
  var f = document.editform;
  if (!affilieCheck('editform'))
    return false;
  $(this).unbind();
  $(this).click(function(){return false;});
  listeAlert('Attendere prego...');
  $.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 = '/affiliazione.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() {
  if (!document.cgvform.cgv.checked) {
    alert('Grazie a voi di leggere e accettare le condizioni generali di vendita.');
    return false;
  }
  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('Attendere prego...');
  $.ajax({
    type: "POST",
    url: SITE_SCRIPT_URL+'/commande-validate.php',
    data: "paiement="+paiement+"&id="+id,
    success: function(data){
      window.location.href = '/ordina.php?step='+step+'&order_ref='+id;
      return false;
    }
  });
  return false;
}

function gotoCommande() {
  var tot = 0; var retrait = 0;
  if (document.panierform.totalite) {
    if (document.panierform.totalite.value)
      tot = 1;
    else if (document.panierform.totalite[1].checked)
      tot = document.panierform.totalite[1].value;
    else
      tot = document.panierform.totalite[0].value;
  }
  if (document.panierform.retrait && 
	document.panierform.retrait.checked) retrait = 1;
  window.location.href = "/ordina.php?tot="+tot+"&retrait="+retrait;
  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('Indicare cognome e nome.');
    return false;
  }
  if (f.email.value) f.email.value = f.email.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.email.value) {
    alert('Indicare il vostro indirizzo email.');
    return false;
  }
  var e = emailIsValid(f.email.value);
  if (e == null) {
    alert('Email sbagliata. Si prega di correggere.');
    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('Indicare il vostro numero di telefono.');
    return false;
  }
  if (f.region.value) f.region.value = f.region.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.region.value) {
    alert('Indicare il vostro regione.');
    return false;
  }
  if (f.message.value) f.message.value = f.message.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.message.value) {
    alert('Scrivete il vostro messaggio.');
    return false;
  }
  $(this).unbind();
  $(this).click(function(){return false;});
  $.ajax({
    type: "POST",
    url: SITE_SCRIPT_URL+'/send-message.php',
    data: "nom="+f.nom.value+"&email="+f.email.value+"&tel="+f.tel.value+"&region="+f.region.value+"&message="+f.message.value,
    success: function(data){
      alert('Messaggio inviato !');
      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('indica il nome y cognome.');
    return false;
  }
  if (f.adresse.value) f.adresse.value = f.adresse.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.adresse.value) {
    alert('Indica l\'indirizzo.');
    return false;
  }
  if (f.cp.value) f.cp.value = f.cp.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.cp.value) {
    alert('Indica il Cap.');
    return false;
  }
  if (f.ville.value) f.ville.value = f.ville.value.replace(/^(\s+)/, '').replace(/(\s+)$/, '');
  if (!f.ville.value) {
    alert('Indica la città.');
    return false;
  }
  if (!f.region.selectedIndex) {
    alert('Indica la regione.');
    return false;
  }
  f.submit();
  $('#popup').removeShadow();
  $('#popup').remove();
}

function incidentRegister() {
  var f = document.myform;
  if (f.produit.options && !f.produit.selectedIndex) {
    alert("Grazie di cuore selezionare il prodotto in questione.");
    return false;
  }
  if (!f.type.selectedIndex) {
    alert("Grazie per aver gentilmente indicare il tipo di problema.");
    return false;
  }
  if ((f.type.selectedIndex > 2) && !f.reference.value) {
    alert("Grazie di cuore citare la parte di riferimento (colonna POS).");
    return false;
  }
  if (!f.description.value) {
    alert("Grazie di cuore descrivere il problema.");
    return false;
  }
  if (!f.quantite.value) {
    alert("Grazie di cuore indica la quantità di prodotto o di un componente in questione.");
    return false;
  }
  f.submit();
  return false;
}


