var customSelectDoAll = false; // override in custom.js if needed - false = only do selects with data-custom="" attribute

// *********** pre-post form data checking stuff
// to use this all you do is add ' onsubmit="return checkData(this);" ' to the form definition
// and add data-man="" to each input, select or textarea you want to be mandatory.
// data-man can have other values to add extra control to the pre-post checks
// multiple controls are separated by | eg "minl=5|maxl=20|blankok"
// "email" does a check for a valid email address
// "minl" and "maxl" control the min and max length
// "minv" and "maxv" control the min and max values
// "maxr" limits the number of rows in a textarea
// "pwd" sets the min and max length to 6 and 20 and stops ' and " being entered
// "cc" does a basic credit card modulus check with min and max lengths of 13 and 19
// "confirm=xxx" will check that the value is the same as the value in the element with id="xxx"
// "novalue=nowt,none" will treat 'nowt' and 'none' as being the same as '' (comma delimited list)
//     -- use this if the default or blank value of a drop down is somthing other than ''
// "blankok" allows restrictions to be set but only checked if the value is not '' eg password change
// "noquote" prevents ' being entered
// "nodblquote" prevents " being entered
// "ukonly=country" country is the id of the country selector. Use this on a postcode field to only insist
//    on a postcode if the country code is in the 'postcodeCountries' array
// "oldpw" makes sure that the entered password matches the encrypted old password in:
//    <input type="hidden" name="sctot" id="sctot" value="<elucid_enc_pw>">
// "group=1" will only apply restrictions if a field with "group=1" has data in it
// "CIcheck=country" will force Channel islands in the 'country' field if a CI postcode is entered
//    or force UK if country = CI and postcode is not.

