//-------------------------------------------------------------------------
//  AJAX buy stuff
//-------------------------------------------------------------------------
var res = '';
var lightBoxTimeOut = 1000;  // 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 = '';

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() {
  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 = 'auto';
  lbDiv.className = 'lightBox';
  lbDiv.position = 'absolute';
  lbDiv.innerHTML = '<div></div>';
}

function showLightBox(c, myEvent, id) {
  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';
  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">'+
                 '<div id="lbTxtT">Adding...</div>'+
                 '<div id="lbTxt">'+id+'</div>'+
                 '<div id="lbTxtB">to your Basket</div>'+
                 '<div id="lbTxtS"></div>'+
                 '</div>'+
                 '</div>'+
                 '</div>';
//  if (id) { document.getElementById('lightBoxCpic').style.backgroundImage = 'url('+thisUrl+'/products/images/small/'+id+'_1_thumb.jpg)'; }


  var x = xOnPage(mouseX(myEvent) - 318,320);
  var y = yOnPage(mouseY(myEvent) - 100,200);

  el.style.left = x + 'px';
  el.style.top =  y + 'px';
  el.style.width = '314px';
  el.style.display = 'block';
  showShadowBox(el);
}

function showAjaxErrorBox(c)
{
// make sure lbDiv is not being used by lightbox
  lbError = true;
  createLightBox()
  popupInit(lightBoxClose,'lbDiv');
  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>'+
                 '<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 + 0;
  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 buyOneAjax(part,e,masterpart,promo,promomaster) {
  if (oneclick == 1) { return false; }
  var fixer = new Date();
  var iURL = thisUrl+"BUYajax.asp?part="+part+"&masterpart="+masterpart+"&quantity=1"+"&when="+fixer.getTime();
  xpart = part;
  if (promo == 'PROMO')  {iURL= iURL+'&attr=promo'; masterpart=promomaster}
  http.open("GET", iURL, true);
  lbLocation = '';  // just to make sure the lightBox doesnt try to call the server with location=
  showLightBox('1 of '+part, e, masterpart);
  startOneClick();
  pauseBuy(200);
  http.onreadystatechange = function(){ getBuyRes(); };
  http.send(null);
}

function buySomeAjax(x,part,e,rel_item) {
  if (oneclick == 1) { return false; }
   // 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();
  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;
  http.open("GET", iURL, true);
  lbLocation = '';  // just to make sure the lightBox doesnt try to call the server with location=
  showLightBox(a+' of '+part, e, part);
  startOneClick();
  pauseBuy(200);
  http.onreadystatechange = function(){ getBuyRes(); };
  http.send(null);
  return false;  // make sure it doesnt submit the form
}

function buyManyAjax(e) {
   var attempt='';
   var q, a, p;
   var j;
   var qstr = '';
   var iURL = thisUrl+"BUYajax.asp?partlist=";
   var num = parseInt(document.getElementById('fcnt').value);
   for (var i=0; i<num; ++i) {
       j = i+1;
      if (document.getElementById('qty'+j)!=null) {
         q = document.getElementById('qty'+j).value;
         if (q!='') {
            a = document.getElementById('qty'+j).value;
            p = document.getElementById('part'+j).value;
            qstr = qstr+p+'~~'+a+'|';
            attempt = attempt+a+' of '+p+'<br>';
         }
      }
   } 
   if (qstr!='') {
      var fixer = new Date();
   	  iURL = iURL+qstr+"&when="+fixer.getTime();
      http.open("GET", iURL, true);
      lbLocation = '';  // just to make sure the lightBox doesnt try to call the server with location=
      showLightBox(p, e, attempt);
      startOneClick();
      pauseBuy(200);
      http.onreadystatechange = function(){ getBuyRes(); };
      http.send(null);
      return false;  // make sure it doesnt submit the form
   }
}

function getBuyRes() {
  if (http.readyState == 1) {
    res = 'Waiting for response................';
    if ( document.getElementById('lbTxtS'))
       { document.getElementById('lbTxtS').innerHTML = res;  }
  }

  if (http.readyState == 4) { 
    res = http.responseText;
    // is it an out of stock message
    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 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);
}

function emailmeAjax(email,part,masterpart,descr,name,e) {
   var result
   var imagepart
   masterpart = trim(masterpart)
   if (masterpart.length == 0) { imagepart = part} else { imagepart = masterpart}

//   var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
//   if (!filter.test(email)) {
       showEmailPopup(email,part,imagepart,descr,name,e)
       return false
//   }   
}