function addToCart( id ) 
{
  if( id )
  {
    $.getJSON('availability.php',{id: id}, function(j) {
      if( j == -1 ) 
      {
          alert( "Désolé. Ce produit n'est plus disponible." );
          return;
      }
      if( !j ) 
      {
        if( window.confirm( "Ce produit n'est présentement pas en stock et sera disponible en 7 à 10 jours.\nDésirez-vous quand même l'ajouter à votre panier?" ) ) 
        {
          goCart( id );
        }
      }
      else 
      {
        goCart( id );
      }
    });
  }
  else 
  {
    goCart();
  }
}

function goCart( id ) 
{
  if( id ) 
  {
    // var loc = 'cart.php?n=1&a=' + id;
    var loc = 'index.php?t=23&n=1&a=' + id;
    if( document.getElementById( 'option_' + id ) ) 
    {
      opt = document.getElementById( 'option_' + id );
      loc += "&o=" + opt.value;
    }
  }
  else 
  {
    // loc = 'cart.php';
    loc = 'index.php?t=23';
  }
  window.location = loc;
  //openWin( loc, 'cart' );
}

function cartChange(idProduct, option, number, parentProduct) 
{
  var dest;
/*
  if( /\?/.test( window.location.href ) ) 
  {
    dest = window.location.href + "&";
  }
  else 
  {
    dest = window.location.href + "?";
  }
*/
  window.location = "index.php?t=23&a=" + idProduct + "&n=" + number + "&o=" + option + "&p=" + parentProduct;
}

function emptyCart() 
{
  if (confirm('Ceci supprimera définitivement tout les produits de votre panier?\nÊtes-vous sûr de vouloir vider le panier?'))
  {
    window.location = "index.php?t=23&empty=1";
  }
}

function remCert() 
{
  $.getJSON('remCert.php');
  document.location.reload();

}

function substitute(idSrc, idDst, option, parentProduct)
{
  //window.location = "./cart.php?s=" + idSrc + "&d=" + idDst + "&o=" + option + "&p=" + parentProduct;;
  window.location = "./index.php?t=23&idSrc=" + idSrc + "&idDst=" + idDst + "&option=" + option + "&p=" + parentProduct;
}

function openWin( location, name ) 
{
  win = window.open( location, name, 'width=710,height=500,location=no,resizable=yes,scrollbars=yes' );
  win.focus();
}

var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
function decode64(input) 
{
   var output = "";
   var chr1, chr2, chr3 = "";
   var enc1, enc2, enc3, enc4 = "";
   var i = 0;

   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
/*   var base64test = /[^A-Za-z0-9\+\/\=]/g;

   if (base64test.exec(input)) 
   {
      alert("There were invalid base64 characters in the input text.\n" +
            "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
            "Expect errors in decoding.");
   }
*/

   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
   do {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);
      if (enc3 != 64) 
      {
         output = output + String.fromCharCode(chr2);
      }

      if (enc4 != 64) 
      {
         output = output + String.fromCharCode(chr3);
      }

      chr1 = chr2 = chr3 = "";
      enc1 = enc2 = enc3 = enc4 = "";
   } while (i < input.length);
   return unescape(output);
}

function label( elementName, alert ) 
{

  if( !document.getElementById( elementName ) ) 
  {
   return 0;
  }

  if( /small/.test( document.getElementById( elementName ).className ) ) 
  {
   classnm = 'formlabel small';
  }
  else 
  {
   classnm = 'formlabel';
  }

  document.getElementById( elementName ).className=classnm  + ( alert ? ' red' : '' );
  return 1;
}

