// Frame image creation helper routines
// Metric / US Imperial Units Version Update 32

// start of user configurable values#
var diags = false;				// set true to display some diagnostics
var defaultwidth = 200;				// width in pixels of displayed image
var defaultheight = 200;			// height in pixels of displayed image
var wall = 'ffffff';				// default wall colour
var mountcolour = 'FFF2D7';			// default mount colour
var mountname = 'Matte White 1 8464 8';		// default mount name
var innercolour = '8F8F8F';			// default inner mount colour
var innername= 'Steel Grey 1 8593 8';		// default inner mount name
var maxcols = 10;				// number of colourway columns
var colourwidth = 30;				// pixel width of colourway cell
var colourheight = 25;				// pixel height of colourway cell
var metric = (units.toLowerCase() != 'ft');	// are we using metric / imperial
// NB - values marked ** below also need to be matched in ShoppingCart.pl
var bottomborder = 1; 				// ** set to 1 or 1.125 depending on UK / US requirements
//                       Metric   Imperial
var minarea = 	metric ? 0.01 	: 0.5		// ** minimum chargeable area
var overlap =   metric ? 5 	: 0.25		// ** mount overlap in measuring units
var mdesc= metric ? 'Mountboard':'Matboard';	// ** Descriptive name to use for Mount Board
var overdesc =  metric ? '5'    : '1/4'		// mount overlap description (for popup hints)
var sheight = 	metric ? 400 	: 10; 		// height of inital sample picture
var swidth =  	metric ? 400 	: 10;  		// width of inital sample picture
var sborder =  	metric ? 50 	: 2;  		// width of inital sample border
var minheight = metric ? 100 	: 5; 		// minmum height of picture we can frame
var minwidth =  metric ? 100 	: 5;  		// minmum width of picture we can frame
var maxheight = metric ? 3000 	: 36; 		// maximum height of picture we can frame
var maxwidth =  metric ? 3000 	: 36;  		// maximum width of picture we can frame
var cutmin =    metric ? 10 	: 1;		// mount minimum width
var cutmax =    metric ? 100 	: 40;		// mount maximum width
var maxside =   metric ? 3000 	: 118;		// maximum side length we can build
var munits = 	metric ? 'mm' 	: 'in';		// measuring units
var lunits = 	metric ? 'm' 	: 'ft';		// strip length units
var aunits = 	metric ? 'sq m' : 'sq ft'; 	// area units
var mtolength = metric ? 1000 	: 12;		// measuring to length factor
var tfactor = 	metric ? 1 	: 25.4;		// strip size to measuring units
var mname = 	metric ? 'mm'	: 'inches';	// measuring length unit name	
var lname = 	metric ? 'metres': 'feet';	// frame length unit name	
var mtoarea = 	mtolength * mtolength;		// measuring to area factor
var glasslong = metric ? 3000 	: 36; 		// maximum size of glass we can use (longer side) U28
var glassshort= metric ? 3000 	: 30;  		// maximum size of glass we can use (shorter side) U28
var checkglass= false;				// true to warn only if glass selected
// end of user configurable values
var noerror = true;
var sessionuserfile = '';
var preventries = [swidth, sheight, sborder];   // previous user entries

function mround(val){	// round or return 3 decimal value
  if ( metric )
    {
    return Math.round(val);
    }
  else
    {
    return to3dec(val);
    }
}

function mceil(val){  	// ceiling or return 3 decimal value
  if ( metric )
    {
    return Math.ceil(val);
    }
  else
    {
    return to3dec(val);
    }
}
function errormsg(msg){	//  warn user - set error flag
  noerror = false;
  alert(msg);
}

function handleEnter (field, event) {   // disable enter key for our size fields
  var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
  if (keyCode == 13) 
    {
    field.onchange();
    return false;
    }
  return true;
}  

