//-------------------------------------------------------------------------
//  AJAX buy stuff
//-------------------------------------------------------------------------
var res = '';
var lightBoxTimeOut = 2000;  // milliseconds
var xpart;
var lbDiv = null;
var lbLocation = '';
var timer1 = null;
var listenerDone = false;
var safetoclose = false;
var oneclick = 0;
var oneclicktimer = null;
var lbError = false;
var ajaxRefresh = '';
var BUY_http = null;
var matrixPopupId = '';
var matrixAjaxRefresh = '';
var voucherLineNo = '';
var voucherName = '';
var voucherType = '';
var verb1 = 'Adding';
var verb2 = 'Added';
var verb3 = 'to';

function startOneClick() {  clearTimeout(oneclicktimer); oneclick = 1; oneclicktimer = window.setTimeout("stopOneClick", 3000); }
function stopOneClick() {  clearTimeout(oneclicktimer); oneclick = 0; }

function timer1timer() {
  clearTimeout(timer1);
  popupClose('timer');
}
//
function lightBoxClose() {
//alert(ajaxRefresh+'|'+lbLocation);
  hideShadowBox();
  if (!lbError)
    { transition( {el:lbDiv }, { id:'ajaxBasket'}, { speed:700, classname:'lightBoxC', vanish:'Y', movediv:'Y', hide:'Y' } ); }
  else
    { lbDiv.style.display='none'; }
  if (lbLocation != '') {  location = lbLocation; }
  // frig to update basket if buy was done from basket page
  if ((lbLocation == '') && (ajaxRefresh != '')) {  location = ajaxRefresh; }
}

function createLightBox() {
  lbDiv = createDynamicPopup('lbDiv');
  lbDiv.style.height = '';
  lbDiv.className = 'lightBox';
  lbDiv.position = 'absolute';
  lbDiv.innerHTML = '<div></div>';
}

var lbOrigWid = 0;
function showLightBox(c, myEvent, id, img, update) {
  lbError = true;  // stop transition happening in case popupInit closes an already open box
  clearTimeout(timer1);
  transitionStop(lbDiv);
  createLightBox()
  popupInit(lightBoxClose,'lbDiv');
  lbError = false;
  el = lbDiv;
  el.className = 'lightBox';
  el.position = 'absolute';
  if (lbOrigWid == 0) { lbOrigWid = cssStyle(el,'width')-0; }
  if (update=='u') {
     verb1 = "Updating";
     verb2 = "Updated";
     verb3 = "in";
  }
  el.innerHTML = '<div id="lightBoxC">'+
//                 '<div id="lightBoxCpic">'+
//                 '<div id="lbBtn">'+
//                 '<div id="lbBtnIn">'+
//                 '<img src="'+thisUrl+'assets/images/closebtn1.jpg" />'+
//                 '<a class="a" onClick="popupClose(\''+c+'\');">X</a>'+
//                 '</div>'+
//                 '</div>'+
                 '<div id="lbTxtHolder">'+
                 '<span id="lbTxtT">'+verb1+'...</span>'+
                 '<span id="lbTxt">&nbsp;'+id+'&nbsp;</span>'+
                 '<span id="lbTxtB">'+verb3+' your Basket</span>'+
                 '<div id="lbTxtS"></div>'+
                 '</div>'+
//                 '</div>'+
                 '</div>';
//  if (id) { document.getElementById('lightBoxCpic').style.backgroundImage = 'url('+thisUrl+'products/images/thumb/'+img+'.jpg)'; }
//  alert(document.getElementById('lightBoxCpic').style.backgroundImage);
  
  if (myEvent) {
    var x = xOnPage(mouseX(myEvent) - lbOrigWid-2,lbOrigWid);
    var y = yOnPage(mouseY(myEvent) - 70,200);
  } else {
    var x = xOnPage(0,lbOrigWid,true);
    var y = yOnPage(0,200,true,'',true);
  }

  el.style.left = x + 'px';
  el.style.top =  y + 'px';
  el.style.width = lbOrigWid+'px';
  el.style.display = 'block';
//  showShadowBox(el,'center');
}

