// textfieldsupport.js - V1.23 - generate table containing text entry fields
// 13-11-09 amended to add mandatory engraving capability  

// customised to limit overall number of characters - look for "maxcharsallowed" for patched lines

// START some user definable fields
var maxcharsallowed = 80;			// maximum characters allowed

var warntext = 'You must enter some engraving text!';	// warning if no text entered
var engrave = 'Add Engraving';			// text to enable engraving (must match text in Product Template)
var noengrave = 'No Engraving';			// text to disable engraving
var tablestyle = '';	// table for text input
var leftstyle  = 'font-size:12px';		// left info column
// the INPUT fields (NB width is computed) the font family should match the default Font Choice
var inputstyle = 'height: 15px; align:left; margin-left:15px; margin-bottom:5px;  font-family: Arial; font-size: 12px; color:#754d2d; text-align: center; border: solid 1px #754d2d; background-color: #ffffff;';	
var rightstyle = 'padding-left:10px; line-height:15px; font-family: Arial; font-size: 12px; color:#754d2d;';		// right info column
var countstyle = 'margin-left:15px;font-family: Arial; font-size: 12px; color:#754d2d;';	// the text count area
// END  some user definable fields

var textitems = new Array();					// we'll list all text items here

function to2digits(num){					// return 2 decimal digits string of number
  var sign = num < 0 ? '-' : '';				// determine sign
  num = Math.abs(num);
  var whole = Math.floor(num);                			// no of pounds
  var fraction = Math.round((num - whole) * 100);  		// Number of Fraction (2 decimal places)
  if ( fraction > 99 ) fraction = 99;
  var res = fraction < 10 ? "0" + fraction.toString() : fraction.toString();  // make 2 digits
  return(sign + whole.toString() + '.' + res);
}

function handleEnter (field, event, prodref) {   			// disable enter key for our text fields (maxcharsallowed modified)
  var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
  if (keyCode == 13) 
    {								// we may need field.onchange(); here (if we used an onchange routine)				
    return false;						// disable submit
    }
  if ( (keyCode >= 32) && (countallchars(prodref) >= maxcharsallowed)  ) return false; // (maxcharsallowed modified)
  return true;
}  

function countallchars(prodref){
  var chars = 0;
  var maxlines = document.getElementById('inf0' + '_' + prodref).value;
  for ( var i = 1; i <= maxlines; i++ )				// for all length entries
    {
    if ( document.getElementById('inf' + i + '_' + prodref) )
      { 
      var thisline = document.getElementById('inf' + i + '_' + prodref).value
      thisline = thisline.replace(/\s/g,'');			// remove spaces
      chars += thisline.length;
      }
    }
  return chars;
}

function displaycount(maxlines, prodref, freechars, penceperchar, engravingcharge){
  
  var charcost = '';
  var totalcost = '';
  var paidcost = 0;
  var chars = countallchars(prodref);
  engravingcharge = engravingcharge - 0;
  if ( chars > 0 )
    {
    if ( chars > freechars )
      {
      var paidchars = chars - freechars;
      var paidcost = paidchars * penceperchar / 100;
      charcost = ' (' + (chars - freechars) + ' at ' + penceperchar + 'p = £' + to2digits(paidcost) + ')';
      } 
    if ( engravingcharge > 0 ) totalcost = ' Total: £' + to2digits(paidcost + engravingcharge);
    document.getElementById('inf0_' + prodref).disabled = false;
    }
  else
    {
    document.getElementById('inf0_' + prodref).disabled = true;
    }
  document.getElementById('count-' + prodref).innerHTML = 'Characters: ' + chars + charcost + totalcost;
}

function setupfields(lengths, maxsize, overlap, prodref, freechars, penceperchar, engravingcharge){	// set up text fields
  var maxsize = maxsize - 0;					// the maximum width to show text field size at
  var overlap = overlap - 0;					// extra size (above text line size) to display 
								// (allows wide characters to be seen)
  document.write('<table style="' + tablestyle + '" cellspacing=2 cellpadding=0>');
  var numlengths = lengths.length;
  // tell scripts how many fields to expect
  if ( numlengths ) document.write('<input disabled type=hidden id="inf0' + '_' + prodref + '" name="inf0' + '_' + prodref + '" value="' + numlengths + '">'); 

  for ( var i = 0; i < numlengths; i++ )			// for all length entries
    {
    if ( lengths[i] != '' )
      { 
      var bits = lengths[i].match(/^(\d+)\s*(.*$)/);		// look for nn text
      if ( bits != null )
        {
        var thismax = bits[1] - 0;
        if ( isNaN(thismax) || (thismax < 1) )			// warn if bad number
          {
          document.write('<tr><td colspan=3><font color=red>Bad TEXT' + (i + 1) + 'LENGTH</font> ' + lengths[i] + '</td></tr>');
          }
        else
          {
          var size = thismax + overlap > maxsize ? maxsize : thismax + overlap;	// size field and allow a bit for extra wide characters
          size = size * 6;					// set to a pixel size
          document.write('<tr><td style="' + leftstyle + '">' + (bits[2] ? bits[2] : '&nbsp;') + '</td><td align=center>');
          document.write('<input style="width:' + size + 'px; ' + inputstyle + '"'
                       + ' type="text" maxlength="' + bits[1] + '" id="inf' + (i + 1) + '_' + prodref + '"' 
		       + ' name="inf' + (i + 1) + '_' + prodref + '" value=""'
                       + ' onkeypress="return handleEnter(this, event, \'' + prodref + '\')"'		// (maxcharsallowed modified)
                       + ' onkeyup="displaycount(' + numlengths + ',\'' + prodref + '\',' + freechars + ',' + penceperchar + ',' + engravingcharge + ')">');
          document.write('</td></tr>');
          }
        }
      else
        {							// warn if bad pattern
        document.write('<tr><td colspan=3><font color=red>Bad TEXT' + (i + 1) + 'LENGTH</font> ' + lengths[i] + '</td></tr>');
        }
      }
    }
  document.write('<tr><td colspan=3><p><span style="' + countstyle + '" id="count-' + prodref + '">Characters: 0</span></p></td></tr>');
  document.write('</table>');
  textitems[textitems.length] = new Array(numlengths, prodref, freechars, penceperchar, engravingcharge);	// save for Refresh onload
}