function isEmail(s) {
  return s.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i) != null;
}
function ccCheck(number) {
  var number=number.replace(/ /g, '');  // Strip any spaces
  var number_length=number.length;
  var parity=number_length % 2;
  var total=0;
  for (i=0; i < number_length; i++) {
    var digit=number.charAt(i);
    if (i % 2 == parity) { digit=digit * 2;  if (digit > 9) { digit=digit - 9; } }
    total = total + parseInt(digit);
  }
  return ((total % 10 == 0) && (number_length >= 13) ? true : false);
}
var checkEleError = null;
var checkErrTimer = null;
var checkErrVal = '';
var checkErrEle = null;
var checkIDCounter = 0;
function showErr(el) {
  if (!checkEleError) {
    checkEleError = createDynamicPopup('errorPopup','','errorPopup');
    var s = '<table cellspacing="0" cellpadding="0" border="0"><tr>';
    s += '<td id="ceeMain" style="padding:14px 0 0 20px; font-weight:bold; background-position: 0 0;"></td>';
    s += '<td style="width:20px; height:20px; background-position: right 0;"><!--x--></td>';
    s += '</tr><tr>';
    s += '<td class="bot" style=" background-position: 0 bottom;"><!--x--></td>';
    s += '<td class="bot" style=" background-position: right bottom;"><!--x--></td>';
    s += '</tr></table>';
    checkEleError.innerHTML = s;
  } else {
    globZindex++;
    checkEleError.style.zIndex = globZindex;
  }

  var tmp = document.getElementById('ceeMain');
  tmp.innerHTML = el.stat;
  checkEleError.style.display = 'block';
  var exy = getBounds(el);
  var exe = getBounds(checkEleError);

  checkEleError.style.top = exy.y -exe.h+1 + 'px';
  checkEleError.style.left = exy.x + 15 + 'px';
  hideSelects(el);
}
function hideErr(el) {
  if (checkErrTimer) { clearTimeout(checkErrTimer); }
  if (checkEleError) { checkEleError.style.display = 'none'; }
  showSelects();
}
function checkErrOnTimer(tim) {
  var ele = checkErrEle;
//document.title = ele.tagName+' | '+ele.value+' | '+checkErrVal;
  if (ele.value != checkErrVal || ele.type == 'radio') {
    checkEle(ele, 1);
  } else {
    checkErrTimer = setTimeout( "checkErrOnTimer(this)", 1000 );
    checkErrTimer.ele = ele;
  }
}
function hasNoValue(val, novalue) {
  val = val.toLowerCase();
  if (val === '') { return true; }
  if (novalue) {
    for (var i=0; i<novalue.length; i++) {
      if (novalue[i].toLowerCase() == val.toLowerCase()) { return true; }
    }
  }
  return false;
}
function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}
var checkDataGroupData = new Array;
var checkDataGroup = new Array;
function groupIsEmpty(group,form) {
//  try { eval('var fields = checkDataGroup'+group); }
//  catch(err) { alert('data-man="group='+group+'" was used but checkDataGroup'+group+' variable was not set up'); };
//  if (!window.checkDataGroup[group]) {
//    alert('data-man="group='+group+'" was used but checkDataGroup'+group+' variable was not set up');
//    return false;

//  } else {
    if (!window.checkDataGroupData[group] || window.checkDataGroupData[group] == undefined) {
      if (!window.checkDataGroup[group]) {
        checkDataGroup[group] = '';
        var eles = form.elements;
        for (var i=0; i<eles.length; i++) {
          var man = eles[i].getAttribute('data-man');
          if (man && man.indexOf('group='+group) > -1) {
            checkDataGroup[group] += eles[i].id + ',';
          }
        }
      }
      checkDataGroupData[group] = '';
      var fields = checkDataGroup[group].split(',');
      for (var i=0; i<fields.length; i++) {
        if (fields[i]) {
          var ele = document.getElementById(fields[i]);
          if (ele) {
            checkDataGroupData[group] += trim(ele.value);
          } else {
            alert(fields[i]+' is in checkDataGroup['+group+'] but doesnt exist on the form');
          }
        }
      }
    }
    return checkDataGroupData[group] == '';
//  }
}
function tidyEvent(ev) {
  var oldfunc = ev.toString();
  var i = oldfunc.indexOf('function');
  var j = oldfunc.indexOf('{');
  if (i > -1 && j > -1) { oldfunc = oldfunc.substring(0,i-1) + oldfunc.substr(j+1,500); }
//  oldfunc = oldfunc.replace('function','');
//  oldfunc = oldfunc.replace('onkeyup()','');
 // oldfunc = oldfunc.replace('onblur()','');
//  oldfunc = oldfunc.replace('{','');
  oldfunc = oldfunc.replace('}','');
  oldfunc = oldfunc.replace(';','');
  oldfunc = oldfunc.replace('return','');
  oldfunc = trim(oldfunc);
  return oldfunc;
}
var postcodeCountries = 'UK,GB,JE,GY';  // override by copying to custom.js if needed
var CIcheck = { 'match':'(gy|je)[ ]*([0-9])', 'country':'CI', 'notCI':'UK' }; // override by copying to custom.js if needed
function checkEle(ele, from, form, src) {
  if (checkErrTimer) { clearTimeout(checkErrTimer); }
  var ok = true;
  var man = ele.getAttribute('data-man');
  var par = ele.getAttribute('data-man-par');

  if (par) {
    ele = document.getElementById(par);
    var man = ele.getAttribute('data-man');
  }
  var val = trim(ele.value);
  if (man != undefined && val != undefined) {
    var minl = 0; var maxl = 9999; var maxr = 9999; var minv = -999999999; var maxv = 999999999;
    var noquote = false; nodblquote = false; countrySel = null;  CIcountrySel = null;  oldpw = false;
    var confirm = '';  var novalue = ''; var isval = false; var blankok = false; group = '';
    var customfunc = null;
    var mana = man.split('|');
    for (var j=0; j<mana.length; j++) {
      var manj = mana[j].split('=');
      if (manj[0] == 'cc') { minl = 13; maxl = 19; }
      if (manj[0] == 'pwd') { minl = 6; maxl = 20; noquote = true; nodblquote = true; }
      if (manj[0] == 'noquote') { noquote = true; }
      if (manj[0] == 'nodblquote') { nodblquote = true; }
      if (manj[0] == 'minl') { minl = manj[1]-0; }
      if (manj[0] == 'maxl') { maxl = manj[1]-0; }
      if (manj[0] == 'maxr') { maxr = manj[1]-0; }
      if (manj[0] == 'minv') { isval = true; minv = manj[1]-0; }
      if (manj[0] == 'maxv') { isval = true; maxv = manj[1]-0; }
      if (manj[0] == 'confirm') { confirm = document.getElementById(manj[1]); }
      if (manj[0] == 'novalue') { novalue = manj[1].split(','); }
      if (manj[0] == 'blankok') { blankok = true; }
      if (manj[0] == 'ukonly') { countrySel = document.getElementById(manj[1]); postcodeCountries += ','; }
      if (manj[0] == 'CIcheck') { CIcountrySel = document.getElementById(manj[1]);  }
      if (manj[0] == 'oldpw') { oldpw = true; }
      if (manj[0] == 'group') { group = manj[1]; }
      if (manj[0] == 'customfunc') { customfunc = manj[1]; }
    }
    var errstr = '';

    if (customfunc) {
      var ss = 'var res = '+customfunc+'(\''+ele.id+'\')';
      eval(ss);
      if (!res.ok) { ok = false; errstr += res.errstr }
    }
    
    if (from == 0 && group && groupIsEmpty(group,form)) {  // from = 0 = batch check
    }
    else if (blankok && hasNoValue(val,novalue)) {
    }
    else if (confirm == undefined || (confirm && (confirm.value == undefined))) {
      // if the confirm element doesnt exist show a message to programmer
      ok = false; errstr += 'confirm id does not exist (programmer)';
    }
    else if (confirm) {
      if (confirm.value != val) { ok = false; errstr += 'Confirmation value does not match'; }
    }
    else if (oldpw) {
      if (val == '') { ok = false; errstr += 'Please enter your old password'; }
      else {
        var pwel = document.getElementById('sctot');
        if (pwel) {
          var scpw = val.toUpperCase();
          var pwht = 0;
          for (var xi=0; xi < scpw.length; xi++) { pwht += scpw.charCodeAt(xi) * (1+Math.pow(xi*256,2)); }
          if (pwht != pwel.value) { ok = false; errstr += 'The password you entered does not match your old password'; }
        } else {
          ok = false; errstr += 'sctot not found on page (programmer)';
        }
      }
    }
    else {
      var eng = (ele.tagName == 'SELECT' ? 'selected' : 'entered');
      if (man == 'cc' && !ccCheck(val)) { ok = false; errstr += 'Credit Card number is invalid<br>'; }
      if (man == 'email' && !isEmail(val)) { ok = false; errstr += 'Email address is not a valid address<br>'; }
      if (val.length < minl) { ok = false; errstr += 'Minimum length is '+minl+' characters ('+val.length+' Entered)<br>'; }
      if (val.length > maxl) { ok = false; errstr += 'Maximum length is '+maxl+' characters ('+val.length+' Entered)<br>'; }
      if (noquote && (val.indexOf("'") > -1)) { ok = false; errstr += "The single quote character (') is not allowed<br>"; }
      if (nodblquote && (val.indexOf('"') > -1)) { ok = false; errstr += "The double quote character (\") is not allowed<br>"; }
      if (isval && (val-0 < minv || val-0 > maxv || !isNumeric(val))) { ok = false; errstr += 'Please enter a number between '+minv+' and '+maxv+'<br>'; }

      if (maxr < 9999) {
        var rows=val.replace(/\r/g,'').split('\n')
        var rowc = rows.length + (rows[rows.length-1] == '' ? -1 : 0);
        if (rowc > maxr) { ok = false; errstr += 'Maximum number of lines is '+maxr+' ('+rowc+' Entered)<br>'; }
      }

      if (hasNoValue(val, novalue)) {
        if (countrySel) {
          if (postcodeCountries.indexOf(countrySel.value+',') > -1 )
            { ok = false; errstr = 'A value needs to be '+eng+'<br>'; }
        } else {
          ok = false; errstr = 'A value needs to be '+eng+'<br>';
        }
      } else {
        // something entered
        if (CIcountrySel) {
          var matchit = new RegExp(CIcheck.match, "i")
          if (val.match(matchit) && CIcountrySel.value != CIcheck.country) {
            CIcountrySel.value = CIcheck.country;
//            alert('Channel Islands country has been auto selected to match your Channel Islands postcode');
            errstr+= 'Channel Islands has been auto selected to match your Channel Islands postcode';
            ok = false;
          } else if (!val.match(matchit) && CIcountrySel.value == CIcheck.country) {
            CIcountrySel.value = CIcheck.notCI;
            errstr+= 'UK has been auto selected to match your none Channel Islands postcode';
            ok = false;
          }
        }
      }
    }

    var rex = new RegExp("(((http://|https://|ftp://|file://)|(www\.|ftp\.)))[-A-Z0-9+&@#/%=~_|$?!:,.]*[A-Z0-9+&@#/%=~_|$]", "i")
    var filt = val.match(rex);
    if (filt) { ok = false; errstr = 'Please remove the Web Site Address from the text.'; }
//    document.title = val + 'xx'+ filt;

    if (ele.tagName == 'INPUT' && ele.type.toUpperCase() == 'RADIO') {
      var radval = '';
      ok = true;
      var rads = ele.form.getElementsByTagName ('input');
      if (rads) {
        for (var i = 0; i < rads.length; ++i) {
          if (rads[i].type == 'radio' && rads[i].name == ele.name && rads[i].checked) {
            radval = rads[i].value;
          }
        }
      }
      if (radval == '') {
        ok = false; errstr = 'A value needs to be selected<br>';
      }
    }

    var bdrel = ele;
    var bckel = ele;
    // IE wont do select border so set the parents border instead
    if (ele.tagName == 'SELECT' || (ele.tagName == 'INPUT' && ele.type.toUpperCase() == 'RADIO')) {  bdrel = ele.parentNode; }
    if (ele.tagName == 'INPUT' && ele.type.toUpperCase() == 'RADIO') { bckel = ele.parentNode; }

    if (!ok) {
      if (ele.done != true) {
        ele.done = true;
        ele.oldbwid = cssStyle(bdrel,'borderTopWidth');
        ele.oldbstyle = cssStyle(bdrel,'borderTopStyle');
        ele.oldbcolor = cssStyle(bdrel,'borderTopColor');
//alert(bel.tagName+' '+bel.className+' '+ele.oldbcolor);
        ele.oldbgcolor = cssStyle(bckel,'backgroundColor');
        ele.oldbgimage = cssStyle(bckel,'backgroundImage');
        ele.oldcolor = cssStyle(ele,'color');
        var pos = getBounds(ele);
        if (ele.tagName == 'INPUT' && ele.type == 'radio') {
//alert(ele+' '+ele.id+ ' '+ele.tagName);
          bdrel.onkeyup = new Function("checkEle(this,1,'','ku')");
          bdrel.onmouseup = new Function("checkEle(this,1,'','mu')");
          bdrel.onchange = new Function("checkEle(this,1,'','ch')");
          bdrel.onblur = new Function("hideErr(this); checkEle(this,0,'','bl')");
          bdrel.onfocus = new Function("checkEle(this,1,'','fo')");
          if (!ele.id) { checkIDCounter++; ele.id = 'AutoGenId'+checkIDCounter; }
          bdrel.setAttribute('data-man-par',ele.id);

          // set up all the radio buttons
/*          var rads = ele.form.getElementsByTagName ('input');
          if (rads) {
            for (var i = 0; i < rads.length; ++i) {
              if (rads[i].type == 'radio' && rads[i].name == ele.name) {
                ele.onkeyup = new Function("checkEle(this,1,'','ku')");
                ele.onmouseup = new Function("checkEle(this,1,'','mu')");
                ele.onchange = new Function("checkEle(this,1,'','ch')");
                ele.onblur = new Function("hideErr(this); checkEle(this,0,'','bl')");
                ele.onfocus = new Function("checkEle(this,1,'','fo')");

                ele.setAttribute('data-man-par',ele.id);
              }
            }
          }
*/
        } else {
          if (typeof ele.onkeyup != 'function') {
            ele.onkeyup = new Function("checkEle(this,1,'ku')");
          } else {
            var oldfunc = tidyEvent(ele.onkeyup);
//alert(oldfunc);
            ele.onkeyup = new Function( oldfunc + "; checkEle(this,1,'ku')");
          }
//          ele.onkeyup = new Function("checkEle(this,1,'','ku')");
          ele.onchange = new Function("checkEle(this,1,'','ch')");
          if (typeof ele.onblur != 'function') {
            ele.onblur = new Function("hideErr(this); checkEle(this,2)");
          } else {
            var oldfunc = tidyEvent(ele.onblur);
//alert(oldfunc);
            ele.onblur = new Function(oldfunc + "; hideErr(this); checkEle(this,2)");
          }
//          ele.onblur = new Function("hideErr(this); checkEle(this,0,'','bl')");
          ele.onfocus = new Function("checkEle(this,1,'','fo')");
        }
      }
      ele.stat = errstr;
      bdrel.style.border = '1px ridge #f00';
      bckel.style.background = 'url(assets/images/redcross2.gif) right 2px no-repeat #fff';
      if (from == 1) {
        showErr(ele);
        checkErrVal = val;
        checkErrTimer = setTimeout( "checkErrOnTimer(this)", 1000 );
        checkErrEle = ele;
      }
    }
    else if (ele.done == true) {
      bdrel.style.border = ele.oldbwid + 'px ' + ele.oldbstyle + ' ' + ele.oldbcolor;
//alert(bel.tagName+' '+bel.style.border);
      bckel.style.backgroundImage = ele.oldbgimage;
      bckel.style.backgroundColor = ele.oldbgcolor;
      hideErr(ele);
    }
  }
// document.title = ele.id+' | '+man+' | '+src+' | '+val+' | '+radval+' | '+ok+' | '+from;
  return ok;
}
function checkData(form) {
  var ok = true;
  var goto = false;
  if (form) {
    checkDataGroupData.length = 0;
    var eles = form.elements;
    for (var i=0; i<eles.length; i++) {
      var ele = eles[i];
      var res = checkEle(ele, 0, form);
      if (!res) { ok = false; if (!goto) { goto = ele; } }
    }
  }
  if (!ok) { try {  goto.focus(); } catch(err) {};  }
  return ok;
}