function showAjaxErrorBox(c)
{
// make sure lbDiv is not being used by lightbox
  lbError = true;
  clearTimeout(timer1);
  lbLocation = ''; // stop it refreshing the page
  ajaxRefresh = ''; // ditto
  popupClose('','');

  alertX(c,'',0,'Please Note');
}

function expressBuy() {
  var el = document.getElementById('catCode');
  if (el) {
    if (trim(el.value) == '') { return false; }
    buyOneAjax(el.value,null,'','EXPRESS');
//    el.value = '';
  }
}

function buyOneAjax(part,e,masterpart,promo, img) {
//alert(part+' - '+masterpart+' - '+promo);
  if (oneclick == 1) { return false; }

  if (!BUY_http) { BUY_http = getBuyAjax(); }

  var fixer = new Date();
  var iURL = thisUrl+"BUYajax.asp?part="+part+"&masterpart="+masterpart+"&quantity=1"+"&when="+fixer.getTime();
  var xpart = part;
  if (promo == 'PROMO')  {iURL= iURL+'&attr=promo'}
  if (promo == 'EXPRESS')  {iURL= iURL+'&express=express&template_suffix=_quickbuy'}

// now look for Gift Wrapping options
//alert('now look for Gift Wrapping options')
   var gw;
   if (document.getElementById('gift_wrapYes')) {
      gw = document.getElementById('gift_wrapYes').checked;
   }
   if (gw) {
      var gw_msg = document.getElementById('gift_msg').value;
      var el = document.getElementById('wrapSelect');
      for (var i = 0; i < el.options.length; i++) {
         if (el.options[i].selected) var gw_paper = el.options[i].value;
      }
      iURL = iURL+'&gift_wrap='+gw_paper+'&gift_msg='+gw_msg;
   }

// now look for Personalisation options
//alert('now look for Personalisation options');
   var persoURL;
   var perso;
   var perso_date;
   var perso_string;
   var perso_number;
   var perso_string_option;
   var perso_number_option;
   persoURL = '';
   var ip;
   if (document.getElementById('personalisationYes')) {
      perso = document.getElementById('personalisationYes').checked;
   }
   if (perso) {
      var perso_number_count = document.getElementById('perso_number_count').value;
      var perso_string_count = document.getElementById('perso_string_count').value;
      persoURL = persoURL+'&pnc='+perso_number_count+'&psc='+perso_string_count
//alert('persoURL='+persoURL);
      for (ip = 1; ip <= perso_string_count; ip++) {
         if (document.getElementById('perso_string'+ip)) {
            perso_string = document.getElementById('perso_string'+ip).value;
            perso_string_option = document.getElementById('perso_string_option'+ip).value;
            persoURL = persoURL+'&ps'+ip+'='+perso_string+'&pso'+ip+'='+perso_string_option
         }
      }
      for (ip = 1; ip <= perso_number_count; ip++) {
         if (document.getElementById('perso_number'+ip)) {
            perso_number = document.getElementById('perso_number'+ip).value;
            perso_number_option = document.getElementById('perso_number_option'+ip).value;
            persoURL = persoURL+'&pn'+ip+'='+perso_number+'&pno'+ip+'='+perso_number_option
         }
      }
      if (document.getElementById('dDate')) {
         perso_date = document.getElementById('dDate').value;
         persoURL = persoURL+'&perso_date='+perso_date
      }
   }
   iURL = iURL+ persoURL

//alert(iURL);
//  try {
    BUY_http.open("GET", iURL, true);
//  } catch(err) { alert(err.description); return false; }

  lbLocation = '';  // just to make sure the lightBox doesnt try to call the server with location=
  if (!masterpart) { masterpart = part; }
  showLightBox('1 of '+part, e, masterpart, img);

  startOneClick();
  pauseBuy(200);
  BUY_http.onreadystatechange = function(){ getBuyRes(); };
  BUY_http.send(null);
}

