// quantitablesupport rev 211

function keychk(e){			// disable enter key
return ((e.which ? e.which : e.keyCode) != 13);
}

function striphtml(text){		// strip any HTML tags from text
  var i = text.indexOf('<');
  while ( i > -1 )
    {
    var j =  text.indexOf('>', i);
    if ( j > -1)						// is there a closing >
      {
      text = i == 0 ? text.substring(j + 1) : text.substring(0, i) + text.substring(j + 1);	// strip the <...>
      }
    else
      {
      return text;						// no more > so all must be done
      }
    i = text.indexOf('<');					// look for another <
    }
  return text;
}

function fiximages(text){		// fix Preview images
  if ( location.href.indexOf('PreviewHTML') == -1 ) return text;	// do nothing if not previewing
  text = text.replace(/(<img.* src=['"]?)(.*)(['"]?.*>)/g, "$1../$2$3");	// make <img src='abc..... into <img src='../abc...
  return text;
}

function formfield(fname){		// look through all forms 'till one containing field "fname"
  var df = document.forms;					// simplified version - only return object fname
  var i = df.length - 1;
  for ( var j = 0; j <= i; j++ )
    {
    var k = df[j].length - 1; 
    for ( var l = 0; l <= k; l++ )
      {
      if ( df[j].elements[l].name == (fname) ) 
        {
        return df[j].elements[l];
        }
      }
    }
  alert('Cannot find field ' + fname);  // shouldn't happen...
  return false;
}

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 = formfield('XY_' + prodref).value;
  var vals = oldval.split(',');
  vals[(cols * (col - 1)) + ( row - 1) + cols + rows + 4] = val;
  formfield('XY_' + prodref).value = vals.join(',');
  if ( showtotals )
    {
    var qtybase = (vals[0] - 0) + (vals[1] - 0) + 4;
    var qtyend = qtybase + (vals[0] * vals[1]);
    var qtytot = 0;
    for ( var I = qtybase; I < qtyend; I++ ) qtytot += (vals[I] - 0);
    if ( hidezeros && (qtytot == 0) ) qtytot = '';
    formfield('rtot_' + prodref).value = qtytot;
    }
}

function qtytable(colvar,rowvar,prodref,initvalue,excludelist){
  // write a quantity / size matrix
  if (trim(colvar) == '') colvar = ',';				// allow for 1D matrix
  if (trim(rowvar) == '') rowvar = ',';
  excludelist = excludelist.replace(/,$/, '');			// remove any trailing comma
  excludelist = excludelist.replace(/\s*([,:])\s*/g, "$1");	// despace commas and colons
  excludelist = ',' + excludelist + ',';			// mark begining and end
  var excsep = (colvar == ',') || (rowvar == ',') ? '' : ':';	// adjust exclude separator if single dimensional
  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 = (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);
    }
  initvalue = initvalue.replace(/"/g, '&#34;');				// fix any embedded " characters
  document.write('<input type=hidden 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>');

  for ( var I=1; I <= colcount; I++ ) document.write('<td class="xypcoltitle">' + fiximages(cols[I]) + '</td>');

// initvalue --> 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 + 4;
  for ( var I=1; I <= rowcount; I++ )
    {
    document.write('<tr><td class="xyprowtitle">' + fiximages(rows[I]) + '</td>');
    for ( var J=1; J <= colcount; J++ )
      {
      var thisitem = ',' + trim(striphtml(cols[J])) + excsep + trim(striphtml(rows[I])) +',';	// form ,Red:M, or ,Red,
      var disabled = excludelist.indexOf(thisitem) > -1 ? ' disabled title="This combination unavailable"' : '';
      var cellclass = excludelist.indexOf(thisitem) > -1 ? 'xypinputboxdisabled' : 'xypinputbox';
      var val = oldvals[qtybase++];
      rtot = rtot + (val - 0);
      if ( hidezeros && (val == 0) ) val = '';
      document.write('<td class="xypinputcell">'
                   + '<input type=text class="' + cellclass + '" value="' + val + '"'
                   + ' onchange="setrowcol(' + colcount + ',' + rowcount + ',' + I + ',' + J + ',\'' + prodref + '\',this.value)"'
                   + ' onKeypress="return (keychk(event));"'		// disable enter key
                   + disabled
                   + ' /></td>');
      }
    document.write('</tr>');
    }

  if ( showtotals )
    {
    if ( hidezeros && (rtot == 0) ) rtot = '';
    document.write('<tr><td class="xyptotaltitle">Total</td>');
    document.write('<td class="xyprtotalcell" colspan="' + colcount + '">');
    document.write('<input class="xyprtotal" type=text name="rtot_' + prodref + '" readonly value="' + rtot + '"'
                 + ' onKeypress="return keychk(event);"'
		 + '></td></tr>');
    }

  document.write('</table>');
}

function qtyinit(colvar,rowvar,prodref,initvalue){
  // write a quantity / size matrix
  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 = (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);
    }
  initvalue = initvalue.replace(/"/g, '&#34;');				// fix any embedded " characters
  document.write('<input type=hidden name="XY_' + prodref + '" value="' + initvalue + '">');
}

function checktotal(prodref, type, minval){
  if ( (type == 'none') || (minval == 0) ) return true;
  var oldval = formfield('XY_' + prodref).value;
  var vals = oldval.split(',');
  var qtybase = (vals[0] - 0) + (vals[1] - 0) + 4;
  var qtyend = qtybase + (vals[0] * vals[1]);
  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
       {
       alert('ERROR! Unknown retriction type: ' + type);
       }
  return false;
}