function checkChars(ele) {
   var str = ele.value;
   var max = ele.getAttribute('maxlength');
   if (max) {
     var len = max -str.length;
     if (len>=0) {
       var el = document.getElementById('noChars'); if (el) { el.innerHTML = len; }
     } else {
        ele.value = str.substr(0, max)
     }
   }
   var max = ele.getAttribute('maxrows');
   if (max) {
     var rows = str.replace(/\r/g,'').split('\n');
     var rowc = rows.length + (rows[rows.length-1] == '' ? -1 : 0);
     var len = max - rowc;
     var el = document.getElementById('noRows'); if (el) { el.innerHTML = len; }
   }
}




//------------------------------------------------
// new stuff for popup mini basket
//------------------------------------------------

function seoName(s) {
   var res = trim(s);
   res = res.replace(/ /g,'-')
   res = res.replace(/&amp;/g,'')
   res = res.replace(/&/g,'')
   res = res.replace(/\//g,'-')
   res = res.replace(/\+/,'-')
   res = res.replace(/--/g,'-')
   res = res.replace(/---/g,'-')
   res = res.replace(/--/g,'-')
   res = res.replace(/\(/g,'')
   res = res.replace(/\)/g,'')
   res = res.replace(/\./g,'')
   res = res.replace(/\,/g,'')
   res = res.replace(/\:/g,'')
   res = res.replace(/\'/g,'')
   res = res.replace(/"/g,'')
   res = res.replace(/%/g,'')
   res = res.replace(/#/g,'')
   res = res.replace(/\*/g,'')
   res = res.replace(/’/g,'')
   res = res.replace(/‘/g,'')
   res = res.replace(/%2D/g,'-')
   return res;
}

function initBasketPopup(modal) {
// alert('initBasketPopup');
  var id = 'basketPopup';
  var div = createDynamicPopup(id,modal);
  var s = '';
// alert('vouc_data='+window.vouc_data);
  if (window.vouc_data && vouc_data.length > 0) {
    var el = document.getElementById('basketPopupLine_tmp');
    if (el) {
      var tmp = el.innerHTML;
      // remove <!-- and --> from around the template
      tmp = tmp.replace('<!--',''); //substring(4,tmp.length-3);
      tmp = tmp.replace('-->','');
      for (var i=0; i<vouc_data.length; i++) {
        var tmp1 = '';
        tmp1+=tmp;
        tmp1 = tmp1.replace(/[\<\[]xx_part[\>\]]/g, vouc_data[i].part);

        var major = (vouc_data[i].template2 ? vouc_data[i].template2 : vouc_data[i].major);
        tmp1 = tmp1.replace(/<xx_partcolour>/g, vouc_data[i].partcolour ? vouc_data[i].partcolour  : major);
        tmp1 = tmp1.replace(/<xx_major>/g, major);

        tmp1 = tmp1.replace(/[\<\[]xx_part_link[\>\]]/g, (vouc_data[i].major ? vouc_data[i].major : vouc_data[i].part));
        tmp1 = tmp1.replace(/[\<\[]xx_descr[\>\]]/g, vouc_data[i].descr);
        tmp1 = tmp1.replace(/[\<\[]xx_descr_link[\>\]]/g, seoName(vouc_data[i].descr));
        tmp1 = tmp1.replace(/[\<\[]xx_qty[\>\]]/g, vouc_data[i].qty);
        tmp1 = tmp1.replace(/[\<\[]xx_price[\>\]]/g, vouc_data_curr+vouc_data[i].total);
        s+= tmp1;
      }
    }
  }
  var t = div.innerHTML;
//alert(t);
  t = t.replace(/<!--rows_go_here-->/i,s);
//alert(t);
  div.innerHTML = t;
// alert(div.innerHTML);
  return div;
}
function initBasketPopup(modal) {
  var id = 'basketPopup';
  var div = document.getElementById(id);
  if (!div || !window.vouc_data) { return false; }

  var div = createDynamicPopup(id,modal);
  var s = '';
  if (vouc_data.length > 0) {
    var el = document.getElementById('basketPopupLine_tmp');
    if (el) {
      var tmp = el.innerHTML;
      // remove <!-- and --> from around the template
      tmp = tmp.replace('<!--',''); //substring(4,tmp.length-3);
      tmp = tmp.replace('-->','');
      for (var i=0; i<vouc_data.length; i++) {
        var tmp1 = '';
        tmp1+=tmp;
        tmp1 = tmp1.replace(/[\<\[]xx_part[\>\]]/g, vouc_data[i].part);

        var major = (vouc_data[i].template2 ? vouc_data[i].template2 : vouc_data[i].major);
        tmp1 = tmp1.replace(/<xx_partcolour>/g, vouc_data[i].partcolour ? vouc_data[i].partcolour  : major);
        tmp1 = tmp1.replace(/<xx_major>/g, major);

        tmp1 = tmp1.replace(/[\<\[]xx_part_link[\>\]]/g, (vouc_data[i].major ? vouc_data[i].major : vouc_data[i].part));
        tmp1 = tmp1.replace(/[\<\[]xx_descr[\>\]]/g, vouc_data[i].descr);
        tmp1 = tmp1.replace(/[\<\[]xx_descr_link[\>\]]/g, seoName(vouc_data[i].descr));
        tmp1 = tmp1.replace(/[\<\[]xx_qty[\>\]]/g, vouc_data[i].qty);
        tmp1 = tmp1.replace(/[\<\[]xx_price[\>\]]/g, vouc_data_curr+vouc_data[i].total);
        s+= tmp1;
      }
    }
  }
  var t = div.innerHTML;
  t = t.replace(/<!--rows_go_here-->/i,s);
  div.innerHTML = t;
  return div;
}
var c = 0;
//--------------------------------------
function onOpenBasketPopupTimer() {
// alert('onOpenBasketPopupTimer');
  showBasketPopupReal(null, openBasketEle)
}
function showBasketPopup(event, ele) {
//alert(ele);
  clearTimeout(openBasketPopupTimer);
  clearTimeout(closeBasketPopupTimer);
  openBasketEle = ele;
  openBasketPopupTimer = setTimeout( 'onOpenBasketPopupTimer()', 300 );
}
function showBasketPopupReal(event, ele) {
// alert('showBasketPopupReal');
  clearTimeout(openBasketPopupTimer);
  clearTimeout(closeBasketPopupTimer);
  if (basketPopupAborted) { return }

  var div = document.getElementById('basketPopup');
  if (div && div.style.display == 'block') { return } // stop repeated firing of mouseover being a problem

  var div = initBasketPopup();
  if (div) {
    c++;
    popupInit(hideBasketPopupReal,'poo');

    var els = document.getElementById('basketPopupScroll');
    if (els) {}
    else {return;}
    els.style.height = 'auto';
    els.style.overflow = 'visible';

    div.style.left = '-10000px';  // create it off screen so i can make it visible to find its size
    div.style.overflow = 'visible';
    div.style.display='block';
    var xy = getBounds(ele);
//document.title = xy.x+' '+xy.y+' '+xy.w+' '+xy.h;
    y = yOnPage(xy.y+xy.h,0);
    x = xOnPage(xy.x+xy.w-div.offsetWidth,div.offsetWidth)+10;

    var exy = getBounds(div);
    var sxy = screenSize();
    if (y > sxy.y + sxy.h - exy.h) {
      els.style.overflow = 'auto';
      var h = sxy.y + sxy.h - y - 35;
      if (h < 20) { h = 20; }
      els.style.height = h + 'px';
    }

    div.style.top = y + 'px';
    div.style.left = x + 'px';
    div.trueleft = x;
    hideSelects();

    div.onmouseover = new Function("keepBasketPopup();");
    div.onmouseout = new Function("hideBasketPopup();");
    rolldown(div);
  }
}
//--------------------------------------
var openBasketPopupTimer = null;
var openBasketEle = null;
var closeBasketPopupTimer = null;
var basketPopupAborted = false;
function hideBasketPopupReal(ss) {
// alert('hideBasketPopupReal');
  var id = document.getElementById('basketPopup');
//  if (id) { id.style.display='none'; showSelects(); }
  if (id) { rollup(id, showSelects); }

}
function onCloseBasketPopupTimer() {
  clearTimeout(closeBasketPopupTimer);
  closeBasketPopupTimer = null;
  popupClose('','');
}
function hideBasketPopup(e) {
//  e = e || window.event; // make sure IE has the event in e
//alert(popupInDiv(e,'miniBasketMain',true)+'xx'+popupInDiv(e,'basketPopup',true)+'yy'+(!popupInDiv(e,'miniBasketMain',true) && !popupInDiv(e,'basketPopup',true)));
//  if (!popupInDiv(e,'miniBasketMain',true) && !popupInDiv(e,'basketPopup',true)) {
    clearTimeout(openBasketPopupTimer);
    closeBasketPopupTimer = setTimeout( 'onCloseBasketPopupTimer()', 500 );
//  }
}
function keepBasketPopup() {
  clearTimeout(closeBasketPopupTimer);
}
function hideBasketPopup_CO(event,miniBasketEle) {
  // called when mini basket is clicked to go to checkout
  basketPopupAborted = true;
  popupClose('','');
  if (miniBasketEle) {
    miniBasketEle.className = miniBasketEle.className + ' clicked';
  }
}
function transitionStop(el) {
  if (el && el.trans) { el.trans.finish(); }
}
function transition(from, tooo, param) {
  var i_trans = new c_trans(from, tooo, param);
}
//var ctc = 0;
function c_trans(from, tooo, param) {
//from:  { id:id, el:element, x:left, y:top, w:width, h:height }
//tooo:  { id:id, el:element, x:left, y:top, w:width, h:height }
//param  { classname:'abc', speed:##, movediv:'Y', grow:'Y', vanish:'Y', hide:'Y', onend:funcname } NOTE ALL FIELD NAMES ARE LOWERCASE
// speed is approx time the transition should take in millisecs, note IE is a bit slow
// vanish:'Y' overrides the tooo size/position so it ends up as 10x10 box in the center of tooo.id
// grow='Y' auto calculates the from position to be a 10x10 box in the center of tooo.id
//     - specify x,y,w,h in from to override the 10x10 centred start position
// movediv:'Y' will move the actual div passed as 'from'
// hide:'Y' will hide the div at the end and move it back to its original position and size Only works if movediv is used
// onend : pass it a function to call when the transition is complete - format: function(div) where div will be the 'from' div
// focus : will set focus to the passed id after the onend has been called
// note, pass a div or el as from if you need to access the div in the onend function

   c_trans.prototype.die = function() {
     clearTimeout(this.timer);
     if (this.from.el && this.from.el.trans) { this.from.el.trans = null; }

     if (!this.param.movediv) {
       this.div.style.display = 'none';
       var elp = this.div.parentNode;
       if (elp) { elp.removeChild(this.div); }
     }
     else if (this.param.hide) {
       this.div.style.display = 'none';
//       ctc++;
//document.title = 'xxposf'+ctc+' '+this.posf.x+' '+this.posf.y+' '+this.posf.w+' '+this.posf.h
       if (this.inited && this.posf.w > 0) {
         // put it back in its original position
         this.div.style.top = this.posf.y + 'px';
         this.div.style.left = this.posf.x + 'px';
         this.div.style.width = this.posf.w + 'px';
         this.div.style.height = this.posf.h + 'px';
       }
     }
   }

   c_trans.prototype.finish = function() {
     if (this.from.el && this.from.el.offsetLeft < -1500) { this.from.el.style.left = this.post.x + 'px'; }
     this.die();
     if (this.param.onend) { this.param.onend(this.from.el); }
     if (this.param.focus) { var el = document.getElementById(this.param.focus); if (el) { el.focus(); } }
     this.destroy;
   }

   c_trans.prototype.onTimer = function() {
     try {
       this.count++;
       if (this.count <= this.maxCount) {
         if (this.loops[this.loop] == 'wh' || this.loops[this.loop] == 'w') {
           this.pos.x = this.pos.x + this.xstep;
           this.pos.w = this.pos.w - this.wstep;
         }

         if (this.loops[this.loop] == 'wh' || this.loops[this.loop] == 'h') {
           this.pos.y = this.pos.y + this.ystep;
           this.pos.h = this.pos.h - this.hstep;
         }

         if (this.loops[this.loop] == 'fi') {
           this.opacity += this.ostep;
           this.div.style.opacity = this.opacity / 100;
           this.div.style.filter = "alpha(opacity=" + Math.round(this.opacity) + ")";
         }

         this.div.style.top = Math.round(this.pos.y) + 'px';
         this.div.style.left= Math.round(this.pos.x) + 'px';
         this.div.style.width = Math.round(this.pos.w) + 'px';
         this.div.style.height = Math.round(this.pos.h) + 'px';
       }
//document.title = 'pos '+this.pos.x+' '+this.pos.y+' '+this.pos.w+' '+this.pos.h
       if (this.count <= this.maxCount+1) {
         if (this.count > this.maxCount && this.loop < this.loops.length-1)
         {
           this.loop++;  this.count = 0;
         }
         this.timer = setTimeout( ( function ( obj ) { return function () { obj.onTimer( ); }; } )( this ), tinc );
       } else {
  //     this.div.style.zIndex = 100;
  //alert('trans width='+this.div.offsetWidth+' '+this.div.pos.w+' '+this.div.opos.w+' '+this.wstep);
         this.finish();
       }
     }
     catch(err)
     {}
   }

   var copyof = function(x) { var ret = {}; for (var i in x) { ret[i] = x[i]; } return ret; }
   var exists = function(val) { return val != undefined; }

   c_trans.prototype.init = function() {
     this.posf = { x:0, y:0, w:10, h:10 }
     this.post = { x:100, y:100, w:10, h:10 }

     if (exists(this.from.el)) { this.elf = this.from.el; this.posf = getBounds(this.elf); }
     if (exists(this.from.id)) { this.elf = document.getElementById(this.from.id); this.posf = getBounds(this.elf); this.from.el = this.elf; }
     if (exists(this.from.x)) { this.posf.x = this.from.x; }
     if (exists(this.from.y)) { this.posf.y = this.from.y; }
     if (exists(this.from.w)) { this.posf.w = this.from.w; }
     if (exists(this.from.h)) { this.posf.h = this.from.h; }
     if (this.from.el) { this.from.el.trans = this; }
//for (var xxx in posf) { alert(xxx + ' = ' + posf[xxx]) }

     if (exists(this.to.el)) { this.elt = this.to.el; this.post = getBounds(this.elt); }
     if (exists(this.to.id)) { this.elt = document.getElementById(this.to.id); this.post = getBounds(this.elt); this.to.el = this.elt; }
     if (exists(this.to.x)) { this.post.x = this.to.x; }
     if (exists(this.to.y)) { this.post.y = this.to.y; }
     if (exists(this.to.w)) { this.post.w = this.to.w; }
     if (exists(this.to.h)) { this.post.h = this.to.h; }
     if (this.to.el) { this.to.el.trans = this; }
//for (var xxx in post) { alert(xxx + ' = ' + post[xxx]) }

     var hmin = (document.documentElement.scrollTop ? document.documentElement.scrollTop : (window.pageYOffset ? window.pageYOffset : 0));
     if (typeof(hmin) != 'number' || hmin < 0) { hmin = 0; }
     var fixed = (cssStyle(this.from.el,'position') == 'fixed' && !isIE6());
//alert(fixed);
     if (fixed) { this.post.y += hmin;  this.posf.y += hmin; }

     if (this.posf && this.post) {
       if (this.param.movediv) {
         this.div = this.elf;
       } else {
         this.div = createDynamicPopup('trans_div'+c_trans.divno);
         c_trans.divno++;
         if (this.from.el) { this.from.el.style.left = '-10000px'; }
       }
       this.div.style.position = 'absolute';
       if (!this.param.movediv) {
         if (this.param.classname)
           { this.div.className = this.param.classname; }
         else
           { this.div.style.background = 'white'; this.div.style.border = '1px solid red'; }
       }

       if (this.loops[0] == 'fi') {
         this.div.style.opacity = this.opacity / 100;
         this.div.style.filter = "alpha(opacity=" + this.opacity + ")";
       }

       var wfix = wborder(this.div);
       this.posf.w -= (wfix);
       this.post.w -= (wfix);

       var hfix = hborder(this.div);
       this.posf.h -= (hfix);
       this.post.h -= (hfix);

       if (this.posf.w < 0) { this.posf.w = 0; }
       if (this.posf.h < 0) { this.posf.h = 0; }

       if (this.param.grow) {
         // default is grow from 10x10 centered on 'to' but can be overridden by setting the 'from' x,y,w,h
         if (this.from.w == undefined) { this.posf.w = 10; }
         if (this.from.x == undefined) { this.posf.x = Math.round(this.post.x + (this.post.w/2)-(this.posf.w/2)); }
         if (this.from.h == undefined) { this.posf.h = 10; }
         if (this.from.y == undefined) { this.posf.y = Math.round(this.post.y + (this.post.h/2)-(this.posf.h/2)); }
       }
//for (var xxx in posf) { alert(xxx + ' = ' + posf[xxx]) }

       if (this.param.vanish) {  // shrink to 10x10 centered on 'to'
         this.post.x = Math.round(this.post.x + (this.post.w/2)-5); this.post.w = 10;
         this.post.y = Math.round(this.post.y + (this.post.h/2)-5); this.post.h = 10;
       }

//ctc++;
//document.title = 'posf'+ctc+' '+this.posf.x+' '+this.posf.y+' '+this.posf.w+' '+this.posf.h+' post '+this.post.x+' '+this.post.y+' '+this.post.w+' '+this.post.h+' '+this.div.style.display;
       // something was causing a call with posf bits = 0 when the minibasket and lightbox were showing which screws up future calls
       if (this.posf.x == 0 && this.posf.y == 0 && this.posf.w == 0 && this.posf.h == 0) {
         this.finish();
         return;
       }

       this.div.style.top = this.posf.y + 'px';
       this.div.style.left = this.posf.x + 'px';
       this.div.style.width = this.posf.w + 'px';
       this.div.style.height = this.posf.h + 'px';
       this.pos = copyof(this.posf);
       this.div.style.display = 'block';
       this.xdiff = (this.posf.x - this.post.x);
       this.ydiff = (this.posf.y - this.post.y);
       this.wdiff = (this.posf.w - this.post.w);
       this.hdiff = (this.posf.h - this.post.h);

       this.maxCount = Math.round(this.param.speed / ((tinc + 100) * this.loops.length)) + 1;
       this.xstep = -this.xdiff / this.maxCount;
       this.ystep = -this.ydiff / this.maxCount;
       this.wstep = this.wdiff / this.maxCount;
       this.hstep = this.hdiff / this.maxCount;

       if (this.loops[0] == 'fi') {
         tinc = 50;
         this.maxCount = this.param.speed / (tinc + 20);
         this.ostep = 80 / this.maxCount;
       }
//alert('posf '+posf.x+' '+posf.y+' '+posf.w+' '+posf.h+' post '+post.x+' '+post.y+' '+post.w+' '+post.h+' '+this.div.style.display);
//document.title = 'posf '+this.posf.x+' '+this.posf.y+' '+this.posf.w+' '+this.posf.h+' post '+this.post.x+' '+this.post.y+' '+this.post.w+' '+this.post.h+' '+this.div.style.display;

       this.count = 0;
       this.inited = true;
       this.timer = setTimeout( ( function ( obj ) { return function () { obj.onTimer( ); }; } )( this ), 1 );
     }
   }

  var tinc = 33;
  this.inited = false;
  this.from = from;
  this.to = tooo;
  this.param = param;
//for (var xxx in param) { alert(xxx + ' = ' + param[xxx]) }

  this.loops = new Array;
  this.loop = 0;
  if (this.param.action == undefined)
    { this.loops[0] = 'wh'; }
  else
    { this.loops = this.param.action.split(',');
  }
  this.opacity = 20;
  if (this.param.speed == undefined) { this.param.speed = 20; }
  if (this.param.movediv == undefined) { this.param.movediv = ''; }
  if (this.param.classname == undefined) { this.param.classname = ''; }
  if (this.param.onend == undefined) { this.param.onend = ''; }
  if (this.param.hide == undefined) { this.param.hide = ''; }
  if (this.param.focus == undefined) { this.param.focus = ''; }

  this.init();
}
c_trans.divno = 0;
// ---------
function rolldown(div) {
  if (typeof(div) == 'string') { div = document.getElementById(div); }
  if (div) {
    var left = div.trueleft ? div.trueleft-0 : div.offsetLeft-0;
    var from = { el:div, x:left, y:div.offsetTop, w:div.offsetWidth, h:1 };
    var too = { x:left, y:div.offsetTop, w:div.offsetWidth, h:div.offsetHeight };
    div.style.display = 'none';
    div.style.overflow = 'hidden';
    transition( from, too, { speed:500, action:'h', movediv:'Y' } );
  }
}

function rollup(div, endfunc) {
  // div must be fixed size, set in css
  if (typeof(div) == 'string') { div = document.getElementById(div); }
  if (div) {
    var from = { el:div, x:div.offsetLeft, y:div.offsetTop, w:div.offsetWidth, h:div.offsetHeight };
    var too = { x:div.offsetLeft, y:div.offsetTop, w:div.offsetWidth, h:0 };
    transition( from, too, { speed:500, action:'h', movediv:'Y', hide:'Y', onend:endfunc } );
  }
}

function wborder(el) {
// returns the padding and border width for el's style
  return (cssStyle(el,'borderLeftWidth')-0) + (cssStyle(el,'borderRightWidth')-0) +
         (cssStyle(el,'paddingLeft')-0) + (cssStyle(el,'paddingRight')-0);
}
function hborder(el) {
// returns the padding and border width for el's style
  return (cssStyle(el,'borderTopWidth')-0) + (cssStyle(el,'borderBottomWidth')-0) +
         (cssStyle(el,'paddingTop')-0) + (cssStyle(el,'paddingBottom')-0);
}


function createDynamicPopup(id, modal, style, parent ) {
// alert('createDynamicPopup - '+id+' - '+modal+' - '+style+' - '+parent);
  if (modal) { var cover = createDynamicPopup('modalCover');  setZIndex(cover); lastCoverZindex = globZindex; }

//  var div = document.getElementById(id);
// 	if (div) { div.parentNode.removeChild(div);

  var div = document.getElementById(id);
// alert(div);
  if (!div) {
    var div = document.createElement('div');
// alert(div);
    div.setAttribute('id', id);
    div.setAttribute('name', id);
    div.setAttribute('z-index', globZindex);
    if (style) { div.setAttribute('className',style); }
    if (style) { div.setAttribute('class',style); }
    if (typeof(parent) == 'string' && parent) { parent = document.getElementById(parent); }
    if (!parent || parent == undefined) { parent = document.body }
    parent.appendChild(div);
  }
  div.style.display = 'none';
//  div.style.display = 'block';
  setZIndex(div)
  return div;
}
var globZindex = 7000;
function setZIndex(el) {
  globZindex++;
  el.style.zIndex = globZindex;
}

//--------------------------------------
// popup.... are routines to use if you want a mouse listener and optional hotspot.
// use: call popupInit(closefunc, hotid) at the start of your popup show function and pass it your hide/close function.
// hotId is the id of the click-to-close area - pass '' for anywhere on the page or !divid to close anywhere EXCEPT divid.
// If you want to manually close the popup, call popupClose('','myresult') NOT your hide/close function
// 'myresult' will be put in global var popupResult so you can control what to do in the hide/close function
var popupSafeToClose = false;
var popupOMD = null;
var popupDiv = '';
var popupCloseFunc = null;
var popupResult = '';
var popupClosing = false;
var popupPending = null;
var popupClosedTime = 0;
//
function popupInit(closeFunc, hotId) {
  if (popupClosing) { return false;  }
  popupPending = null;
  // tidy up any open popup
  if (popupSafeToClose) { popupRemoveListener(); if (popupCloseFunc) { popupCloseFunc();} popupCloseFunc = null;  popupSafeToClose = false; }
  // prep the listener for the new popup
  popupCloseFunc = closeFunc;  popupDiv = hotId;  popupAttachListener();  hideSelects();  popupSafeToClose = true;
  return true;
}
//
function popupClose(e,closeResult) {
  if (popupSafeToClose) {
    if (e == undefined) var e = window.event; // make sure IE has the event in e
    if (e && e.button && e.button == 2) return;
    if (popupDiv.match('!')) { var pd = popupDiv.substring(1,100); var inpd = false; } else { var pd = popupDiv; var inpd = true; }
    if (pd == '' || (pd != '' && (e == '' || e == 'timer' || (popupInDiv(e,pd,inpd))))) {
      popupClosing = true;
      popupResult = (closeResult==undefined ? null : closeResult);
//      popupResult = ((closeResult == '') || (closeResult==null) || (closeResult==undefined) ? '' : closeResult);
      popupRemoveListener();
      popupSafeToClose = false;
      if (popupCloseFunc) {
         popupCloseFunc();
      }
      popupCloseFunc = null;
      showSelects();
      popupClosing = false;
      popupClosedTime = Date.parse(new Date());
      if (popupPending) { popupPending(); popupPending = null; }
    }
  }
}
function popupJustClosed() {
  var now = Date.parse(new Date());
//  alert(now+' '+popupClosedTime);
  var i = Math.abs(now - popupClosedTime);
//  alert(i);
  popupClosedTime = 0;
  return (i < 100);
}
//
function popupAttachListener() {
   	if (document.layers) {	document.captureEvents(Event.MOUSEDOWN);	}
   	popupOMD = document.onmousedown;
   	if (popupOMD != null) {	document.onmousedown = function(event) { popupOMD(event); popupClose(event); } }
    else { document.onmousedown = function(event) { popupClose(event); } }
}
//
function popupRemoveListener() {
   	if (popupOMD != null) {	document.onmousedown = popupOMD; } else { document.onmousedown = null; }
}
//
function popupInDiv(e, divID, testbool) {
  if (!e) var e = window.event; // make sure IE has the event in e
  if (!divID) { divID = popupDiv; }
  if (document.layers) {
			var clickX = e.pageX;
			var clickY = e.pageY;
			var t = document.layers[divID];
			if ((clickX > t.left) && (clickX < t.left+t.clip.width) && (clickY > t.top) && (clickY < t.top+t.clip.height)) {
				return testbool;
			}
		}
		else if (e && e.srcElement) {
			var t = e.srcElement;
			while (t && t.parentElement != null) {
//alert(t.ID+' '+divID+' '+testbool);
				if (t.id==divID) {	return testbool; }
				t = t.parentElement;
			}
		}
		else if (e && e.target) {
			var t = e.target;

//   try { if (t.id) {} } // will get error here if firefox and input box is clicked on - mar 2010
//   catch(errr) { alert('err: '+errr); return !testbool;}

   try {
   		while (t && (t.parentNode != null) && (t.parentNode != undefined) && (t.attributes)) {
   				if (t.id==divID) { return testbool; }
 	  			t = t.parentNode;
 	  	}
  	}
   catch(err)
   { alert('error: '+err.description);}
		}
		return !testbool;
}


//
//  stuff for tpye-ahead search
//
var searchBox = null;  // pointer to the searchbox element
var searchhttp=null;
var searchedValue = '';
var badValue = '';
var typeAheadLive=true;

function stopTypeAhead() {
  typeAheadLive = false;
  if (window.typeAheadPopup) { typeAheadPopup.style.display = 'none'; }
}

function startTypeAhead() {
  typeAheadLive = true;
}

function hideSuggestions() {
  popupClose('','');
}
function hideSuggestionsCore() {
  var id = document.getElementById('suggestionBox');
  if (id) { id.style.display='none'; showSelects(); }
  searchedValue = '';
//  hideShadowBox();
}

function getSearchRes() {
  if (!typeAheadLive) { return; }
  if(searchhttp.readyState==4 && searchhttp.status==200) {
    res = searchhttp.responseText;
    if (res) {
      var aa ='';
      var pts = res.split('|');
      for (var i=0; i<pts.length; i++) {
        if (trim(pts[i])) {
          var pt = pts[i].split('\\');
          f=searchedValue;
          var s1 = (pt[2] ? pt[2] : 'products');
          var L_descr = pt[1].toLowerCase();
          var L_f = f.toLowerCase(f);
          var p = L_descr.indexOf(L_f);
          var s = pt[1].substr(p,searchedValue.length);
          var d='<span class="match">'+s+'</span>';
          pt[1]=pt[1].replace(new RegExp(searchedValue,"ig"),d)
          aa = aa+'<li><a id=item'+i+' href="'+thisUrl.replace('https:','http:')+'sp'+delim404+s1+delim404+pt[0]+'?tyah=y" onclick="popupClose(\'\',\'\');">'+pt[1]+'</a></li>';
        }
      }
    }
    if (!aa) {
//      a='no suggestions - try again.';
      a = '';
      badValue = searchedValue;
    } else {
      a = '<ul>'+'<li>Suggested products – hit enter for more results</li>'+aa+'</ul>';
      badValue = '';
    }
    if (a!='') showSuggestions(a);
  }
}

function showSuggestions(a) {
  var id = 'suggestionBox';
  var div = document.getElementById(id);
  if (!div) {
    div = createDynamicPopup(id,false);
    div.innerHTML+='<div id="sresults" class="ta" name="suggestionresults"></div>';
  }
  popupInit(hideSuggestionsCore,'!suggestionBox');
 // put the shadow png around the box
//  a = '<div id="suggestionT"><!--xx--></div><div id="suggestionM">' + a + '</div><div id="suggestionB"><!--xx--></div>';
  a = '<table cellspacing="0" cellpadding="0" border="0"><tr><td class="tl" style="background-position: 0 0;">'+a;
  a+= '</td><td class="tr" style="background-position: right 0;">&nbsp;<!--x--></td></tr><tr><td class="bot" style=" background-position: left bottom;" ><!--x--></td><td class="bot" style=" background-position: right bottom;"><!--x--></td></tr></table>';

  el = document.getElementById('sresults');
  el.innerHTML = a;
//alert(el);

  div.style.display='block';
  var xy = getBounds(searchBoxId);
  y = yOnPage(xy.y+xy.h+4,div.offsetHeight);
  x = xOnPage(xy.x,div.offsetWidth);
  div.style.top = y + 'px';
  div.style.left = x + 'px';
//alert(div.innerHTML);
  hideSelects();
//  showShadowBox(div);
}

function getSuggestions() {
  try {   // The following "try" blocks get the XMLHTTP object for various browsers…
     searchhttp = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
    try {
      searchhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e2) {
      // This block handles Mozilla/Firefox browsers...
      try {
        searchhttp = new XMLHttpRequest();
      } catch (e3) {
        searchhttp = false;
      }
    }
  }
  if(searchhttp!=null) {
    var fixer = new Date();
    searchhttp.open("GET",thisUrl+"typeAhead.asp?searchwhat="+searchedValue+'&when='+fixer.getTime(),true);
    searchhttp.onreadystatechange=function(){ getSearchRes(); };
    searchhttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2005 00:00:00 GMT");
    searchhttp.send(null)
  }
}

function doSearch(c) {
  if (!typeAheadLive) { return }
  var dv = searchBox.getAttribute('data-def-value');
  if (dv && dv == searchBox.value) { searchBox.value = ''; return; }
  var a = trim(searchBox.value);
  if (!a) { hideSuggestions(); searchedValue = ''; return }
  if (searchedValue != a) {
    searchedValue = a;
//    if (badValue == '' || searchedValue.indexOf(badValue) != 0) {
    badValue = '';
    getSuggestions();
//    }
  }
  return
}

function searchSuggKeyDown(c) {
  c = c || window.event;
  var a = (c.keyCode ? c.keyCode : c.which);
  if (a==191) { if (window.event) { event.returnValue = false; } return false; } // ? mark
  return true
}

function initSearchBox() {
  window.focus();
  searchBox = document.getElementById(searchBoxId);
  if (searchBox) {
//		searchBox.onkeypress = function(c) { return editKeyPress(c)};
    searchBox.onkeyup = function(c) { return doSearch(c) };
    searchBox.onfocus = function(c) { return doSearch(c) };
    searchBox.onclick = function(c) { return doSearch(c) };
    searchBox.onkeydown = function(c) { return searchSuggKeyDown(c) };
  }
}

function getBounds(ele) {
  var res = { x:0, y:0, w:0, h:0 }
  if (typeof(ele) == 'string') { var el = document.getElementById(ele); } else { var el = ele; }
  if (el) {
    res.x = el.offsetLeft; res.y = el.offsetTop;  res.h = el.offsetHeight;  res.w = el.offsetWidth;
    while((el=el.offsetParent) != null) {
      res.x += el.offsetLeft+(el.clientLeft ? el.clientLeft : 0);
      res.y += el.offsetTop+(el.clientTop ? el.clientTop : 0);
    }
  }
  return res;
}

function xOnPage(x,w,centerIt,ele,fixed) {
  var sw = -1;
  if (self.innerWidth){sw = self.innerWidth;}
  else if (document.documentElement && document.documentElement.clientWidth){sw = document.documentElement.clientWidth;}
  else if (document.body){sw = document.body.clientWidth;}
  var wmin = (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : (window.pageXOffset ? window.pageXOffset : 0));
  if (typeof(wmin) != 'number' || wmin < 0) { wmin = 0; }
  if (isIE6()) { fixed = false; }
  if (fixed) { wmin = 0; }
  var sw = sw + wmin;
  if (centerIt) { x = (Math.round((sw - wmin - w) / 2)) + wmin; }
  if ((sw > -1)) {	if (x<0) { x=0; }		if ((x + w) > sw - 10) {	x = sw - w - 10;	} }
  if (x < wmin) { x = wmin; }
  if (ele && w > sw) { ele.style.width = sw-10+'px'; }
  return x;
}

function yOnPage(y,h,centerIt,ele,fixed) { // pass ele to make sure max height is not exceeded
  var sh = -1;
  if (self.innerHeight){sh = self.innerHeight;}
  else if (document.documentElement && document.documentElement.clientHeight){sh = document.documentElement.clientHeight;}
  else if (document.body){sh = document.body.clientHeight;}
  var hmin = (document.documentElement.scrollTop ? document.documentElement.scrollTop : (window.pageYOffset ? window.pageYOffset : 0));
  if (typeof(hmin) != 'number' || hmin < 0) { hmin = 0; }
//alert(hmin+'|'+sh);
  if (isIE6()) { fixed = false; }
  if (fixed) { hmin = 0; }
  var sh = sh + hmin;
  if (centerIt) { y = (Math.round((sh - hmin - h) / 2)) + hmin; }
  if ((sh > -1)) {	if (y<0) { y=0; }		if ((y + h) > sh - 10) {	y = sh - h - 10 ; } }
  if (y < hmin) { y = hmin; }
//alert(ele.offsetHeight+' '+h+' '+sh);
  if (ele && h > sh) { ele.style.height = sh-6+'px'; }
  return y;
}

function doCustomSelects() {
// call a timer in case other things that create selects are also on a timer
  setTimeout(new Function("doCustomSelects_c()") ,1);
}

function doCustomSelects_c() {
  var sels = document.getElementsByTagName('select');
  if (sels) {
    for (var i = 0; i < sels.length; ++i) {
      var xx = sels[i].getAttribute('data-custom');
      if (customSelectDoAll && xx == null) { xx = ''; }
      if (xx !=  null) {
        var ele = sels[i];
        var yy = sels[i].getAttribute('data-img-path');
        sels[i].imgpath = (yy ? yy : '');
        var yy = sels[i].getAttribute('data-img-ext');
        sels[i].imgext = (yy ? yy : '.gif');
        // the code expects css to exist for cSelBack_xx and cSelInput_xx
        ele.style.display = 'none';
        if (!ele.id) { csel_id++; ele.id = 'csel_'+csel_id; }
        if (ele.id == 'title') { csel_id++; ele.id = ele.id + csel_id; }
        var id = ele.id;

        if (ele.dropped == undefined) {  // dont add another if this function is called a second time
          var divn=document.createElement('div');
          divn.id=id+'div';
          divn.onclick = new Function('cselDD(\''+id+'\',\''+xx+'\'); return false;');
          divn.className = 'cSelBack_'+xx;

          var txt = (ele.options.length > 0 && ele.selectedIndex > -1) ? ele.options[ele.selectedIndex].text : '';
          var html = '';
          html += '<div class="cSelBtn_'+xx+'" id="'+id+'btn">&nbsp;</div>';
          html += '<div class="cSelImg_'+xx+'" id="'+id+'img" >';
          html += '<input type="text" class="cSelInput_'+xx+'" id="'+id+'inp" value="'+txt+'" readonly onkeydown="cselKD(event,\''+id+'\')" />';
          html += '</div>';
          html += '';
          divn.innerHTML = html;

          ele.dropped = false;
          ele.parentNode.insertBefore(divn,ele);
        }

        var div = document.getElementById(id+'div');
        var d = getBounds(div);
        var dw = wborder(div);

        // if the original select is not visible d.w will be 0.
        // You may need to re-call this function if it is made visible later
        if (d.w > 0) {
          var btn = document.getElementById(id+'btn');
          var b = getBounds(btn);
          var img = document.getElementById(id+'img');
          var iw = wborder(img);
          img.style.width = (d.w - dw - b.w - iw-1)+'px';
          var inp = document.getElementById(id+'inp');
          var ew = wborder(inp);
          inp.style.width = (d.w - dw - b.w - iw - ew- 1) + 'px';
          inp.onfocus = ele.onfocus;
          inp.onblur = ele.onblur;
          bgi = cssStyle(div,'backgroundImage');
          if (bgi && bgi != 'none') { // it has a background image so remove the selectborder border if there is one
            var par = ele.parentNode;
//std50Border
            if (par && par.className.match(/selectborder/ig)) {par.style.border = '0px solid red'; par.style.width = '100%' }
          }
        }
        selectRefresh(ele,'draw');
      }
    }
  }
}

function setBackImage(x) {
    if (x==undefined) {x=0;}
    var z = x;
    if (window.json_images && json_images.length > 0) {
       if (!isNumeric(x)) {
    	   for (var i=0; i<=json_images.length-1; i++) {
    	      if (json_images[i].part==z) {x=i;}
    	   }
       }
    }
	el = document.getElementById('productBack')
	if (el) {
      el.style.display = 'block';
	   if (json_images[x].back=='no') {el.style.display = 'none';}
	}
	if (window.imageFront) {imageFront();}
}

// switch on intellisense (search drop down) by calling initSearchBox()
var searchBoxId = 'searchwhat';  // the id of the search input box
addLoadEvent(initSearchBox);
//addLoadEvent(doCustomSelects,true); // get it done as early as possible
addLoadEvent(doCustomSelects,'last');  // do it again incase new selectors have been created
//stopRightClick();
//addLoadEvent(templateSwitch);
addLoadEvent(preLoad);
//addLoadEvent(setHeight);
addLoadEvent(setBackImage);