function buySomeAjax(x,part,e,rel_item,img) {
  if (oneclick == 1) { return false; }
//alert(rel_item);
  if (!BUY_http) { BUY_http = getBuyAjax(); }

   // set rel_item to 'NOPRESEL' to stop the presel scan. --> Dont want related item buy to add presel item.
   if (x == '')  // '' means buy one - called from infopage and search via verysmall.tmp etc.
   { a = 1; rel_item='NOPRESEL'; }
   else
   { a = document.getElementById('qty'+x).value; }
   b = parseInt(a);
   if (isNaN(b)) {
      showAjaxErrorBox("ERROR - quantity entered - "+a+" - is INVALID");
      return false;
   }

  var xiURL = '';
  var yiURL = '';
  var fixer = new Date();
  var iURL = thisUrl+"/BUYajax.asp?part="+part+"&quantity="+a+"&when="+fixer.getTime();
//  if (part==catalog) iURL = iURL+'&attr=catlg'
  
// now look for Gift Wrapping options
   var gw;
   if (document.getElementById('gift_wrapYes')) {
      gw = document.getElementById('gift_wrapYes').checked;
   }
   if (gw) {
      var gw_msg = document.getElementById('gift_msg').value;
      var el = document.getElementById('wrapSelect');
      for (var i = 0; i < el.options.length; i++) {
         if (el.options[i].selected) var gw_paper = el.options[i].value;
      }
      iURL = iURL+'&gift_wrap='+gw_paper+'&gift_msg='+gw_msg;
   }

// now look for Personalisation options
//alert('now look for Personalisation options');
   var persoURL;
   var perso;
   var perso_date;
   var perso_string;
   var perso_number;
   var perso_string_option;
   var perso_number_option;
   persoURL = '';
   var ip;
   if (document.getElementById('personalisationYes')) {
      perso = document.getElementById('personalisationYes').checked;
   }
//alert('perso='+perso);
   if (perso) {
      var perso_number_count = document.getElementById('perso_number_count').value;
      var perso_string_count = document.getElementById('perso_string_count').value;
      persoURL = persoURL+'&pnc='+perso_number_count+'&psc='+perso_string_count
//alert('persoURL='+persoURL);
      for (ip = 1; ip <= perso_string_count; ip++) {
         if (document.getElementById('perso_string'+ip)) {
            perso_string = document.getElementById('perso_string'+ip).value;
            perso_string_option = document.getElementById('perso_string_option'+ip).value;
            persoURL = persoURL+'&ps'+ip+'='+perso_string+'&pso'+ip+'='+perso_string_option
         }
      }
      for (ip = 1; ip <= perso_number_count; ip++) {
         if (document.getElementById('perso_number'+ip)) {
            perso_number = document.getElementById('perso_number'+ip).value;
            perso_number_option = document.getElementById('perso_number_option'+ip).value;
            persoURL = persoURL+'&pn'+ip+'='+perso_number+'&pno'+ip+'='+perso_number_option
         }
      }
      if (document.getElementById('dDate')) {
         perso_date = document.getElementById('dDate').value;
         persoURL = persoURL+'&perso_date='+perso_date
      }
   }
   iURL = iURL+ persoURL

  var xpart = part;
//  look for preSelectedRelatives and add to buying string if found
  if ( rel_item != 'NOPRESEL' && (document.getElementById('numPre'))) {
     numPre = parseInt(document.getElementById('numPre').value);
     xiURL = '&preParts=';
     for (var i=0; i<numPre; ++i) {
         j = i+1;
        if (document.getElementById('buyPre0'+j).checked!='') xiURL = xiURL+document.getElementById('partPre0'+j).value+'|';
     } 
  }
//     } else alert('numPre not found');

  if (rel_item == 'promo')  {yiURL='&attr=promo'}
  if (rel_item.toUpperCase() == 'VOUCHER7') { iURL += '&attr='+voucherName+'~7~'+voucherLineNo+'&price=0'; }
  if (rel_item.toUpperCase() == 'VOUCHER6') { iURL += '&attr='+voucherName+'~6&price=0'; }

  iURL = iURL+xiURL+yiURL;
  BUY_http.open("GET", iURL, true);
//alert(iURL);
  lbLocation = '';  // just to make sure the lightBox doesnt try to call the server with location=
  showLightBox(a+' of '+part, e, part, img);

  startOneClick();
  pauseBuy(200);
  BUY_http.onreadystatechange = function(){ getBuyRes(); };
  BUY_http.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2005 00:00:00 GMT");
  BUY_http.send(null);
  return false;  // make sure it doesnt submit the form
}