function formResult( theForm, data )
{
   switch( theForm.id )
   {
     case "login":
     if( data )
     {
       document.location.reload();
     }
     else
     {
       alert( "Nom d'usager ou mot de passe invalide.\nVeuillez essayer de nouveau." );
     }
     break;
     case "password":

       if( data )
       {
         document.location.reload();
       }
       else 
       {
         alert( "Désolé. Nous ne retrouvons aucun dossier correspondant.\nVeuillez essayer de nouveau." );
       }
       break;
     case "user":
/*
       switch( data ) {
         case "1":
           label( "labelCourriel", 1 );
           alert( "Cette adresse courriel est déjà utilisée par un membre!" );
           break;
         case "2":
           alert( "Votre compte a été modifié correctement." );
           break;
         case "3":
           alert( "Votre compte a été créé! Merci!" );
           window.location.href = "index.php";
           break;
         default:
         alert( data );
         break;
       }
*/
       if( data.indexOf("1") !== -1 )
       {
           label( "labelCourriel", 1 );
           alert( "Cette adresse courriel est déjà utilisée par un membre!" );
           break;
       }
       else if( data.indexOf("2") !== -1 )
       {
           alert( "Votre compte a été modifié correctement." );
           break;
       }
       else if( data.indexOf("3") !== -1 )
       {
           alert( "Votre compte a été créé! Merci!" );
           window.location.href = "index.php";
           break;
       }
       else
       {
         alert( data );
       }
       break;
     case "ship":
       if( data )
       {
         alert( "L'adresse de livraison a été modifiée correctement." );
         document.location.reload();
       }
       else
       {
         alert( "L'adresse n'a pu être modifiée. Veuillez recommencer." );
       }
       break;
     case "charge":
       if( data )
       {
         alert( "Merci! Nous avons porté la commande à votre compte." );
         window.location.href = "index.php";
       }
       else
       {
         alert( "Un problème est survenu lors du traitement de votre commande.\nVeuillez essayer à nouveau." );
         document.location.reload();
       }
       break;
     case "payment":
       if( data )
       {
         window.location.href=("/tlrp/achat?mosaique_" + data );
       }
       else
       {
         alert( "Un problème est survenu lors du traitement de votre commande.\nVeuillez essayer à nouveau." );
         document.location.reload();
       }
       break;
     case "interac":
       window.location.href= 'index.php?t=21';
       break;
     case "cert":
       //to do
       window.location.href= 'index.php?t=22';
       break;
     case "cc":
       if( data.indexOf("1") !== -1 )
       {
         document.location.reload();
       }
       else
       {
         alert( "Désolé. Le code entré ne correspond à aucun chèque-cadeau valide." );
       }
       break;
   }
}   

function validate( theForm )
{
  var valid = true;
  if( theForm.id == "user" )
  {
    var ac = theForm.ac.value;
  }
  else
  {
    var ac = "m";
  }  
  var lb = 0;   
  for( i=0; i < theForm.elements.length; i++ )
  {
    if( theForm.elements[i].id != "" && typeof( theForm.elements[i].id ) != "undefined" && theForm.elements[i].type != "hidden" )
    {
      lb = label( "label" + theForm.elements[i].id );
      if( !theForm.elements[i].value )
      {
        if( ac == "u" && ( theForm.elements[i].id == "Confirmation" || theForm.elements[i].id == "Mot de passe" ) )
        {
          continue;
        }
        label( "label" + theForm.elements[i].id, 1 );
        valid = false;
      }
    }
  }
  if( !valid )
  {
    if( lb )
    {
      alert( "Vous devez compléter les champs identifiés en rouge" );
    }
    else
    {
      alert( "Vous devez compléter tous les champs!" );
    }
  }
  else if( theForm.id == "user" )
  {
     if( document.getElementById( "Mot de passe" ).value != document.getElementById( "Confirmation" ).value ) {
       valid = false;
       alert( "Les mots de passe entrés ne correspondent pas." );
     }
  }
  return valid;
}

function submitForm( theForm )
{
  if( validate( theForm ) )
  {
    params = $(theForm.elements).serialize();
    $.post( theForm.action, params, function( data ) {
      formResult( theForm, data )
    });
  }
}

function logout()
{
 $.post( "login.php", { logout : "1" }, function( data ) {
   document.location.reload();
 });
}

var intervalID;
var mouseX;
var mouseY;
var IE = document.all?true:false
var el;
var prodEl;

function showProd( id, option, cart )
{
  clearInterval( intervalID );
  hideProd();
  if( cart )
  {  
    intervalID = setInterval( "showCart(" + id +")",10);
  }
  else
  {
    intervalID = setInterval( "showCard(" + id + "," + option + ")",500);
  }
}