function parsenum(text, field, ref, name, min, max, prev){      // used for width, height, border freeform entry
  // parse a user entered unsigned positive number to allow for US style "1 7/8" type entries
  // prev is index into preventries array containing last good [width, height, border]
  var num = -1;
  var value = text.value;
  var res = value.match(/^\s*\d+\s*$|^\s*\d*\.\d+\s*$/);	// simplest case a pure number e.g. 1 .2 0.2 2.2
  if ( res != null )
    {
    num = value;
    }  
  else
    {
    var res = value.match(/^\s*(\d+)\s+([123456789]\d*)\s*\/\s*([123456789]\d*)\s*$/);	// number with fraction e.g. 1 1/4
    if ( res != null )
      {
      var fra = res[2] / res[3];
      num = fra < 1 ? (res[1] - 0) + fra : -1;						// make sure sensible fraction
      }
    else
      {  
      var res = value.match(/^\s*([123456789]\d*)\s*\/\s*([123456789]\d*)\s*$/);	// just fraction e.g. 1/4
      if ( res != null )
        {
        fra = res[1] / res[2];
        num = fra < 1 ? fra : -1;							// make sure sensible fraction
        }
      }
    }
  if ( (num < min) || (num > max) )
    {
    var prompt = num < 0 ? 'Not a valid entry' : 'Invalid size';
    alert(prompt + ' - valid range for ' + name + ' is ' + min + munits + ' to ' + max + munits);
    num = ff(field + ref).value;					// set prior value
    text.value = preventries[prev];					// reset the entry field to prior 
    } 
  ff(field + ref).value = num;
  preventries[prev] = text.value;					// save entry text
  redraw(ref);
  setpricenew(ref);
  return;
}

function topounds(nPounds){	// return 2 decimal digits string of number
  var nCurrency, nWholeCurrency, nFraction, sFraction;
  nWholeCurrency = Math.floor(nPounds);                // no of pounds
  nFraction = Math.round((nPounds - nWholeCurrency) * 100);  // Number of Fraction (2 decimal places)
  if ( nFraction > 99 ) nFraction = 99;
  if (nFraction < 10)                                  // Needs to be two digits
    {
    sFraction = "0" + nFraction.toString();            // Pad with leading zero
    }
  else
    {                                                  // Already has two digits
    sFraction = nFraction.toString();                  // So just format it
    }
  return(nWholeCurrency.toString() + '.' + sFraction);
}

function to3dec(nPounds){		// return up to 3 decimal digits string from number
  var nCurrency, nWholeCurrency, nFraction, sFraction;
  nWholeCurrency = Math.floor(nPounds);                // no of pounds
  nFraction = Math.round((nPounds - nWholeCurrency) * 1000);  // Number of Fraction (3 decimal places)
  if ( nFraction > 999 ) nFraction = 999;
  if (nFraction < 10)                                  // Needs to be three digits
    {
    sFraction = "00" + nFraction.toString();           // Pad with 2 leading zeros
    }
  else if (nFraction < 100)                            // Already has two digits
    {
    sFraction = "0" + nFraction.toString();            // Pad with leading zero
    }
  else
    {                                                  // Already has three digits
    sFraction = nFraction.toString();                  // So just format it
    }
  // remove .replace(/\.000|0{1,2}$/, "")  below if you don't want result trimmed
  return((nWholeCurrency.toString() + '.' + sFraction).replace(/\.000|0{1,2}$/, ""));	// trim trailing spaces
}

function ff(field){  // look through all parent forms for one containing field
  if ( document.getElementById(field) ) return document.getElementById(field); 
  // should never get here but...
  alert('Cannot find field - ' + field);
  return false;
}