function buyGiftVAjax(x,part,e,rel_item,img) {
  if (oneclick == 1) { return false; }

  if (!BUY_http) { BUY_http = getBuyAjax(); }

   if (document.GVform.design) {
      for (var i=0; i < document.GVform.design.length; i++) {
      if (document.GVform.design[i].checked) {
         var gv = document.GVform.design[i].value;
         part = gv
         }
      }
    }
//    if (part=='giftvp') {part='giftvp1';}
   var value = document.getElementById('manual_value').value;
   var lineNo = document.getElementById('lineNo').value;
   var email = '';
   if (document.getElementById('friend_email')) {email = document.getElementById('friend_email').value;}
   var toName = document.getElementById('toName').value;
   var fromName = document.getElementById('fromName').value;
   var msg = document.getElementById('email_msg').value;
   var first_name = '';
   var last_name = '';
   var address = '';
   var city = '';
   var county; 
   var country;
   var postcode;
   var postcodefind;
   if (document.getElementById("first_name")) {first_name = document.getElementById("first_name").value;}
   if (document.getElementById("last_name")) {last_name = document.getElementById("last_name").value;}
   if (document.getElementById("address")) {address = document.getElementById("address").value;}
   if (document.getElementById("city")) {city = document.getElementById("city").value;}
   if (document.getElementById("county")) {county = document.getElementById("county").value;}
   if (document.getElementById("country")) {country = document.getElementById("country").value;}
   if (document.getElementById("postcodefind")) {postcodefind = document.getElementById("postcodefind").value;}
   if (document.getElementById("postcode")) {postcode = document.getElementById("postcode").value;}
   if (postcodefind!='Postcode') {postcode=postcodefind}
   address = address.replace(/\n/g,'~');
   var fixer = new Date();
   var iURL = thisUrl+"BUYajax.asp?part="+part+"&lineNo="+lineNo+"&price="+value+"&email="+email+"&toname="+toName+"&fromname="+fromName+"&inits="+first_name+"&surname="+last_name+"&addrs="+address+"&city="+city+"&county="+county+"&country="+country+"&postcode="+postcode+"&msg="+msg+"&attr=giftv&when="+fixer.getTime();
// alert(iURL);

   BUY_http.open("GET", iURL, true);

   lbLocation = '';  // just to make sure the lightBox doesnt try to call the server with location=
   showLightBox('1 of '+gv, e, part, img,'u');

   startOneClick();
   pauseBuy(100);
   BUY_http.onreadystatechange = function(){ getBuyRes(); };
   BUY_http.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2005 00:00:00 GMT");
   BUY_http.send(null);
   return false;  // make sure it doesnt submit the form
}

