//-------------------------------------------------------------------------
//  AJAX buy stuff
//-------------------------------------------------------------------------
var res = '';
var lightBoxTimeOut = 2000;  // milliseconds
var xpart;
var lbDiv = null;
var shadowDiv = 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;

function startOneClick() {  clearTimeout(oneclicktimer); oneclick = 1; oneclicktimer = window.setTimeout("stopOneClick", 3000); }
function stopOneClick() {  clearTimeout(oneclicktimer); oneclick = 0; }

function timer1timer() {
  clearTimeout(timer1);
  popupClose('timer');
}
//
function lightBoxCloseNew() {
  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 createLightBoxNew() {
  lbDiv = createDynamicPopup('lbDivNew');
  lbDiv.style.height = '';
  lbDiv.className = 'lightBox';
  lbDiv.position = 'absolute';
  lbDiv.innerHTML = '<div></div>';
}

var lbOrigWid = 0;
function showLightBoxNew(c, myEvent, id, img) {
  lbError = true;  // stop transition happening in case popupInit closes an already open box
  clearTimeout(timer1);
  createLightBoxNew()
  popupInit(lightBoxCloseNew,'lbDivNew');
  lbError = false;
  el = lbDiv;
  el.className = 'lightBox';
  el.position = 'absolute';
  if (lbOrigWid == 0) { lbOrigWid = cssStyle(el,'width')-0; }

  if (isIE6())
    { lbDiv.style.backgroundImage = "url('assets/images/buypopup.jpg')"; }

  el = lbDiv;
  el.innerHTML = '<div id="lbBtn">'+
                 '<a class="a" onClick="lightBoxCloseNew(\''+x+'\');"></a>'+
                 '</div>'+
                 '<div id="lbTxt">'+c+'</div>';
  el.style.display = 'block';

  if (myEvent) {
    var x = xOnPage(mouseX(myEvent) - lbOrigWid-2,lbOrigWid);
    var y = yOnPage(mouseY(myEvent) - 100,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';
  timer1 = window.setTimeout("lightBoxCloseNew()",5000);
}

function showAjaxErrorBox(c)
{
// make sure lbDiv is not being used by lightbox
  lbError = true;
  createLightBoxNew()
  popupInit(lightBoxCloseNew,'lbDivNew');
  clearTimeout(timer1);
  lbDiv.style.display='none';

  el = lbDiv;
  el.className = 'ajaxErrorBox';
  el.position = 'absolute';
  el.style.display = 'block';

  el.innerHTML = '<div id="ajaxErrorBoxC">'+
                 '<div id="ajeb_heading">Please note:</div>'+
                 '<a id="ajeb_btn" href="javascript:popupClose();" ><img src="'+thisUrl+'assets/images/closebtn1.jpg" /></a>'+
                 '<div id="ajeb_body"><ul>'+
                 c+
                 '</ul></div>'+
                 '<div id="ajeb_footer"><a class="BMBtn" style="float:right;" href="javascript:popupClose();"> Close Message Box</a></div>'+
                 '</div>';

  w = document.getElementById('ajeb_body').offsetWidth + 10;
  el.style.width = (w)+'px';
  h = el.offsetHeight;

  var x = xOnPage(10,w,true);
  var y = yOnPage(10,h,true);

  el.style.display = 'block';
  el.style.left = x + 'px';
  el.style.top =  y + 'px';
  document.getElementById('ajeb_heading').style.width = w+'px';
}

function expressBuy() {
  var el = document.getElementById('catCode');
  if (el) {
    buyOneAjax(el.value,null,'','');
    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'}

// 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; }
  showLightBoxNew('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; }

  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();

// 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'}
  iURL = iURL+xiURL+yiURL;
  BUY_http.open("GET", iURL, true);

  lbLocation = '';  // just to make sure the lightBox doesnt try to call the server with location=
  showLightBoxNew(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 ajaxFilter(s) {
  s = s.replace(/\n/g,'~');
  s = s.replace('#','');  // firefox and chrome will truncate the data at the point of a #
  s = s.replace('&','~and~');
  s = s.replace('£','~pnd~');
  return s;
}

function buyGiftVAjax(x,part,e,rel_item,img) {
  if (oneclick == 1) { return false; }

  if (!BUY_http) { BUY_http = getBuyAjax(); }

   var gv = document.getElementById('giftdesign').value;
   if (document.GVform.design) {
      for (var i=0; i < document.GVform.design.length; i++) {
      if (document.GVform.design[i].checked) {
         gv = document.GVform.design[i].value;
         part = gv
         }
      }
    }
// alert(part);
//    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 = ajaxFilter(document.getElementById('toName').value);
   var fromName = ajaxFilter(document.getElementById('fromName').value);
   var msg = ajaxFilter(document.getElementById('email_msg').value);
   var title = '';
   var first_name = '';
   var last_name = '';
   var address = '';
   var city = '';
   var county;
   var country;
   var postcode;
   var postcodefind;
   if (document.getElementById("title")) {title = document.getElementById("title").value;}
   if (document.getElementById("first_name")) {first_name = ajaxFilter(document.getElementById("first_name").value);}
   if (document.getElementById("last_name")) {last_name = ajaxFilter(document.getElementById("last_name").value);}
   if (document.getElementById("address")) {address = ajaxFilter(document.getElementById("address").value);}
   if (document.getElementById("city")) {city = ajaxFilter(document.getElementById("city").value);}
   if (document.getElementById("county")) {county = ajaxFilter(document.getElementById("county").value);}
   if (document.getElementById("country")) {country = ajaxFilter(document.getElementById("country").value);}
   if (document.getElementById("postcode")) {postcode = ajaxFilter(document.getElementById("postcode").value);}
   var fixer = new Date();
   var iURL = thisUrl+"BUYajax.asp?"+"part="+part+"&lineNo="+lineNo+"&price="+value+"&email="+email+"&totitle="+title+"&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=
   showLightBoxNew('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 checkStockAjax(part,line) {
   if (oneclick == 1) { return false; }
   if (!BUY_http) { BUY_http = getBuyAjax(); }
   var fixer = new Date();
   var iURL = thisUrl+"BUYajax.asp?"+"part="+part+"&function=checkStock&when="+fixer.getTime();
// alert(iURL);
   BUY_http.open("GET", iURL, true);
   startOneClick();
   pauseBuy(100);
   BUY_http.onreadystatechange = function(){ getStockRes(); };
   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 getStockRes() {
   if (BUY_http.readyState == 4) {
      res = BUY_http.responseText;
  }
   stopOneClick();
}

function getBuyRes() {
  if (BUY_http.readyState == 1) {
    res = 'Waiting for response................';
    if ( document.getElementById('lbTxtS'))
       { document.getElementById('lbTxtS').innerHTML = res;  }
  }

  if (BUY_http.readyState == 4) {
    res = BUY_http.responseText;
//alert(res);
    if ( document.getElementById('lbTxtS'))
       { document.getElementById('lbTxtS').innerHTML = '';  }
    // is it an out of stock message
//alert(res);
    if (res.search('#####') > -1) {
      aaa = res.split('#####');
//      document.getElementById('ajaxBasket').innerHTML = aaa[0];
      showAjaxErrorBox(aaa[1]);
    }
    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 = 'Added'; }
        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;
    }
    stopOneClick();
  }
}

function refreshMiniBasket() {
  if (!BUY_http) { BUY_http = getBuyAjax(); }

  var fixer = new Date();
  iURL = thisUrl + 'mini_basket.asp'+"?when="+fixer.getTime();
//alert(iURL);
  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;
//alert(res);
    if (res) {
      var el = document.getElementById('ajaxBasket');
      if (el) { el.innerHTML = res; }
    }
  }
}

function getBuyAjax() {
  var xbuyhttp;
   try {   // The following "try" blocks get the XMLHTTP object for various browsers…
      xbuyhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xbuyhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e2) {
 // This block handles Mozilla/Firefox browsers...
     try {
       xbuyhttp = new XMLHttpRequest();
     } catch (e3) {
       xbuyhttp = false;
     }
      }
    }
  return xbuyhttp; // Return the XMLHTTP object
}

function pauseBuy(millis) {
   var date = new Date();
   var curDate = null;
   do { curDate = new Date(); }
   while(curDate-date < millis);
}

function enterGV() {
   total_order_value = document.getElementById('total_order_value').value;
   var gv = trim(document.getElementById('giftVoucher').value);
//alert('total_order_value = '+total_order_value);
//alert('voucher '+gv+' entered');

  if (gv) {
     if (oneclick == 1) { return false; }
     if (gv.match(/accepted/i) || gv.match(/unknown/i) || gv.match(/redeemed/i)) {
       alert('Please enter a gift voucher code');
       return false;
     }
     var vs = document.getElementById('gvValues').innerHTML;
     var gvx = '<br>'+gv+'-';
     var x = vs.match(new RegExp(gvx,'i'));
     if (x) {
        alert('Voucher '+gv+' cannot be used more than once !'); return false;
     }

     if (!BUY_http) { BUY_http = getBuyAjax(); }

 //alert(vs);
     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;
//alert(res);
    try {
      eval(res);
    } catch(err) { res = ''; }
    if (res.indexOf('JSon') > -1 && !(JSon.msg.slice(0,7) == 'Voucher' || JSon.msg.slice(0,12) == 'This Voucher')) {
       var n = JSon.msg.indexOf(' ');
       var voucher = JSon.voucher;
       var v_type = JSon.type;
       if (v_type==document.getElementById('gvType').value && document.getElementById('gvType').value=='MKTG') {
          var gvM = 'Only one Promotional Voucher may be used for each purchase.';
          document.getElementById('gvValues').innerHTML = gvValues;
          document.getElementById('giftVoucher').value = voucher+' not accepted.';
          JSon.msg = voucher + ' not accepted';
 alert(gvM);
       } else {
          if (gvValues.slice(0,7)!='You may') {gvValues='You may enter another gift voucher code if you have one in the box above.<br>The values of these vouchers will be applied to your order after you click on "Enter" above.<br><br>';}
          if (v_type=='MKTG' && !(JSon.msg.slice(0,7) == 'Voucher' || JSon.msg.slice(0,12) == 'This Voucher')) {document.getElementById('gvType').value = v_type};
          allValues = allValues+voucher+',';
          gvValues = gvValues+JSon.msg+'<br>';
          if (JSon.tov==0) {document.getElementById('enterGVbtn').style.display='none'};
          document.getElementById('gvValues').innerHTML = gvValues;
          var msg = '<br>Your total order cost is reduced to £'+JSon.tov;
          var mode='via email.'
          if (JSon.mode=='P' | JSon.mode=='p') {mode='via the post'};
          if (JSon.osv>0) {
             msg+='<br>Your credit card will, of course, not be charged.';
             if (def_order_unredeemed_voucher=='NO' | def_order_unredeemed_voucher=='')
                {msg+='<br>You may redeem the outstanding amount £'+JSon.osv+' in voucher '+voucher+'<br>with a future order.';}
              else
                {msg+='<br>You will receive a voucher for the outstanding amount £'+JSon.osv+' - '+mode+' soon.';}
          }
   //    if (JSon.osv==0) {
   //       msg+='<br>Your credit card will, of course, not be charged.';
   //    }
          document.getElementById('gvEnd').innerHTML = msg+'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; // spaces for ie
          document.getElementById('gift_voucher').value = allValues;
          document.getElementById('gift_voucher_last').value = voucher;
          document.getElementById('gift_voucher_remains').value = JSon.osv;
          document.getElementById('total_order_value').value = JSon.tov;
       }
    }
    if ( document.getElementById('giftVoucher'))
       { document.getElementById('giftVoucher').value = JSon.msg;  document.getElementById('gift_voucher_remains').value = JSon.osv;}
   stopOneClick();
   if (window.do_redeem_voucher) {do_redeem_voucher()}
  }
}
