// quantitablesupport rev 206.

var showtotals = true;			// whether to show a running total on the product page

function trim(text){			// strip leading and traiing spaces
  text = text.replace(/^\s*/, '');	// trim leading spaces
  return text.replace(/\s*$/, '');	// trim trailing spaces
}

function setrowcol(cols, rows, col, row, prodref, val){
  val = parseInt(val);
  if ( isNaN(val) ) val = 0;
  if ( val < 0 ) val = 0;
  var oldval = document.getElementById('XY_' + prodref).value;
  var vals = oldval.split(',');
  vals[(cols * (col - 1)) + ( row - 1) + cols + rows + 6] = val;
  document.getElementById('XY_' + prodref).value = vals.join(',');
  if ( showtotals )
    {
    var qtybase = (vals[2] - 0) + (vals[3] - 0) + 6;
    var qtyend = qtybase + (vals[2] * vals[3]);
    var qtytot = 0;
    for ( var I = qtybase; I < qtyend; I++ ) qtytot += (vals[I] - 0);
    document.getElementById('rtot_' + prodref).value = qtytot;
    }
}

function displaywarnings(colvar,rowvar,prodref,initvalue,type,minval){
  if ( (type == '') || (type == 'none') ) return true;
  if ( type == 'range' )	// it's a range so check minval for nn-nn
    {
    if ( minval.search(/^\d+-\d+$/) == -1 )
      {
      document.write('<br/><b><font color=red>SETUP ERROR! QUANTITYLIMIT "' + minval + '" Should be number range. E.g. 2-6.</font></b>' );
      return false;
      }
    return true;
    }
  if ( (type == 'minimum') || (type == 'exact') || (type == 'modulus') )
    {
    if ( isNaN(minval) )
      {
      document.write('<br/><b><font color=red>SETUP ERROR! QUANTITYLIMIT "' + minval + '" Should be whole number.</font></b>' );
      return false;
      }
    return true;
    }
  document.write('<br/><b><font color=red>SETUP ERROR! Unknown QUANTITYLIMITTYPE: ' + type + '</font></b>' );
  return false;
}

function qtytable(colvar,rowvar,prodref,initvalue,limittype,limitval){
  if ( ! displaywarnings(colvar,rowvar,prodref,initvalue,limittype,limitval) ) return;
  // write a quantity / size matrix
  prodref = unescape((prodref.substring(1)).replace(/_/g,'%'));	// extract ref from anchor
  if (trim(colvar) == '') colvar = ',';				// allow for 1D matrix
  if (trim(rowvar) == '') rowvar = ',';
  var cols = colvar.split(',');
  var rows = rowvar.split(',');
  var colname = cols[0];
  var rowname = rows[0];
  var colcount = cols.length - 1;
  var rowcount = rows.length - 1;
  var rtot = 0;
  // setup col count, row count, col desc & sizes, row desc & sizes
  if ( initvalue == 'new' )
    {
    var initvalue = limittype + ',' + limitval + ',' + (cols.length - 1) + ',' + (rows.length - 1) + ',' + colvar  + ',' + rowvar + ',';
      for ( var I=1; I <= rowcount; I++ )
      {
      for ( var J=1; J <= colcount; J++ ) initvalue += "0,";
      }
    initvalue = initvalue.slice(0,-1);
    }
  document.write('<input type=hidden id="XY_' + prodref + '" name="XY_' + prodref + '" value="' + initvalue + '">');
  var sep = ((rowname != '' ) && (colname != '')) ? '/' : '';		// hide separator if single dimensional
  document.write('<table class="xyptable"><tr><td class="xyptopleft">' + rowname + sep + colname + '</td>');	// 1D fix

  for ( var I=1; I <= colcount; I++ ) document.write('<td class="xypcoltitle">' + cols[I] + '</td>');

// initvalue --> limittype,limitval,4,3,Size,S,M,L,XL,Colour,Red,Green,Blue,0,0,0,0,0,0,0,0,0,0,0,0
  var oldvals = initvalue.split(',');
  var qtybase = colcount + rowcount + 6;
  for ( var I=1; I <= rowcount; I++ )
    {
    document.write('<tr><td class="xyprowtitle">' + rows[I] + '</td>');
    for ( var J=1; J <= colcount; J++ )
      {
      var val = oldvals[qtybase++];
      rtot = rtot + (val - 0);
      document.write('<td class="xypinputcell">'
                   + '<input type=text'
                   + ' class="xypinputbox"'
                   + ' value="' + val + '"'
                   + ' onKeypress="return ((event.which ? event.which : event.keyCode) != \'13\')"'
                   + ' onchange="setrowcol(' + colcount + ',' + rowcount + ',' + I + ',' + J + ',\'' + prodref + '\',this.value);"'
                   + '></td>');
      }
    document.write('</tr>');
    }

  if ( showtotals )
    {
    document.write('<tr><td class="xyptotaltitle">Total</td>');
    document.write('<td class="xyprtotalcell" colspan="' + colcount + '">');
    document.write('<input class="xyprtotal" type=text id="rtot_' + prodref + '" name="rtot_' + prodref + '" readonly value="' + rtot + '"></td></tr>');
    }
  document.write('</table>');
}