function getBuyRes() {
  if (BUY_http.readyState == 1) {
    res = 'Checking Stock........';
    if ( document.getElementById('lbTxtS'))
       { document.getElementById('lbTxtS').innerHTML = res;  }
  }

  if (BUY_http.readyState == 4) {
    res = BUY_http.responseText;
    if ( document.getElementById('lbTxtS')) { document.getElementById('lbTxtS').innerHTML = '';  }
//alertX(res);
    vouc_data = '';
    // was the basket summary returned
    if (res.search('#-#-#-#-#') > -1) {
      aaa = res.split('#-#-#-#-#');
      vouc_data = aaa[1];
      res = aaa[0];
    }
    // is it an out of stock message
    // or it might now be the code for a colour / size selector if it was an express buy
    if (res.search('#####') > -1) {
//alertX_BR(res);
      aaa = res.split('#####');
      if (aaa.length == 2) {
        // only two parts so it must be a stock message
        showAjaxErrorBox(aaa[1]);
      } else {
        // assume it is a showpart colour/size template
        lbError = true;
        lbLocation = ''; // stop it refreshing the page
        matrixAjaxRefresh = ajaxRefresh; // ditto
        ajaxRefresh = ''; // ditto
        clearTimeout(timer1);
        popupClose('');
        ajaxRefresh = matrixAjaxRefresh;

//alert(aaa[0]);
        // put the template in the work area div so I can create the matrix and find out its size before making it visible
        makeWorkArea(aaa[0]);  // aaa[0] is the template

        var idx = trim(aaa[1]);  /// aaa[1] is the part code = index into the json array
        // aaa[2] is the json data
        eval(aaa[2]); // if you get mx_data doesnt exist error here, you need to put "var mx_data = new Array();" into the main template
//alertX_BR(aaa[2]);
        switch(mx_data[idx].template)
        {
          case 'MTX_LARGE' : func = createMatrixTable; break;
          case 'LIST' : func = createMatrixTable; break;
          case 'MTX_LARGE_TABLE' : func = createMatrixTable; break;
          case 'MTX_LARGE_ALPHA' : func = createMatrixAlphabet; break;
          case 'MTX_LARGE_BRA' : func = createMatrixBra; break;
        }
        // matrix box is now on the workarea, process it there so the height is known before adding to the showX popup
        func(idx,'matrixHead_qb','matrixBody_qb', 'iB_qb', 'Select size and colour below, choose your quantity and then<br /> click on Add to Basket.');

        alertPrettyHead = true;
        matrixPopupId = showX(getWorkArea()); // save the id so I can kill the popup if we are on the basket page
/*
      document.getElementById('ajaxBasket').innerHTML = aaa[0];
      if (aaa[1].substring(0,8) == 'showpart') {
        lbError = true;
        lbLocation = ''; // stop it refreshing the page
        ajaxRefresh = ''; // ditto
        clearTimeout(timer1);
        popupClose();

        showpart_part = aaa[1].substring(8,20)
        aaa[1] = 'Your Express Ordered item needs a colour/size to be selected<br><br>Please click the \'Select\' button to proceed to the selection page';
        promptX(aaa[1], showpartCloseFunc, 0, {'Select':'select', 'Cancel':'cancel'}, '');
*/
      }
    }
    else  // its not out of stock
    {
      err = '';

      if ((res.substr(0,2) == '<%') || (res == '')) // asp code was returned
        { err='Y'; res = ''; }
      if (res.substr(0,60).match(/\<\!DOCT/i))  // html was returned
        { err='HTML'; }
      if (err == 'HTML') {
        showAjaxErrorBox(res);
      }
      else
      if (err == 'Y') {
        if ( document.getElementById('lbTxtT')) { document.getElementById('lbTxtT').innerHTML = 'Error:'; }
        if ( document.getElementById('lbTxtB')) { document.getElementById('lbTxtB').innerHTML = ''; }
        if ( document.getElementById('lbTxt')) { document.getElementById('lbTxt').innerHTML = 'Server did not respond.'; }
        if ( document.getElementById('lbTxtS')) { document.getElementById('lbTxtS').innerHTML = 'Please try again in a few seconds.'; }
      }
      else {
        document.getElementById('ajaxBasket').innerHTML = res;
        if ( document.getElementById('lbTxtT')) { document.getElementById('lbTxtT').innerHTML = verb2; }
        if ( document.getElementById('lbTxtS') && document.getElementById('basket_itemcount'))
          { q = document.getElementById('basket_itemcount').innerHTML;
            if (q == 1) { q = q + ' item'; } else { q = q + ' items'; }
            document.getElementById('lbTxtS').innerHTML = 'Your basket now holds '+q; }
        clearTimeout(timer1);
        timer1 = window.setTimeout("timer1timer()",lightBoxTimeOut);
        if (window.switchPromoButton) { switchPromoButton(); }
      }
//      safetoclose = true;
    }
    if (vouc_data) {
//alertX(vouc_data);
      eval(vouc_data);
      if (window.quickShopBasket) { quickShopBasket(); }
    }
    stopOneClick();
  }
}

