// this is the standalone build entry of AlgoliaSearch
var createAlgoliasearch = require('./create-algoliasearch');

module.exports = createAlgoliasearch(request);

var each = require('foreach');
var Promise = global.Promise || require('es6-promise').Promise;

var JSONPRequest = require('./jsonp-request');

var support = {
  hasXMLHttpRequest: 'XMLHttpRequest' in window,
  hasXDomainRequest: 'XDomainRequest' in window,
  cors: 'withCredentials' in new XMLHttpRequest(),
  timeout: 'timeout' in new XMLHttpRequest()
};

function request(url, opts) {
  return new Promise(function(resolve, reject) {
    // no cors or XDomainRequest, no request
    if (!support.cors && !support.hasXDomainRequest) {
      // very old browser, not supported
      reject(new Error('CORS not supported'));
      return;
    }

    var body = null;
    var req = support.cors ? new XMLHttpRequest() : new XDomainRequest();
    var ontimeout;
    var timedOut;

    if (opts.body !== undefined) {
      body = JSON.stringify(opts.body);
    }

    // do not rely on default XHR async flag, as some analytics code like hotjar
    // breaks it and set it to false by default
    if (req instanceof XMLHttpRequest) {
      req.open(opts.method, url, true);
    } else {
      req.open(opts.method, url);
    }

    if (support.cors && body && opts.method !== 'GET') {
      req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    }

    req.onload = load;
    req.onerror = error;

    if (support.timeout) {
      // .timeout supported by both XHR and XDR,
      // we do receive timeout event, tested
      req.timeout = opts.timeout;

      req.ontimeout = timeout;
    } else {
      ontimeout = setTimeout(timeout, opts.timeout);
    }

    req.send(body);

    // event object not received in IE8, at least
    // but we do not use it, still important to note
    function load(/*event*/) {
      // When browser does not supports req.timeout, we can
      // have both a load and timeout event, since handled by a dumb setTimeout
      if (timedOut) {
        return;
      }

      if (!support.timeout) {
        clearTimeout(ontimeout);
      }

      var response = null;

      try {
        response = JSON.parse(req.responseText);
      } catch(e) {}

      resolve({
        body: response,
        statusCode: req.status
      });
    }

    function error(event) {
      if (timedOut) {
        return;
      }

      if (!support.timeout) {
        clearTimeout(ontimeout);
      }

      // error event is trigerred both with XDR/XHR on:
      //   - DNS error
      //   - unallowed cross domain request
      reject(new Error('Could not connect to host, error was:' + event));
    }

    function timeout() {
      if (!support.timeout) {
        timedOut = true;
        req.abort();
      }

      resolve(new Error('Timeout - Could not connect to endpoint ' + url));
    }

  });
}

request.fallback = function(url, opts) {
  return new Promise(function(resolve, reject) {
    JSONPRequest(url, opts, function JSONPRequestDone(err, content) {
      if (err) {
        reject(err);
        return;
      }

      resolve(content);
    });
  });
};

request.reject = function(val) {
  return Promise.reject(val);
};

request.resolve = function(val) {
  return Promise.resolve(val);
};

request.delay = function(ms) {
  return new Promise(function(resolve/*, reject*/) {
    setTimeout(resolve, ms);
  });
};

var v2Globals = ['AlgoliaSearch', 'AlgoliaSearchHelper', 'AlgoliaExplainResults'];
each(v2Globals, throwWhenUsed);

function throwWhenUsed(fnName) {
  var message = 'You are trying to use a new version of the AlgoliaSearch JavaScript client with an old notation.' +
  ' Please read our migration guide at https://github.com/algolia/algoliasearch-client-js/wiki/Migration-guide-from-2.x.x-to-3.x.x';

  global[fnName] = function() {
    throw new Error(message);
  };
}

@@ -162,39 +162,8 @@
 );%0A%0A
-var each = require('foreach');%0A
 var 
@@ -3403,160 +3403,18 @@
 var 
-v2Globals = %5B'AlgoliaSearch', 'AlgoliaSearchHelper', 'AlgoliaExplainResults'%5D;%0Aeach(v2Globals, throwWhenUsed);%0A%0Afunction throwWhenUsed(fnName) %7B%0A  var m
+migrationM
 essa
@@ -3657,24 +3657,308 @@
 ';%0A%0A
-  global%5BfnName%5D
+// cannot dinamically add these properties to window, fails on IE old versions%0A/*global AlgoliaSearch:true,AlgoliaSearchHelper:true,AlgoliaExplainResults:true*/%0A/*eslint no-unused-vars: %5B2, %7B%22vars%22: %22local%22%7D%5D*/%0AAlgoliaSearch = function() %7B%0A  throw new Error(migrationMessage);%0A%7D;%0A%0AAlgoliaSearchHelper
  = f
@@ -3969,18 +3969,16 @@
 ion() %7B%0A
-  
   throw 
@@ -3992,20 +3992,103 @@
 or(m
+igrationMessage);%0A%7D;%0A%0AAlgoliaExplainResults = function() %7B%0A  throw new Error(migrationM
 essage)
-;%0A  %7D
 ;%0A%7D
+;
 %0A

fix old globals test in IE8