function qtyinit(colvar,rowvar,prodref,initvalue,limittype,limitval){
  // write a quantity / size matrix
  prodref = unescape((prodref.substring(1)).replace(/_/g,'%'));	// extract ref from anchor
  if (trim(colvar) == '') colvar = ',';				// allow for 1D matrix
  if (trim(rowvar) == '') rowvar = ',';
  var cols = colvar.split(',');
  var rows = rowvar.split(',');
  var colname = cols[0];
  var rowname = rows[0];
  var colcount = cols.length - 1;
  var rowcount = rows.length - 1;
  if ( initvalue == 'new' )
    {
    var initvalue = limittype +',' + limitval + ',' + (cols.length - 1) + ',' + (rows.length - 1) + ',' + colvar  + ',' + rowvar + ',';
      for ( var I=1; I <= rowcount; I++ )
      {
      for ( var J=1; J <= colcount; J++ ) initvalue += "0,";
      }
    initvalue = initvalue.slice(0,-1);
    }
  document.write('<input type=hidden id="XY_' + prodref + '" name="XY_' + prodref + '" value="' + initvalue + '">');
}

function checktotal(prodref, type, minval){
  prodref = unescape((prodref.substring(1)).replace(/_/g,'%'));	// extract ref from anchor
  type = type.toLowerCase();
  if ( (type == '') || (type == 'none') ) return true;
  if ( type == 'range' )	// it's a range so check minval for nn-nn
    {
    if ( minval.search(/^\d+-\d+$/) == -1 )
      {
      alert('SETUP ERROR! QUANTITYLIMIT "' + minval + '" Should be number range. E.g. 2-6.' );
      return false;
      }
    }
  else				// single number so check minval for +ve integer
    {
    if ( isNaN(minval) )
      {
      alert('SETUP ERROR! QUANTITYLIMIT "' + minval + '" Should be whole number.' );
      return false;
      }
    }
  
  var oldval = document.getElementById('XY_' + prodref).value;
  var vals = oldval.split(',');
  var qtybase = (vals[2] - 0) + (vals[3] - 0) + 6;
  var qtyend = qtybase + (vals[2] * vals[3]);
  var qtytot = 0;
  for ( var I = qtybase; I < qtyend; I++ ) qtytot += (vals[I] - 0);
  if ( type == 'minimum' )
    {
    if ( qtytot >= minval ) return true;
    alert('Minimum quantity is ' + minval);
    }
   else if ( type == 'exact' )
     {
     if ( qtytot == minval ) return true;
     alert('You must purchase exactly ' + minval);
     }
    else if ( type == 'modulus' )
      {
      if ( (qtytot % minval) == 0 ) return true;
      alert('You must purchase in multiples of ' + minval);
      }
     else if ( type == 'range' )
       {
       var minmax = minval.split('-');
       if ( (qtytot >= minmax[0]) && (qtytot <= minmax[1]) ) return true;
       alert('You must purchase between ' + minmax[0] + ' and ' + minmax[1]);
       }
      else
        {
        alert('SETUP ERROR! Unknown QUANTITYLIMITTYPE: ' + type);
        }
  return false;
}

function setsubmitcheck(prodref, limittype,limitval){		// attach onsubmit check to product form
  xyref = 'XY_' + unescape((prodref.substring(1)).replace(/_/g,'%'));		// extract ref from anchor
  if ( document.getElementById(xyref) )
    {
    document.getElementById(xyref).form.onsubmit=function(){return checktotal(prodref, limittype,limitval);}
    }
}