// 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 qtytableLetters(colvar,rowvar,prodref,initvalue,excludelist){
   // write a quantity / size matrix
  if (trim(colvar) == '') colvar = ',';				// allow for 1D matrix
  if (trim(rowvar) == '') rowvar = ',';
  if (rowvar.slice(-1) != ',') {rowvar= rowvar + ','}; // adds a commer if one not there
  // document.write('<div>' + rowvar + '</div>');
  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;
  var MyCount = 0;
  var MyColCount = 7;
  // 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,"; // D Sets initial value to 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>');
  
//document.write('<table class="xyptable"><tr><td class="I_Text_Medium" style="text-align:left;" colspan="' + MyColCount + '">' + fiximages(rows[0]) + '</td></tr><tr>');
document.write('<table class="xyptable">');
//  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>');
// document.write('<tr><td class="xyprowtitle">' + fiximages(rows[I]) + '</td>');

    for ( var J=0; J <= colcount; J++ )
      {
   
	if ((MyCount/MyColCount) == parseInt(MyCount/MyColCount)){document.write ('</tr><tr>'); }; // D Added to limit line length to 8 sections
	
	if (cols[J].slice(0,1) == ":") {document.write ('</tr><tr><td class="I_Text_Medium" style="Text-align: left" colspan="' + MyColCount + '">' + fiximages(cols[J].slice(1,100)) + '</td></tr><tr>'); MyCount=0}; // Starts a new line
	if (cols[J].slice(0,1) != ":") {document.write('<td class="" style="Font-Color: Black; Width:' + (640/MyColCount) + 'px; text-align:left; border:1px none darkblue; font-size:10; spacing:0px; padding:0px;">');//David Added heding line
      var thisitem = ',' + trim(striphtml(cols[J])) + excsep + trim(striphtml(rows[I])) +',';	
      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('<input type=text id="DC-' + J + '" class="' + cellclass + '" value="' + val + '"'
                   + ' onchange="setrowcol(' + colcount + ',' + rowcount + ',' + I + ',' + J + ',\'' + prodref + '\',this.value)"'
                   + ' onKeypress="return (keychk(event));"'		// disable enter key
                   + disabled
                   + ' />&nbsp '
                   + fiximages(cols[J]) + '</td>');
MyCount = MyCount + 1;
		
     } }
    document.write('</tr>');
    }

  if ( showtotals )
    {
    if ( hidezeros && (rtot == 0) ) rtot = '';
    document.write('<tr><td class="I_Text_Medium" colspan="' + MyColCount + '">Quantity total of all cells ' );
    document.write('<span class="xyprtotalcell">');
    document.write('<input class="xyprtotal" type=text name="rtot_' + prodref + '" readonly value="' + rtot + '"'
                 + ' onKeypress="return keychk(event);"'
		 + '></span></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;
}

/***********************************************************************
*David 
* 
* David Collins 2010
************************************************************************/

function letterReset(colvar,prodref){
var cols = colvar.split(',');
var colcount = cols.length-1;
for (var j = 1; j <= colcount; j++)
{
if(cols[j].slice(0,1) != ":"){document.getElementById("DC-" + j).value=0;}
}
/*document.getElementById("addTextLength").value=f;*/
return;
}
/***********************************************************************
*David 
* Get a word brake it into bits and add them to the grid of letters
* David Collins 2010
************************************************************************/

function addWord(colvar,prodref){
var text = document.getElementById("addText").value;
text = text.replace(/'/gi, '[');
text = text.replace(/"/gi, ']');
var cols = colvar.split(',');
var rows = "dd";
var colcount = cols.length-1;
var val;
var letter;
for (var f = 0 ; f <= text.length+1; f++ )
{
letter = text.slice(f,f+1);
for (var j = 1; j <= colcount; j++)
	{
	if ( letter == "," && cols[j]=="comma" )
		{
		val = document.getElementById("DC-" + j).value;
		val = parseInt(val) + 1;
		if(isNaN(val)){val = 1;};
		document.getElementById("DC-" + j).value=val;
		document.getElementById("DC-" + j).onchange();
		
		};
	if ( letter == "]" && cols[j]=="''speach")
		{
		val = document.getElementById("DC-" + j).value;
		val = parseInt(val) + 1;
		if(isNaN(val)){val = 1;};
		document.getElementById("DC-" + j).value=val;
		document.getElementById("DC-" + j).onchange();
		};
	if ( letter == "[" && cols[j]=="'apos")
		{
		val = document.getElementById("DC-" + j).value;
		val = parseInt(val) + 1;
		if(isNaN(val)){val = 1;};
		document.getElementById("DC-" + j).value=val;
		document.getElementById("DC-" + j).onchange();
		};
	if ( cols[j].slice(0,1) == letter)
		{
		val = document.getElementById("DC-" + j).value;
		val = parseInt(val) + 1;
		if(isNaN(val)){val = 1;};
		document.getElementById("DC-" + j).value=val;		
		document.getElementById("DC-" + j).onchange(); 
		letter = " ";
		};
	
	};
	
};
document.getElementById("addText").value = "";
/*document.getElementById("addText").value=f;*/
return;
}