function hideProd()
{
  if( prodEl.style.visibility != 'visible' )
  {
    clearInterval( intervalID );
  }
  prodEl.style.visibility = 'hidden'
}    

function showCard(idProduct,option)
{
  clearInterval( intervalID );
  $.post("./autoSub.php", {i: ""+idProduct+"",o: ""+option}, function(data){showProductCard(data)});
}

function showCart(idInvoice)
{
  clearInterval( intervalID );
  $.post("./autoSub.php", {cid: ""+idInvoice}, function(data){showProductCard(data)});
}

function showProductCard( content )
{
  prodEl.innerHTML=decode64( content );
  prodEl.style.visibility='visible'
  prodEl.style.left = mouseX + 20;
  if( $.browser.msie ) 
  {
    prodEl.style.top = Math.min( document.body.offsetHeight - prodEl.clientHeight -10 + document.body.scrollTop, Math.max( document.body.scrollTop, mouseY - (prodEl.clientHeight/2) ) );
  }
  else 
  {
    prodEl.style.top = Math.min( window.innerHeight - prodEl.clientHeight -10 + document.body.scrollTop, Math.max( document.body.scrollTop, mouseY - (prodEl.clientHeight/2) ) );
  }
  clearInterval( intervalID );
}  

function hoverIn(idProduct, option, idParent)
{
  hideSubstitute();
  getInfo( idProduct, option, idParent );    
}

function hoverOut() 
{
  if( el.style.visibility != 'visible' ) 
  {
    //clearInterval( intervalID );
  }
}

function getInfo(idProduct,option, idParent) 
{
  $.post("./autoSub.php", {i: ""+idProduct+"",o: ""+option+"",p: ""+idParent+""}, function(data){showSubstitute(data)});
}

function showSubstitute( content )
{
  el.innerHTML=decode64( content );
  el.style.visibility='visible'
  el.style.left=mouseX - 20;
  el.style.top=mouseY - 20; 
  //clearInterval( intervalID );
}  

function getMouseXY(ev) 
{
  if (IE) 
  { // grab the x-y pos.s if browser is IE
    mouseX = event.clientX + document.body.scrollLeft
    mouseY = event.clientY + document.body.scrollTop
  } 
  else 
  {  // grab the x-y pos.s if browser is NS
    mouseX = ev.pageX
    mouseY = ev.pageY
  }

  if( el ) 
  {
    if( el.style.visibility == 'visible' ) 
    {
      if( mouseX > parseInt( el.style.left ) + parseInt( el.clientWidth )
       || mouseX < parseInt( el.style.left )
       || mouseY > parseInt( el.style.top ) + parseInt( el.clientHeight )
       || mouseY < parseInt( el.style.top ) ) 
      {
        hideSubstitute();
      }
      //alert( parseInt( el.style.left ) + parseInt( el.width ));
    }
  }
}



function hideSubstitute() 
{
    el.style.visibility='hidden';
    //clearInterval( intervalID );
}

function initCartView() 
{
  prodEl = document.getElementById('productCard');
  if (!IE) document.captureEvents(Event.MOUSEMOVE);
  document.onmousemove = getMouseXY;
}

function initCart() 
{
  el = document.getElementById('substitution');
  prodEl = document.getElementById('productCard');
  if (!IE) document.captureEvents(Event.MOUSEMOVE);
  document.onmousemove = getMouseXY;
  updateCount();
}

function cashout() 
{
  window.opener.location.href='index.php?t=18';
  window.close();
}

function updateCount() 
{
  $.getJSON('numItems.php',{id: 1}, function(j) {
    if( j>=1 ) 
    {
      text = "(" + j + ( j > 1 ? " articles)" : " article)" );
    }
    else 
    {
      text = "";
    } 
    if( window.opener ) 
    {
      window.opener.document.getElementById( "numItems" ).innerHTML="<span>" + text + "</span>";
      if( /t=18/.test( window.opener.location.href ) ) 
      {
        window.opener.document.location.reload();
      }
    }
  })
}

function getPrice( id ) 
{
  theElm = document.getElementById('priceDiv');
  if( id )
  {
    $.get('priceCheck.php',{id: id}, function(j){
      theElm.innerHTML = decode64( j );
    })
  }
}