function refreshcounts(){					// refresh counts on form load (IE refresh needs this to update counts)
  for ( var i = 0; i < textitems.length; i++ )
    {
    displaycount( textitems[i][0], textitems[i][1], textitems[i][2], textitems[i][3], textitems[i][4] );	// numlengths, prodref, freechars, penceperchar, engravingcharge
    }

  // now see if any Choices set fonts
  var ifields = document.getElementsByTagName('input');		// look through all INPUT fields
  for ( var i = 0; i < ifields.length; i++ )
    {
    if ( (ifields[i].type == 'radio') )				// for RADIO buttons
      {
      if ( ifields[i].checked && (ifields[i].name.indexOf('v_') == 0) )	// but only Choice ones				// if selected
        {
        if (ifields[i].onclick) ifields[i].onclick();		// fire onclick to preset font
        }
      }
    }
}

// extra code to set the style depending on a radio choice.
function radioclicked(radio, extracode){			// see if we're changing a font
  if ( extracode != null )					// the bit within {...}
    {
    var tidycode = extracode.replace(/;\s*$/, '')		// remove any trailing ; 
    var styleitems = tidycode.split(';');			// split out the style pairs
    var rbits = radio.name.match(/_(.*)_/);			// extract the product reference	
    var ref = rbits[1];
    var ifields = document.getElementsByTagName('input');	// look through all INPUT fields
    for ( var i = 0; i < ifields.length; i++ )
      {
      var ibits = ifields[i].name.match(/^inf\d+_(.*)$/);	// for an inf1_ type field
      if ( ibits != null )					// found one
        {
        if ( ibits[1] == ref ) 					// see if it matches our product ref
          {
          for ( var j = 0; j < styleitems.length; j++ )		// pick out all style fragments
            {
            var jstyle = styleitems[j].split(':');		// split the style into name and value
	    var sitem = jstyle[0].replace(/^\s*|\s*$/, '');	// remove any leading / trailing spaces
	    var sval = jstyle[1].replace(/^\s*|\s*$/, '');	// remove any leading / trailing spaces
            // replace e.g. font-family with fontFamily
            var styletype = sitem.replace(/-\w/g, function(s){return s.substring(1).toUpperCase()});
            styleval = '="' + sval + '"';			// replace e.g. arial with ="arial"
            eval('ifields[i].style.' + styletype + styleval);	// set the style via ifields[i].style.fontFamily="arial"
            }
          }
        }
      }
    }
 }
  
function selectchanged(sel){					// select has changed
  if ( ! sel.options[sel.selectedIndex].onclick ) return;	// no embedded style so exit	
  var val = sel.options[sel.selectedIndex].onclick();		// the value (hidden in onclick)
  if (val) radioclicked(sel, val);				// see if font change required
}

function showengraving(prodref, button){				// Show / Hide the display area
  if (button.value == engrave)
    {
    document.getElementById('eng_' + prodref).style.display = 'block';
    document.getElementById('eng_' + prodref).style.visibility = 'visible';
    button.value = noengrave;
    document.getElementById('inf0_' + prodref).disabled = ( countallchars(prodref) == 0 ) ;
    }
  else
    {
    document.getElementById('eng_' + prodref).style.display = 'none';
    document.getElementById('eng_' + prodref).style.visibility = 'hidden';
    button.value = engrave;
    document.getElementById('inf0_' + prodref).disabled = true;
    }
}

function checkengraving(prodref){				// make sure some text has been entered - inhibit add to cart if none
  if ( document.getElementById('inf0' + '_' + prodref) )
    {
    var lengths = document.getElementById('inf0' + '_' + prodref).value;
    for ( var i=0; i<lengths; i++ )
      {
      if ( document.getElementById('inf' + (i + 1) + '_' + prodref) )
        {
        if ( document.getElementById('inf' + (i + 1) + '_' + prodref).value != '' ) return true;
        }
      }
    }
  alert(warntext);
  return false;
}

function setformcheck(prodref){					// mandatory engraving - add onsubmit handler to form
  if ( document.getElementById('inf0' + '_' + prodref) )
    {
    document.getElementById('inf0' + '_' + prodref).form.onsubmit = function() { return checkengraving(prodref); };
    }
}

function checkengraving(prodref){				// make sure some text has been entered - inhibit add to cart if none
  if ( document.getElementById('inf0' + '_' + prodref) )
    {
    var lengths = document.getElementById('inf0' + '_' + prodref).value;
    for ( var i=0; i<lengths; i++ )
      {
      if ( document.getElementById('inf' + (i + 1) + '_' + prodref) )
        {
        if ( document.getElementById('inf' + (i + 1) + '_' + prodref).value != '' ) return true;
        }
      }
    }
  alert(warntext);
  return false;
}

function setformcheck(prodref){					// mandatory engraving - add onsubmit handler to form
  if ( document.getElementById('inf0' + '_' + prodref) )
    {
    document.getElementById('inf0' + '_' + prodref).form.onsubmit = function() { return checkengraving(prodref); };
    }
}