SHOW_ADDED = 1; // set
Offset_X = -10;
Offset_Y = -30;

function JsHttpRequest(){
  this._construct()
}

(function(){ // to create local-scope variables
  var COUNT       = 0;
  var PENDING     = {};
  var CACHE       = {};
  // called by server script on data load.
  JsHttpRequest.dataReady = function(id, text, js){
    var undef;
    var th = PENDING[id];
    delete PENDING[id];
    if (th){
      delete th._xmlReq;
      if (th.caching) CACHE[th.hash] = [text, js];
      th._dataReady(text, js);
    }
    else if (typeof(th) != typeof(undef)){
      alert("ScriptLoader: unknown pending id: "+id);
    }
  }
  JsHttpRequest.prototype ={
    // standard properties.
    onreadystatechange: null,
    readyState:         0,
    responseText:       null,
    responseXML:        null,
    status:             200,
    statusText:         "OK",
    // additional properties.
    session_name:       "osCsid",  // set to SID cookie or GET parameter name
    responseJS:         null,      // JavaScript response array/hash
    caching:            false,     // need to use caching?
    // internals
    _span:              null,
    _id:                null,
    _xmlReq:            null,
    _openArg:           null,
    _reqHeaders:        null,
    dummy: function() {},          // empty function
    abort: function(){
      if (this._xmlReq) return this._xmlReq.abort();
      if (this._span){
        this.readyState = 0;
        if (this.onreadystatechange) this.onreadystatechange();
        this._cleanupScript();
      }
    },
    open: function(method, url, asyncFlag, username, password){
      this._openArg = {
        'method':    method,
        'url':       url,
        'asyncFlag': asyncFlag,
        'username':  username,
        'password':  password
      };
      this._id = null;
      this._xmlReq = null;
      this._reqHeaders = [];
      return true;
    },
    send: function(content){
      var id = (new Date().getTime()) + "" + COUNT++;
      // build QUERY_STRING from query hash.
      var query = this._hash2query(content);
      // append SID to original URL now.
      var url = this._openArg.url;
      var sid = this._getSid();
      if (sid) url += (url.indexOf('?')>=0? '&' : '?') + this.session_name + "=" + this.escape(sid);
      // solve hash BEFORE appending ID.
      var hash = this.hash = url + '?' + query;
      if (this.caching && CACHE[hash]){
        var c = CACHE[hash];
        this._dataReady(c[0], c[1]);
        return false;
      }
      // try to use XMLHttpRequest.
      this._xmlReq = this._obtainXmlReq(id, url);
      // pass data in URL (GET, HEAD etc.) or in request body (POST)?
      var hasSetHeader = this._xmlReq && (window.ActiveXObject || this._xmlReq.setRequestHeader);
      var href, body;
      if (this._xmlReq && hasSetHeader && (""+this._openArg.method).toUpperCase() == "POST"){
        // use POST method. Pass query in request body.
        // Opera 8.01 does not support setRequestHeader, so no POST method.
        this._openArg.method = "POST";
        href = url;
        body = query;
      }
      else{
        this._openArg.method = "GET";
        href = url + (url.indexOf('?')>=0? '&' : '?') + query;
        body = null;
      }
      // append ID: a=aaa&b=bbb&<id>
      href = href + (href.indexOf('?')>=0? '&' : '?') + id;
      // save loading script.
      PENDING[id] = this;
      if (this._xmlReq){
        // open request now & send it.
        // in XMLHttpRequest mode request URL MUST be ended with "<id>-xml".
        var a = this._openArg;
        this._xmlReq.open(a.method, href+"-xml", a.asyncFlag, a.username, a.password);
        if (hasSetHeader){
          // Pass pending headers.
          for (var i=0; i<this._reqHeaders.length; i++)
          this._xmlReq.setRequestHeader(this._reqHeaders[i][0], this._reqHeaders[i][1]);
          // set non-default Content-type. We cannot use
          // "application/x-www-form-urlencoded" here, because
          // in PHP variable HTTP_RAW_POST_DATA is accessible only when
          // enctype is not default (e.g., "application/octet-stream"
          // is a good start). We parse POST data manually in backend
          // library code.
          this._xmlReq.setRequestHeader('Content-Type', 'application/octet-stream');
        }
      // send the request.
      return this._xmlReq.send(body);
      }
      else{
        // create <script> element and run it.
        this._obtainScript(id, href);
        return true;
      }
    },
    getAllResponseHeaders: function(){
      if (this._xmlReq) return this._xmlReq.getAllResponseHeaders();
      return '';
    },
    getResponseHeader: function(label){
      if (this._xmlReq) return this._xmlReq.getResponseHeader(label);
      return '';
    },
    setRequestHeader: function(label, value){
      // collect headers.
      this._reqHeaders[this._reqHeaders.length] = [label, value];
    },
    //
    // internal functions.
    //
    // constructor.
    _construct: function() {},
    // do all work when data is ready.
    _dataReady: function(text, js){
      with (this){
      if (text !== null || js !== null){
        readyState = 4;
        responseText = responseXML = text;
        responseJS = js;
      }
      else{
        readyState = 0;
        responseText = responseXML = responseJS = null;
      }
      if (onreadystatechange) onreadystatechange();
        _cleanupScript();
      }
    },
    // create new XMLHttpRequest object.
    _obtainXmlReq: function(id, url){
      // if url.domain specified, cannot use XMLHttpRequest!
      // XMLHttpRequest (and MS ActiveX'es) cannot work with different domains.
      if (url.match(new RegExp('^[a-z]+://', 'i'))) return null;
      // Try to use built-in loaders.
      var req = null;
      if (window.XMLHttpRequest){
        try{
          req = new XMLHttpRequest()
        }
        catch(e){
        }
      }
      else if (window.ActiveXObject){
        try{
          req = new ActiveXObject("Microsoft.XMLHTTP")
        }
        catch(e){
        }
        if (!req) try{
          req = new ActiveXObject("Msxml2.XMLHTTP")
          }catch (e){
        }
      }
      if (req){
        var th = this;
        req.onreadystatechange = function(){
          var s = req.readyState;
          if (s == 4){
            // avoid memory leak by removing closure.
            req.onreadystatechange = th.dummy;
            // remove possible junk from response.
            var responseText = req.responseText;
            try{
              // call associated dataReady().
              eval(responseText);
              }
              catch (e){
                JsHttpRequest.dataReady(id, "JavaScript code generated by backend is invalid !\n"+responseText, null);
              }
              }
              else{
                th.readyState = s;
                if (th.onreadystatechange) th.onreadystatechange()
              }
          };
          this._id = id;
        }
        return req;
      },
      // create new script element and start loading.
      _obtainScript: function(id, href){
        with (document){
          var span = null;
          // element over createElement (in HEAD or BODY section or in nested SPAN -
          // no matter): it is created deadly, and does not respons on href assignment.
          // So - always create SPAN.
          span = body.appendChild(createElement("SPAN"));
          span.style.display = 'none';
          span.innerHTML = 'Text for stupid IE.<s'+'cript></' + 'script>';
          setTimeout(function(){
            var s = span.getElementsByTagName("script")[0];
            s.language = "JavaScript";
            if (s.setAttribute) s.setAttribute('src', href); else s.src = href;
            }, 10);
            this._id = id;
            this._span = span;
          }
        },
        // remove last used script element (clean memory).
        _cleanupScript: function(){
          var span = this._span;
          if (span){
            this._span = null;
            setTimeout(function(){
              // without setTimeout - crash in IE 5.0!
              span.parentNode.removeChild(span);
            }, 50);
          }
          return false;
        },
        // convert hash to QUERY_STRING.
        _hash2query: function(content, prefix){
          if (prefix == null) prefix = "";
          var query = [];
          if (content instanceof Object){
            for (var k in content){
              var v = content[k];
              if (v == null || ((v.constructor||{}).prototype||{})[k]) continue;
              var curPrefix = prefix? prefix+'['+this.escape(k)+']' : this.escape(k);
              if (v instanceof Object)
              query[query.length] = this._hash2query(v, curPrefix);
              else
              query[query.length] = curPrefix + "=" + this.escape(v);
            }
          }
          else{
            query = [content];
          }
          return query.join('&');
        },
        // return value of SID based on QUERY_STRING or cookie
        // (PHP compatible sessions).
        _getSid: function(){
          var m = document.location.search.match(new RegExp('[&?]'+this.session_name+'=([^&?]*)'));
          var sid = null;
          if (m){
            sid = m[1];
          }
          else{
            var m = document.cookie.match(new RegExp(s='(;|^)\\s*'+this.session_name+'=([^;]*)'));
            if (m) sid = m[2];
          }
          return sid;
        },
        escape: function(s){
          return escape(s).replace(new RegExp('\\+','g'), '%2B');
        }
      }
    })();
    function addHandler(object, event, handler){
      if (typeof object.addEventListener != 'undefined')
      object.addEventListener(event, handler, false);
      else if (typeof object.attachEvent != 'undefined')
      object.attachEvent('on' + event, handler);
    else{
      var handlersProp = '_handlerStack_' + event;
      var eventProp = 'on' + event;
      if (typeof object[handlersProp] == 'undefined'){
        object[handlersProp] = [];
        if (typeof object[eventProp] != 'undefined')
        object[handlersProp].push(object[eventProp]);
        object[eventProp] = function(e){
          var ret = true;
          for (var i = 0; ret != false && i < object[handlersProp].length; i++)
          ret = object[handlersProp][i](e);
          return ret;
        }
      }
      object[handlersProp].push(handler);
    }
  }
  function removeHandler(object, event, handler){
    if (typeof object.removeEventListener != 'undefined')
      object.removeEventListener(event, handler, false);
      else if (typeof object.detachEvent != 'undefined')
      object.detachEvent('on' + event, handler);
    else{
      var handlersProp = '_handlerStack_' + event;
      if (typeof object[handlersProp] != 'undefined'){
        for (var i = 0; i < object[handlersProp].length; i++){
        if (object[handlersProp][i] == handler){
          object[handlersProp].splice(i, 1);
          return;
        }
      }
    }
  }
}
var x, y;
var loadingImage = new Image();
var okImage = new Image();
loadingImage.src = "images/loading.gif";
okImage.src = "images/ok.gif";
if (window.opera || (navigator.userAgent.indexOf('MSIE') > -1)){
  getM_x = function (){
  Xadder = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft; 
  return event.clientX + Xadder;}
  getM_y = function (){
    Yadder = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
    return event.clientY + Yadder;
  }
}
else{ // Mozilla
  addHandler(document, 'mousemove', function(e){
    x = e.pageX;
    y = e.pageY;
  });
  getM_x = function (){
    return x;
  }
  getM_y = function (){
    return y;
  }
}
function showOk(){
  var imgLoading = document.getElementById("_loading_");
  with (imgLoading){
    src = okImage.src;
    style.visibility = "visible";
  }
}
function hideOk(){
  if(document.getElementById("_loading_")) document.getElementById('_loading_').style.visibility = "hidden";
  removeHandler(document, 'mousemove', hideOk);
}
function showLoading(){
  var imgLoading = document.getElementById("_loading_");
  if(!imgLoading){
    imgLoading = document.createElement("img");
    with(imgLoading){
      id = "_loading_";
      style.position = "absolute";
      style.visibility = "hidden";
    }
    document.body.appendChild(imgLoading);
  }
  with(imgLoading){
    src = loadingImage.src;
    style.left = (getM_x() + Offset_X) + "px";
    style.top = (getM_y() + Offset_Y) + "px";
    style.visibility = "visible";
  }
}
function hideLoading(){
  if(document.getElementById("_loading_")) document.getElementById("_loading_").style.visibility = "hidden";
}
function doBuyNowGet(link){
  showLoading();
  var reqAddCart = new JsHttpRequest();
  reqAddCart.onreadystatechange = function(){
    if (reqAddCart.readyState == 4){
      if (reqAddCart.responseJS){
        document.location.href = reqAddCart.responseJS.ajax_redirect;
        return;
      }
      else{
        document.getElementById('divShoppingCart').innerHTML = '<table border="0" width="100%" cellspacing="0" cellpadding="0">'+(reqAddCart.responseText||'')+'</table>';
        hideLoading();
        if (SHOW_ADDED){
          showOk();
          timerID = setTimeout("addHandler(document, \'mousemove\', hideOk)", 500);
        }
      }
    }
  }
  reqAddCart.caching = false;
  reqAddCart.open('GET', link, true);
  reqAddCart.send(null);
}
function doAddProduct(form){
  showLoading();
  var reqAddCart = new JsHttpRequest();
  reqAddCart.onreadystatechange = function(){
    if (reqAddCart.readyState == 4){
      if (reqAddCart.responseJS){
        document.location.href = reqAddCart.responseJS.ajax_redirect;
        return;
      }
      else{
        var frm = form.elements;
        for(var i=0; i<frm.length; i++){
          if (frm[i].name == "cart_quantity"){
            if (Number(frm[i].value) <= 0){
              frm[i].value = 1;
              hideLoading();
              return;
            }
          }
        }
        document.getElementById('divShoppingCart').innerHTML = '<table border="0" width="100%" cellspacing="0" cellpadding="2">'+(reqAddCart.responseText||'')+'</table>';
        if (SHOW_ADDED){
          showOk();
          timerID = setTimeout("addHandler(document, \'mousemove\', hideOk)", 500);
        }
      }
    }
  }
  var senddata = new Object();
  var fe = form.elements;
  for(var i=0; i<fe.length; i++){
  if (fe[i].type=="radio" || fe[i].type=="checkbox"){
    if (fe[i].checked) senddata[fe[i].name] = fe[i].value;
    }
    else{
      senddata[fe[i].name] = fe[i].value;
    }
  }
  var url = 'ajax_shopping_cart.php?' + (senddata.products_id ? 'products_id='+senddata.products_id+'&' : "") + 'action=add_product';
  reqAddCart.caching = false;
  reqAddCart.open(form.method, url, true);
  reqAddCart.send(senddata);
  return false;
}
function doAddProductInfo(form){
  showLoading();
  var reqAddCart = new JsHttpRequest();
    reqAddCart.onreadystatechange = function(){
    if (reqAddCart.readyState == 4){
      if (reqAddCart.responseJS){
        document.location.href = reqAddCart.responseJS.ajax_redirect;
        return;
      }
      else{
        var quantity = document.getElementById('qty');
        if (Number(quantity.value) <= 0){
          alert("Pour retirer un article de votre panier, veuillez cliquer sur l'icone corbeille\nou l'élément supprimer de \'Mon Panier\'.");
          quantity.value = 1;
          hideLoading();
          return;
        }
        document.getElementById('divShoppingCart').innerHTML = '<table border="0" width="100%" cellspacing="0" cellpadding="0">'+(reqAddCart.responseText||'')+'</table>';
        if (SHOW_ADDED){
          showOk();
          timerID = setTimeout("addHandler(document, \'mousemove\', hideOk)", 500);
        }
      }
    }
  }
  var senddata = new Object();
  var fe = form.elements;
  for(var i=0; i<fe.length; i++){
    if (fe[i].type=="radio" || fe[i].type=="checkbox"){
      if (fe[i].checked) senddata[fe[i].name] = fe[i].value;
    }
    else{
      senddata[fe[i].name] = fe[i].value;
    }
  }
  var url = 'ajax_shopping_cart.php?' + (senddata.products_id ? 'products_id='+senddata.products_id+'&' : "") + 'action=addproduct_info';
  reqAddCart.caching = false;
  reqAddCart.open(form.method, url, true);
  reqAddCart.send(senddata );
  return false;
}
function doUpdProduct(form){
  showLoading();
  var reqAddCart = new JsHttpRequest();
  reqAddCart.onreadystatechange = function(){
    if (reqAddCart.readyState == 4){
      if (reqAddCart.responseJS){
        document.location.href = reqAddCart.responseJS.ajax_redirect;
        return;
      }
      else{
        var frm = form.elements;
        for(var i=0; i<frm.length; i++){
          if (frm[i].name == "cart_quantity"){
            if (Number(frm[i].value) <= 0){
              alert("Pour retirer un article de votre panier, veuillez cliquer\nsur l'élément corbeille.");
              frm[i].value = 1;
              hideLoading();
              return;
            }
          }
        }
        document.getElementById('divShoppingCart').innerHTML = '<table border="0" width="100%" cellspacing="0" cellpadding="0">'+(reqAddCart.responseText||'')+'</table>';
        //DEBUT MAJ du total panier sur shopping_cart.php
        try{
          document.getElementById('sTotalCartShoppingCart').innerHTML = document.getElementById('sTotalCartShoppingCartBox').innerHTML;
        }
        catch(err){ 
          var error=err.description;
        }
        //FIN MAJ du total panier sur shopping_cart.php
        if (SHOW_ADDED){
          showOk();
          timerID = setTimeout("addHandler(document, \'mousemove\', hideOk)", 500);
        }
      }
    }
  }
  var senddata = new Object();
  var fe = form.elements;
  for(var i=0; i<fe.length; i++){
  if (fe[i].type=="radio" || fe[i].type=="checkbox"){
    if (fe[i].checked ) senddata[fe[i].name] = fe[i].value;
    }
    else{
      senddata[fe[i].name] = fe[i].value;
    }
  }
  var url = 'ajax_shopping_cart.php?' + (senddata.products_id ? 'products_id='+senddata.products_id+'&' : "") + 'action=upd_product';
  reqAddCart.caching = false;
  reqAddCart.open(form.method, url, true);
  reqAddCart.send(senddata);
  return false;
}