//function voucherBuy(ev, part,lineNo,voucher,vtype) {
function voucherBuy(part,lineNo,voucher,vtype) {
  if (!BUY_http) { BUY_http = getBuyAjax(); }

  voucherLineNo = lineNo;
  voucherName = voucher;
  voucherType = vtype;
  var fixer = new Date();
  // sitecodes should be provided by asp and in store_finder.tmp as a js var
  var iURL = thisUrl+"showPart_ajax.asp?part="+part+"&template_suffix=_voucher7&voucherType="+voucherType+"&when="+fixer.getTime();
//alert(iURL);
  BUY_http.open("GET", iURL, true);
  pauseBuy(100);
  BUY_http.onreadystatechange = function(){ show_voucher7_matrix(); };
  BUY_http.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2005 00:00:00 GMT");
  BUY_http.send(null);
}

var freeCount = 0;
function updateFreeCount() {
  if (!freeCount) return;
  var el = document.getElementById('matrix_buy_count');
  if (el) {
    var count = el.value-0;
    var el = document.getElementById('free_count');
    if (el) { el.innerHTML = freeCount; }
    var el = document.getElementById('free_count_s');
    if (el) { el.innerHTML = (count > 1 ? 's' : ''); }
    var el = document.getElementById('free_count_remaining');
    if (el) { el.innerHTML = count; }
  }
}

function show_voucher7_matrix() {
  showRes = false;
  if (BUY_http.readyState == 1) {
    var el = document.getElementById("matrixWaiting"+voucherLineNo);
    if (el) { el.style.display = 'block'; el.innerHTML = BUY_http.responseText; }
  }

  if (BUY_http.readyState == 4) {
    res = BUY_http.responseText;
    showRes = true;
    var el = document.getElementById("matrixWaiting"+voucherLineNo);
    if (el) { el.style.display = 'none'; }
  }

  if (showRes) {
    var el = document.getElementById('matrix_buy_count');
    if (el) {
      freeCount = el.value-0;
    }
    aaa = res.split('#####');

    // put the template in the work area div so I can create the matrix and find out its size before making it visible
    makeWorkArea(aaa[0]);  // aaa[0] is the template

    var idx = trim(aaa[1]);  /// aaa[1] is the part code
    // aaa[2] is the json data
    eval(aaa[2]); // if you get mx_data doesnt exist error here, you need to put "var mx_data = new Array();" into the main template
//alertX_BR(aaa[2]);

    matrixAjaxRefresh = ajaxRefresh;
    var matrix = (mx_data[idx] && mx_data[idx].feat && (mx_data[idx].feat.length > 0));

    if (matrix) {
      switch(mx_data[idx].template)
      {
        case 'MTX_LARGE' : func = createMatrixTable; break;
        case 'LIST' : func = createMatrixTable; break;
        case 'MTX_LARGE_TABLE' : func = createMatrixTable; break;
        case 'MTX_LARGE_ALPHA' : func = createMatrixAlphabet; break;
        case 'MTX_LARGE_BRA' : func = createMatrixBra; break;
      }
      // matrix box is now on the workarea, process it there so the height is known before adding to the showX popup
      func(idx,'matrixHead_qb','matrixBody_qb', 'iB_qb', 'Select size and colour below, choose your quantity and then<br /> click on Add to Basket.');

      alertPrettyHead = true;
      matrixPopupId = showX(getWorkArea()); // save the id so I can kill the popup if we are on the basket page
      updateFreeCount();
    }
  }
}

