// Scripts used for the "similar products" module leading to the product comparison page

// Counts the number of selected products in a column.
// col: the column number
// nb: the initial number of products (should be 0 at the first call)
// val: the value of the "pids" field of the form
function nbImages(col, nb, val) {
   var i = val.indexOf("-" + col + "c");
   if (i > -1) {
      return nbImages(col, nb + 1, val.substr(i + 1));
   }
   else {
      return nb;
   }
}

// Selects a product.
// col: the column number
// pid: the product id
// WARNING: before this function is called, the variable "max" should be defined
function selectProduct(col, pid) {
   var cb = col + "c" + pid;
   var pids = document.forms["compareProductsF"].pids;
   var val = pids.value;
   if (document.getElementById(cb).checked == true) {
      if (nbImages(col, 0, val) > 3) {
         alert(max);
         document.getElementById(cb).checked = false;
      }
      else {
         var liste = val + cb + "-";
         pids.value = liste;
      }
   }
   else {
      var key = "-" + cb;
      var i = val.indexOf(key + "-");
      if (i > -1) {
         var liste = val.substr(0, i + 1) + val.substr(i + key.length + 1);
         pids.value = liste;
      }
   }
}

// Resets all checkboxes and the value of the "pids" field.
// cPid: the pid of the current product
function preUncheck(cPid) {
   for (var i = 0; i < document.forms["compareChoiceF"].elements.length; i++) {
      if ((document.forms["compareChoiceF"].elements[i].id != null) && (document.forms["compareChoiceF"].elements[i].id.length > 0)) {
         document.forms["compareChoiceF"].elements[i].checked = false;
      }
   }
   document.forms["compareProductsF"].pids.value = "-"+ cPid + "-";
}

// Compares the selected products in a column.
// col: the column number
// WARNING: before this function is called, the variable "min" should be defined
function compareProducts(col) {
   var val = document.forms["compareProductsF"].pids.value;
   var prefix = "-" + col + "c";
   var nb = nbImages(col, 0, val);
   if (nb > 0) {
      var i = nb;
      while (i > 0) {
         val = val.replace(prefix, "-");
         i = i - 1;
      }
      var pids = "-";
      i = val.substr(1).indexOf("-");
      while (i > -1){
         var pid = val.substr(1, i);
         if (pid.indexOf("c") == -1) {
            pids = pids + pid + "-";
         }
         if (val.length > (i + 1)) {
            val = val.substr(i + 1);
            i = val.substr(1).indexOf("-");
         }
         else {
            i = -1;
         }
      }
      document.forms["compareProductsF"].pids.value = pids;
      document.forms["compareProductsF"].submit();
   }
   else {
      alert(min);
   }
}