function manageprice(prodref, price){    // work out if a discount is to be applied
 price = price.replace(/&#44;/g,"");     // remove all commas
 price = price.replace(/&#46;/g,".");    // restore decimal point
 price = price.replace(/&#163;|&#36;/g,"£");    // fix £ and $ to just £ (so we can fiddle with it later)
 var pbits = price.match(/(£\d+\.\d\d).*(£\d+\.\d\d)/);
 if ( pbits != null )
  {
  document.getElementById(prodref + '$disc').value = pbits[2].replace(/£/,"") / pbits[1].replace(/£/,"");  // save the calculated discount
  //  alert(price + ' - ' + pbits[1] + ' - ' + pbits[2] + ' - ' + document.getElementById(prodref + '$disc').value);
  }
}

function setprice(prodref, item, price){  // work out if a discount is to be applied
//alert(item);
 document.getElementById(prodref + item).value  = currsymbol + topounds(document.getElementById(prodref + '$disc').value * price)
}

function createoptions(selname, min, max, def){		// only used for Imperial Templates
  var opt = ff(selname).options; 			// our options
  opt.length = 0;					// delete any options
  var optindex = 0;
  for ( var i = min; i <= max; i++ )
    {
    opt[optindex++] = new Option(i, i);
    }  
  for ( var i = 0; i < opt.length; i++ )
    {
    if ( opt[i].value == def ) opt[i].selected = true;
    }  
}

function setimperial(ref, units, fracts, dest){ 	 // only used for Imperial Templates
  ff(dest + ref).value = (ff(units + ref).value - 0) + (ff(fracts + ref).value - 0);
  redraw(ref);
  setpricenew(ref);  
}

function setpricenew(prodref)
  {
  var discount = document.getElementById(prodref + '$disc').value
  var glassprice = document.getElementById(prodref + '$glprice').value.replace(/£|\$/,"");
  var mountprice = document.getElementById(prodref + '$mbprice').value.replace(/£|\$/,"");
  var hardboardprice = document.getElementById(prodref + '$hbprice').value.replace(/£|\$/,"");
  var foamcoreprice = document.getElementById(prodref + '$fcprice').value.replace(/£|\$/,"");
  var cutoutprice = document.getElementById(prodref + '$coprice').value.replace(/£|\$/,"");
  var cuttingcharge = document.getElementById(prodref + '$cctemp').value.replace(/£|\$/,"");
  noerror = true;
  var info = '';

  var frameprice = document.getElementById(prodref + '$stripprice').value.replace(/£|\$/ig,"");
  var frameindex = document.getElementById(prodref + '$stripindex').value;
  var thickness = mround((document.getElementById(prodref + '-' + frameindex).height / framescale) / tfactor) - 0;  // US Mod NB changed Rounding from mm to 2 decimals
  var across = ff('acro_' + prodref).value;
  if ( isNaN(across) || (across < 0) || ( across > 10) ) 
   {
   across = 1;
   errormsg('Bad number of images across - must be between 1 and 10');
   }
  across = Math.ceil(across);
  ff('acro_' + prodref).value = across;

  var down = ff('down_' + prodref).value;
  if ( isNaN(down) || (down < 0) || ( down > 10) ) 
   {
   down = 1;
   errormsg('Bad number of images down - must be between 1 and 10');
   }
  down = Math.ceil(down);
  ff('down_' + prodref).value = down;

  var width = ff('wdth_' + prodref).value - 0;
  if ( isNaN(width) || (width < minwidth) ) 
   {
   width = minwidth;
   errormsg('Bad width - minimum is ' + minheight + munits);	// US Mod
   }
  var rwidth = mceil(width - 0);				// US Mod
  ff('wdth_' + prodref).value = rwidth;

  var height = ff('hght_' + prodref).value - 0;
  if ( isNaN(height) || (height < minheight) )
   {
   height = minheight;
   errormsg('Bad height - minimum is ' + minheight + munits);	// US Mod
   }
  var rheight = mceil(height - 0);				// US Mod
  ff('hght_' + prodref).value = rheight;

  // check for valid mountboard border width
  var cutwidth = ff('cuw_' + prodref).value;
  if ( isNaN(cutwidth) || (cutwidth < cutmin) || cutwidth > cutmax )	// US Mod 
    {
    errormsg('Bad border width - must be between ' + cutmin + ' ' + munits + ' and ' + cutmax + ' ' + munits);	// US Mod
    cutwidth = cutmin;							// US Mod
    }
  cutwidth = mceil(cutwidth); 						// US Mod
  ff('cuw_' + prodref).value = cutwidth;
 
  if ( ff('mob_' + prodref).checked )	// check for outer mount
    {
    var outerborder = true;
    }
  else
    {
    outerborder = false;
    }

  if ( ff('cuh_' + prodref).checked )	// check for inner mount
    {
    var innerborder = true;
    }
  else
    {
    innerborder = false;
    }
  var innerwidth = ( across * ( width - overlap - overlap) ) + ( cutwidth * (across + 1) );    // US Mod
  var innerheight = ( down * ( height - overlap - overlap) ) + ( cutwidth * (down + bottomborder) );  // US Mod

  // U28 - special code to check that bigger picture than max glass size can't be ordered
  var glasswidth = innerwidth + overlap + overlap;
  var glassheight = innerheight + overlap + overlap;
  if ( (Math.max(glasswidth, glassheight) > glasslong) || (Math.min(glasswidth, glassheight) > glassshort) )
    { 
    if ( ! checkglass )
      // U28 US VERSION - Ignore whether glass required - special code to check that bigger picture than max glass size can't be ordered
      {
      alert('Sorry, but the maximum inner frame measurement for this frame is: ' + glasslong + munits + ' by '  + glassshort + munits + '.'
          + '\nYour picture needs an inner frame ' + topounds(glasswidth) + munits + ' wide x ' + topounds(glassheight) + munits + ' high.' 
          + ' Please review.');
      noerror = false;
      }
    else if ( ff('gab_' + prodref).checked || (ff('gab_' + prodref).value == "SHOW") )
      {
      alert('This picture can\'t be glazed. Maximum glass size is: ' + glasslong + munits + ' by '  + glassshort + munits
          + '\nYour picture needs a glass ' + topounds(glasswidth) + munits + ' wide x ' + topounds(glassheight) + munits + ' high' 
          + '\nEither uncheck "Plastic Glass" or reduce picture / border size');
      noerror = false;
      }
    }

  var outerwidth = innerwidth + thickness + thickness;
  var outerheight = innerheight + thickness + thickness;

  if ( innerwidth > maxside )		// US Mod
    {
    alert('Overall frame width: ' + innerwidth + ' ' + munits + ' is too big to build');	// US Mod
    noerror = false;
    }
  if ( innerheight > maxside )		// US Mod
    {
    alert('Overall frame height: ' + innerheight + ' ' + munits + ' is too big to build');	// US Mod
    noerror = false;
    }

  var length = (outerwidth + outerwidth + outerheight + outerheight) / mtolength;	// US Mod
  var rlength = topounds(length);
  var area = innerwidth * innerheight / mtoarea;					// US Mod
  if ( (area != 0) && (area < minarea) ) area = minarea;          			// US Mod
  var rarea = topounds(area);
  info = 'Width: ' + rwidth + ' ' + munits +'|Height: ' + rheight + ' ' + munits 
        +'|Across: ' + across + '|Down: ' + down + '|Border: ' + cutwidth + ' ' + munits; 	// US Mod
  info += '{' + thickness + '}';
  if ( innerborder && outerborder ) info += '|Innerborder: Yes';

  ff('len_' + prodref).value = rlength;
  var rtotal = 0;

  // the frame name length & price
  // V208 amended to skip if zero cost
  if ( (frameprice - 0) > 0 )
    {
    var lprice = topounds(frameprice * rlength);
    rtotal += lprice - 0;
    var framename = document.getElementById(prodref + '$stripname').value.replace(/:|\|/g," ");   // remove any special characters

    info += '|Frame: ' + framename + '{' + frameindex + '}|Length: ' + rlength + ' ' + lunits + ' @ ' + currsymbol + frameprice + ' - ' + currsymbol + lprice;
    ff('frt_' + prodref).value = lprice;
    }

  // the cutting charge
  if ( cuttingcharge ) 
    {
    rtotal += cuttingcharge - 0;
    ff('cct_' + prodref).value = cuttingcharge;
    info += '|Cutting Charge: ' + currsymbol + cuttingcharge;
    }

  // the glass price (V208 patch on 1 line below)
  if ( ff('gab_' + prodref).checked || (ff('gab_' + prodref).value == "SHOW") ) 
    {
    ff('ar1_' + prodref).value = rarea;
    var gprice = topounds(glassprice * rarea);
    ff('gat_' + prodref).value = gprice;
    rtotal += gprice - 0;
    info += '|Plastic Glass: ' + rarea + ' ' + aunits + ' @ ' + currsymbol + glassprice + ' - ' + currsymbol + gprice;	// US Mod 
    }
  else
    {
    ff('ar1_' + prodref).value = '';
    ff('gat_' + prodref).value = '';
    }

/* disabled the non-reflective price
  var nonreflect = document.getElementById(prodref + '$nreflect').value.replace(/£|\$/,"");
  if ( ff('non_' + prodref).checked && ff('gab_' + prodref).checked ) 
    {
    ff('ar3_' + prodref).value = rarea;
    var noncost = topounds(glassprice * nonreflect)
    var nonprice = topounds(noncost * rarea);
    ff('not_' + prodref).value = nonprice;
    rtotal += nonprice - 0;
    info += '|Non Reflective: ' + rarea + ' ' + aunits + ' @ ' + currsymbol + noncost + ' - ' + currsymbol + nonprice;	// US Mod 
    }
  else
    {
    ff('ar3_' + prodref).value = '';
    ff('not_' + prodref).value = '';
    }
*/

  // hardboard
  if ( ff('hab_' + prodref).checked ) 
    {
    ff('ar4_' + prodref).value = rarea;
    var hprice = topounds(hardboardprice * rarea);
    ff('hat_' + prodref).value = hprice;
    rtotal += hprice - 0;
    info += '|Hardboard: ' + rarea + ' ' + aunits + ' @ '  + currsymbol + hardboardprice + ' - ' + currsymbol + hprice;	// US Mod 
    }
  else
    {
    ff('ar4_' + prodref).value = '';
    ff('hat_' + prodref).value = '';
    }

  // foamcore
  if ( ff('foc_' + prodref).checked ) 
    {
    ff('ar5_' + prodref).value = rarea;
    var fprice = topounds(foamcoreprice * rarea);
    ff('fot_' + prodref).value = fprice;
    rtotal += fprice - 0;
    info += '|Foamcore: ' + rarea + ' ' + aunits + ' @ ' + currsymbol + foamcoreprice + ' - ' + currsymbol + fprice;	// US Mod 
    }
  else
    {
    ff('ar5_' + prodref).value = '';
    ff('fot_' + prodref).value = '';
    }

  // mountboard
  if ( outerborder ) 
    {
    var marea = rarea - 0;
    var innerinfo = '';
    if ( innerborder )
      {
      marea += marea;   // twice as much mountboard if inner border
      innerinfo = ' (Inner ' + innername + ')';
      }
    ff('ar2_' + prodref).value = marea;
    var mprice = topounds(mountprice * marea);
    ff('mot_' + prodref).value = mprice;
    rtotal += mprice - 0;
    info += '|' + mdesc + ': ' + mountname + innerinfo + ' - ' + marea + ' ' + aunits + ' @ ' + currsymbol + mountprice + ' - ' + currsymbol + mprice;	// US Mod 
    }
  else
    {
    ff('ar2_' + prodref).value = '';
    ff('mot_' + prodref).value = '';
    }

  // cutout
  if ( ff('cuo_' + prodref).checked && ff('mob_' + prodref).checked ) 
    {
    var numcutouts =  across * down;
    var cutoutinfo = '';
    if ( innerborder ) 
      {
      cutoutinfo = 'Outer ' + numcutouts + ', Inner ' + numcutouts + ', Total ';
      numcutouts += numcutouts;   // twice as may cutouts if inner border
      }
    var cutouttotal = numcutouts * cutoutprice;
    ff('cuc_' + prodref).value = numcutouts;
    var ctotal = topounds(cutouttotal);
    ff('cut_' + prodref).value = ctotal;
    rtotal += numcutouts * ( cutoutprice - 0);
    info += '|Cutouts: ' + cutoutinfo + numcutouts + ' @ ' + cutoutprice + ' - ' + currsymbol + ctotal;
    }
  else
    {
    ff('cuc_' + prodref).value = '';
    ff('cut_' + prodref).value = '';
    }
  info += '{Total: ' + topounds(rtotal) + '}';    		// pass hidden calculated total to scripts
  info += '{Icon: ' + document.getElementById(prodref + '$icon').value + '}';	// pass hidden icon filename
  var iconimage = geticonimage(prodref,100,100);
  if ( iconimage ) info += '{Image: ' + iconimage + '}';	// pass hidden icon filename
  ff('tot_' + prodref).value =  currsymbol + topounds(rtotal);
  ff('inf_' + prodref).value = info;
  if ( diags ) ff('diag_' + prodref).innerHTML = info;
  return noerror;
}

	function redraw(ref, price, name, index, icon){
        if ( icon )
          {
          document.getElementById(ref + '$icon').value = icon;
          }

        if ( index )
          {
          document.getElementById(ref + '$stripindex').value = index;
          }

        if ( name )
          {
          document.getElementById(ref + '$stripname').value = name;
          }
        if ( price )
          {
          document.getElementById(ref + '$stripprice').value =  currsymbol + topounds(price * document.getElementById(ref + '$disc').value);
          setpricenew(ref);
          }
        drawsized(ref, defaultwidth, defaultheight);
        }


function useuploadimage(ref){
  var lastimage = sessionuserfile;
  if ( ! lastimage ) lastimage = document.getElementById(ref + '$uploaded').value
  if ( ! lastimage )
    {
    alert('No image uploaded');
    return;
    }
  document.getElementById(ref + '$mypic').value = lastimage.replace(/\.jpg$/i,"");
  redraw(ref);
}

function cartimageenlarge(image){
  var popwin = window.open(basehref + image, 'showbig', 'width=420,height=420,toolbar=no');
  popwin.focus();
}


        function popupuploadform(ref){
	 var popwin = window.open(basehref + 'user_image_upload_form.html?ref=_' + ref + '_', 'upform', 'height=500,width=500,toolbar=no');
         popwin.focus();
        }


        function popupsized(ref, w, h, corner){
         var frame = ff(ref + '$frame').value;
         var icon = document.getElementById(ref + '$icon').value;
         var mirror = document.getElementById(ref + '$mirr').value;
         var width = Math.round(ff('wdth_' + ref).value * tfactor);       // US Mod always use mm
         var height = Math.round(ff('hght_' + ref).value * tfactor);      // US Mod always use mm
         var across = ff('acro_' + ref).value;
         var down = ff('down_' + ref).value;
         var mountwidth = Math.round(ff('cuw_' + ref).value * tfactor);   // US Mod always use mm
         var picture = ff(ref + '$mypic').value;
         var now = new Date();
	 if ( ff('cuh_' + ref).checked )
    	  {
          var mounttwo = 'yes';
           }
         else
           {
           mounttwo = '';
           }
         if ( (width < (minwidth * tfactor)) || (height < (minheight * tfactor)) )	// US Mod always use mm
           {
           alert('Sizes too small');
           return;
           } 
         if ( (width > (maxside * tfactor)) || (height > (maxside * tfactor)) ) 	// US Mod always use mm
           {
           alert('Sizes too large');
           return;
           }

         var popwidth = w + 100;
         var popheight = h + 150;

	 // we seem to need a full URL here for IE when logged in.
	 var popwin = window.open(basehref + 'scaledframewindow.php?strip=' + frame 
					    + '&icon=' + icon + '&mirr=' + mirror + '&scale=' + framescale 
                                            + '&width=' + width + '&height=' + height 
                                            + '&ac=' + across + '&do=' + down 
                                            + '&mcol=' + mountcolour + '&mow=' + mountwidth + '&mo2=' + mounttwo
					    + '&icol=' + innercolour
                                            + '&mypic=' + picture + '&dw=' + w + '&dh=' + h + '&corn=' + corner 
                                            + '&wall=' + wall
                                            + '&seq=' + now.getTime(),
				  'showbig', 
				  ',width=' + popwidth + ',height=' + popheight + ',toolbar=no');
         popwin.focus();
	}

        function drawsized(ref, w, h){
         
         var frame = ff(ref + '$frame').value;
         var icon = document.getElementById(ref + '$icon').value;
         var mirror = document.getElementById(ref + '$mirr').value;
         var width = Math.round(ff('wdth_' + ref).value * tfactor);       // US Mod always use mm
         var height = Math.round(ff('hght_' + ref).value * tfactor);      // US Mod always use mm
         var across = ff('acro_' + ref).value;
         var down = ff('down_' + ref).value;
         var mountwidth = Math.round(ff('cuw_' + ref).value * tfactor);   // US Mod always use mm
         var picture = ff(ref + '$mypic').value;
         var now = new Date();
	 if ( ff('cuh_' + ref).checked )
    	  {
          var mounttwo = 'yes';
           }
         else
           {
           mounttwo = '';
           }
         if ( (width < (minwidth * tfactor)) || (height < (minheight * tfactor)) )	// US Mod always use mm
           {
           alert('Sizes too small');
           return;
           } 
         if ( (width > (maxside * tfactor)) || (height > (maxside * tfactor)) ) 	// US Mod always use mm
           {
           alert('Sizes too large');
           return;
           }
	 document.getElementById(ref + '$wowza').src='scaledframe.php?strip=' + frame
					    + '&icon=' + icon + '&mirr=' + mirror + '&scale=' + framescale  
                                            + '&width=' + width + '&height=' + height 
                                            + '&ac=' + across + '&do=' + down 
                                            + '&mcol=' + mountcolour + '&mow=' + mountwidth + '&mo2=' + mounttwo
					    + '&icol=' + innercolour
                                            + '&mypic=' + picture + '&dw=' + w + '&dh=' + h + '&corn=no&seq=' + now.getTime();
	}

function geticonimage(ref, w, h){
         
         var frame = ff(ref + '$frame').value;
         var mirror = document.getElementById(ref + '$mirr').value;
         var icon = document.getElementById(ref + '$icon').value;
         var width = Math.round(ff('wdth_' + ref).value * tfactor);       // US Mod always use mm
         var height = Math.round(ff('hght_' + ref).value * tfactor);      // US Mod always use mm
         var across = ff('acro_' + ref).value;
         var down = ff('down_' + ref).value;
         var mountwidth = Math.round(ff('cuw_' + ref).value * tfactor);   // US Mod always use mm
         var picture = ff(ref + '$mypic').value;
         var now = new Date();
	 if ( ff('cuh_' + ref).checked )
    	  {
          var mounttwo = 'yes';
           }
         else
           {
           mounttwo = '';
           }
         if ( (width < (minwidth * tfactor)) || (height < (minheight * tfactor)) )	// US Mod always use mm
           {
           alert('Sizes too small');
           return;
           } 
         if ( (width > (maxside * tfactor)) || (height > (maxside * tfactor)) ) 	// US Mod always use mm
           {
           alert('Sizes too large');
           return;
           }
	 return 'scaledframe.php?strip=' + frame
					    + '&icon=' + icon + '&mirr=' + mirror + '&scale=' + framescale  
                                            + '&width=' + width + '&height=' + height 
                                            + '&ac=' + across + '&do=' + down 
                                            + '&mcol=' + mountcolour + '&mow=' + mountwidth + '&mo2=' + mounttwo 
					    + '&icol=' + innercolour
                                            + '&mypic=' + picture + '&dw=' + w + '&dh=' + h + '&corn=no&seq=' + now.getTime();
	}

function framechoice(ref,name,stripicon,stripimage){
  var previewpath = location.href.indexOf('PreviewHTML') > -1 ? '../' : '';  // V8
  stripindex++;
  if ( stripicon == '' ) return;
  namebits = name.match(/^[£\$]*(\d+\.\d\d)\s+(.+)/);		// extract the price
  if ( namebits != null )
    { 
    var price = namebits[1];
    name = namebits[2]; 
    var cleanname = name.replace(/:|\||\{|\}/g," ");   		// remove any special characters;
    if ( firsticon == '' )					// remember first valid icon
      {
      firstname = cleanname;
      firstindex = stripindex;
      firsticon = stripicon;
      firstimage = stripimage;
      firstprice = price;
      }
    if ( seq++ == 0) document.write('<tr>');
    document.write('<td class="fficonoutercell" width="33%">'
		 + '<table class="fficontable" width=100%><tr><td class="fficonname">' + name + '</td></tr>'
                 + '<tr><td class="fficonimagecell">'
                 + '<img class="fficonimage" id="' + ref + '-' + stripindex + '"' 
		 + ' border=0 src="' + previewpath + stripicon + '" alt="' + name + '" title="' + name + '"'
		 + ' onclick="document.getElementById(\'' + ref + '$frame\').value=\'' + stripimage 
                 + '\';redraw(\'' + ref + '\',\'' + price + '\',\'' + cleanname + '\',' + stripindex + ',\'' + stripicon + '\')"' 
		 + '></td></tr>'
                 + '<tr><td class="fficonprice">' + currsymbol + price + '</td></tr>'
		 + '</table>'
		 + '</td>');
    }
  else
    {
    if (name.search(/^[£\$]*\d+\.\d\d/) == -1)
      {
      price = '<font color=red><b>PRICE ERROR<br>' + currsymbol + name.substring(0,5) + '</b></font>';
      }
    else
      {
      namebits = name.match(/^[£\$]*(\d+\.\d\d)\s*(.*)/);
      price = currsymbol + namebits[1];
      name = namebits[2];
      }
    if (name.length == 0) name = '<font color=red><b>ERROR<br>No description</b></font>';
    if ( seq++ == 0) document.write('<tr>');
    document.write('<td class="fficonoutererrorcell" width="33%">'
		 + '<table class="fficontable" width=100%><tr><td class="fficonname">' + name + '</td></tr>'
                 + '<tr><td class="fficonimagecell" align=center>'
                 + '<img class="fficonimage" border=0 src="' + previewpath + stripicon + '" alt="' + name + '" title="' + name + '">'
                 + '</td></tr>'
                 + '<tr><td class="fficonprice">' + price + '</td></tr>'
		 + '</table>'
		 + '</td>');
    }

  if ( seq >= 3 )
    {
    document.write('</tr>');
    seq = 0;
    }
} 

function framefinish(){ // balance out the table (3 cols at present)
  if ( seq != 0 )
    {
    while ( seq++ < 3 ) document.write('<td>&nbsp;</td>');
    }
}

 
function setinitialprice(ref, name, price, icon, image, index){
  document.getElementById(ref + '$stripindex').value = index;
  document.getElementById(ref + '$stripprice').value = currsymbol + topounds(price * document.getElementById(ref + '$disc').value);
  document.getElementById(ref + '$stripname').value = name;
  document.getElementById(ref + '$icon').value = icon;
  document.getElementById(ref + '$frame').value = image;
}

function setcolour(ref, cname, cvalue){
  if ( document.getElementById(ref + '$csel1').checked ) 
    {
    wall = cvalue;
    document.getElementById(ref + '$wall').style.backgroundColor='#' + cvalue;
    }
  if ( document.getElementById(ref + '$csel2').checked )
    {
    mountcolour = cvalue;
    mountname = cname;
    redraw(ref);
    }
  if ( document.getElementById(ref + '$csel3').checked )
    {
    innercolour = cvalue;
    innername = cname;
    redraw(ref);
    }
  document.getElementById(ref + '$cdemo').style.backgroundColor='#' + cvalue;
}

function showcolour(ref, cname, cvalue){
  document.getElementById(ref + '$cdemo').style.backgroundColor='#' + cvalue;
}

function drawcolourmatrix(ref){
// generate a colour matrix
var count = 0;
document.write('<table cellspacing=1 cellpadding=0 border=0 style="cursor:pointer"><tr height=10>');
col = 0;
for ( i = 0; i < mountcolours.length - 2; i += 2 )
  {
      if ( col >= maxcols )
        {
        document.write('</tr><tr height=10>');
        col = 0;
        }
      count++;
      var imgpos = mountcolours[i].indexOf(' ');	// either 'rrggbb' or 'rrggbb image.jpg'
      if ( imgpos == -1 )
        {
        var colour = mountcolours[i];			//simple rrggbb colourcode
        var colourcell = ' bgcolor="#' + colour; 
        }
      else
        {						// we have an image as well so 
        colour = mountcolours[i].substring(0, imgpos);  // pick out rgb code
        colourcell = ' background="' + mountcolours[i].substring(imgpos + 1).replace(/\s/g,""); //then image name after space
        }
      var cname = mountcolours[i + 1].replace(/:|\||\{|\}/g," ");   	// remove any special characters;
      document.write('<td width=' + colourwidth + ' height=' + colourheight + colourcell + '"' 
                   + ' onmouseover="showcolour(\'' + ref + '\',\'' + cname + '\',\'' + colour + '\')"'
                   + ' onmouseout="showcolour(\'' + ref + '\',\'' + cname + '\',\'ffffff\')"'
                   + ' onclick="setcolour(\'' + ref + '\',\'' + cname + '\',\'' + colour + '\')">'
                   + '<img border=0 src="c2x2.gif" width=' + colourwidth + ' height=' + colourheight 
		   + ' title="' + cname + '"></td>');
      col++;
  }
// pad out with final colour
while ( col++ < maxcols )
       {
       document.write('<td width=' + colourwidth + ' height=' + colourheight + colourcell + '"' 
                   + ' onmouseover="showcolour(\'' + ref + '\',\'' + cname + '\',\'' + colour + '\')"'
                   + ' onmouseout="showcolour(\'' + ref + '\',\'' + cname + '\',\'ffffff\')"'
                   + ' onclick="setcolour(\'' + ref + '\',\'' + cname + '\',\'' + colour + '\')">'
                   + '<img border=0 src="c2x2.gif" width=' + colourwidth + ' height=' + colourheight
		   + ' title="' + cname + '"></td>');
       }
document.write('</tr></table>');
}