function refreshMiniBasket() {
  if (!BUY_http) { BUY_http = getBuyAjax(); }

  var fixer = new Date();
  iURL = thisUrl + 'mini_basket.asp'+"?when="+fixer.getTime();
  BUY_http.open("GET", iURL, true);
  pauseBuy(200);
  BUY_http.onreadystatechange = function(){ getRefreshRes(); };
  BUY_http.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2005 00:00:00 GMT");
  BUY_http.send(null);
}

function getRefreshRes() {
  if (BUY_http.readyState == 1) {
  }

  if (BUY_http.readyState == 4) {
    res = BUY_http.responseText;
    res = res.split('#####');

//alert(res);
    if (res[0]) {
      var el = document.getElementById('ajaxBasket');
      if (el) { el.innerHTML = res[0]; }
    }
    if (res.length > 1) {
      // element[1] will contain the basket summary in the vouc_data array
//alert(res[1]);
      eval(res[1]);
      if (window.quickShopBasket) { quickShopBasket(); }
    }
  }
}

function getBuyAjax() {
  var xhttp;
   try {   // The following "try" blocks get the XMLHTTP object for various browsers…
      xhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e2) {
 // This block handles Mozilla/Firefox browsers...
     try {
       xhttp = new XMLHttpRequest();
     } catch (e3) {
       xhttp = false;
     }
      }
    }
  return xhttp; // Return the XMLHTTP object
}

function pauseBuy(millis) {
   var date = new Date();
   var curDate = null;
   do { curDate = new Date(); }
   while(curDate-date < millis);
}

var reviewAlertId = '';
function showReviewBox(part) {
  alertPrettyHead = true;
  reviewAlertId = promptX('reviewDataHolder',saveReview,0,{'Save':'save'},co_name+' Product Review');
}

function setFirstReview() {
  var deftext = 'We are waiting for our first review<br /><a class="review" onClick="showReviewBox(\'<elucid_part>\');return false;">Be the first to write about this product</a>';
  var el = document.getElementById('tabboxr');
  if (el) {
    if (trim(el.innerHTML) == '') { el.innerHTML = deftext; }
  }
}

function saveReview(opt) {
// return false to stop the alert box from closing
   if (opt=='save')  { addReview(); return false; }
   if (opt=='close')  {  }
}

function addReview() {
   var fm = document.getElementById('reviewForm');
   if (!checkData(fm)) { return false; }
   var err = '';
   var part = document.getElementById('part').value;
   var descr = document.getElementById('descr').value;
   var name = document.getElementById('name').value;
   var email = document.getElementById('email').value;
   var where = document.getElementById('location').value;
   var comment = document.getElementById('comment').value;
   if (trim(comment) == '') { err = 'Please enter your review text<br />'; }
   var ok_to_show = 'Y';
   var oks = document.getElementsByName('ok_to_show');
   for (var i=0; i < oks.length; i++) {
     if (oks[i].checked) { ok_to_show = oks[i].value; }
   }

   if (err) {
     alertX('Error:<br />'+err);
     return false;
   }
//   var rate='0';
//   if (document.getElementById('rate0').checked==true) {rate='0';}
//   if (document.getElementById('rate1').checked==true) {rate='1';}
//   if (document.getElementById('rate2').checked==true) {rate='2';}
//   if (document.getElementById('rate3').checked==true) {rate='3';}
//   if (document.getElementById('rate4').checked==true) {rate='4';}
//   if (document.getElementById('rate5').checked==true) {rate='5';}

   // crlf from the textarea wont make it through the ajax link so replace them here and back again at the other end
   comment = comment.replace(/\n/g,'#|#');
   var fixer = new Date();
   var iURL = thisUrl+"review.asp?submit=SUBMIT YOUR REVIEW&part="+part+"&descr="+descr+"&name="+name+"&email="+email+"&location="+where+"&comment="+comment+"&ok_to_show="+ok_to_show+"&when="+fixer.getTime();
//alert(iURL);

   if (!BUY_http) { BUY_http = getBuyAjax(); }

   BUY_http.open("GET", iURL, true);

   lbLocation = '';  // just to make sure the lightBox doesnt try to call the server with location=
//   showLightBox('Your review has been submitted.', '', '', '');

   startOneClick();
   pauseBuy(100);
   BUY_http.onreadystatechange = function(){ getReviewRes(); };
   BUY_http.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2005 00:00:00 GMT");
   BUY_http.setRequestHeader("Content-Type", "text/plain");
   BUY_http.send(null);
   return false;  // make sure it doesnt submit the form
}

function getReviewRes() {
  if (BUY_http.readyState == 1) {
    res = 'Waiting for response................';
    if ( document.getElementById('reviewRes'))
       { document.getElementById('reviewRes').innerHTML = res;  }
  }

  if (BUY_http.readyState == 4) {

    res = BUY_http.responseText;
    if ( document.getElementById('reviewRes'))
       { document.getElementById('reviewRes').innerHTML = res;  }
    alertX_SetButtons(reviewAlertId, { 'Close':'close' } );
  }
}

function enterGV() {
   total_order_value = document.getElementById('total_order_value').value;
   gv = trim(document.getElementById('giftVoucher').value);

//alert('voucher '+gv+' entered');

  if (gv) {
     if (oneclick == 1) { return false; }
     if (!BUY_http) { BUY_http = getBuyAjax(); }

     var fixer = new Date();
     var iURL = thisUrl+"BUYajax.asp?mode=gv&giftvoucher="+gv+"&total_order_value="+total_order_value+"&when="+fixer.getTime();
//alert(iURL);

     BUY_http.open("GET", iURL, true);

     startOneClick();
     pauseBuy(100);
     BUY_http.onreadystatechange = function(){ getGVRes(); };
     BUY_http.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2005 00:00:00 GMT");
     BUY_http.send(null);
   }
   return false;  // make sure it doesnt submit the form
}

function getGVRes() {
  if (BUY_http.readyState == 1) {
    res = 'Waiting for response................';
     if ( document.getElementById('giftVoucher'))
       { document.getElementById('giftVoucher').value = res;  }
 }

  if (BUY_http.readyState == 4) {
    res = BUY_http.responseText;
    var allValues = document.getElementById('gift_voucher').value;
    var gvValues = document.getElementById('gvValues').innerHTML;

    eval(res);

    if (JSon.msg.slice(0,7) != 'Voucher') {
       var n = JSon.msg.indexOf(' ');
       var voucher = JSon.voucher;
       if (gvValues.slice(0,5)!='These') {gvValues='The voucher values will be applied to your order when it is completed".<br><br>';}
       allValues = allValues+voucher+',';
       gvValues = gvValues+JSon.msg+'<br>';
       if (JSon.tov==0) {document.getElementById('enterGVbtn').style.display='none'};
       document.getElementById('gvValues').innerHTML = gvValues;
       document.getElementById('gvEnd').innerHTML = '<br>The total amount to left to pay is reduced to '+JSon.symbol+JSon.tov;
       document.getElementById('gift_voucher').value = allValues;
       document.getElementById('total_order_value').value = JSon.tov;
       var el = document.getElementById('cc_total_to_pay');
       if (el) { el.innerHTML = JSon.symbol+JSon.tov; }
    }
    if ( document.getElementById('giftVoucher'))
       { document.getElementById('giftVoucher').value = JSon.msg;  }
   stopOneClick();
  }
}