var curry = require('./curry'),
	map = require('./map'),
	each = require('./each'),
	json = require('./json')

module.exports = {
	request: request,
	get: curry(request, 'get'),
	post: curry(request, 'post'),
	jsonGet: curry(sendJSON, 'get'),
	jsonPost: curry(sendJSON, 'post')
}

var XHR = window.XMLHttpRequest || function() { return new ActiveXObject("Msxml2.XMLHTTP"); }

function request(method, url, params, callback, headers, opts) {
	var xhr = new XHR()
	method = method.toUpperCase()
	headers = headers || {}
	opts = opts || {}
	xhr.onreadystatechange = function() {
		var err, result
		try {
			if (xhr.readyState != 4) { return }
			if (xhr.status != 200) { return callback(new Error(xhr.status)) }
			result = (opts.json ? json.parse(xhr.responseText) : xhr.responseText)
			if (xhr.getResponseHeader('Content-Type') == 'application/json') { result = json.parse(result) }
		} catch(e) {
			err = e
		}
		if (err || typeof result != undefined) {
			_abortXHR(xhr)
			callback(err, result)
		}
	}
	var data = null,
		encode = (opts.encode !== false),
		queryArr = map(params, function(value, key) {
			return (encode ? encodeURIComponent(key) : key) + '=' + (encode ? encodeURIComponent(json.stringify(value)) : value) })
	if (method == 'GET') {
		if (url.indexOf('?') == -1) { url = url + '?' }
		url += queryArr.join('&')
	} else if (method == 'POST') {
		data = queryArr.join('&')
	}
	xhr.open(method, url, true)
	if (method == 'POST') {
    if (!headers['Content-Type']) { headers['Content-Type'] = "application/x-www-form-urlencoded" }
		if (!headers['Content-length']) { headers['Content-length'] = data.length }
		if (!headers['Connection']) { headers['Connection'] = 'close' }
    each(headers, function(val, key) { xhr.setRequestHeader(key, val) })
	}
	xhr.send(data)
}

function sendJSON(method, url, params, callback) {
	return request(method, url, params, callback, { 'Content-Type':'application/json' }, { json:true })
}

function _abortXHR(xhr) {
	try {
		if('onload' in xhr) {
			xhr.onload = xhr.onerror = xhr.ontimeout = null;
		} else if('onreadystatechange' in xhr) {
			xhr.onreadystatechange = null;
		}
		if(xhr.abort) { xhr.abort(); }
	} catch(e) {}
}

@@ -1000,16 +1000,17 @@
 %0A%09%09%7D%0A%09%7D%0A
+%0A
 %09var dat
@@ -1017,20 +1017,48 @@
 a = null
-,%0A%09%09
+%0A%0A%09if (method == 'GET') %7B%0A%09%09var 
 encode =
@@ -1130,20 +1130,17 @@
 , key) %7B
-%0A%09%09%09
+ 
 return (
@@ -1220,30 +1220,14 @@
 ent(
-json.stringify(
 value)
-)
  : v
@@ -1240,89 +1240,73 @@
 %7D)%0A%09
-if (method == 'GET') %7B%0A%09%09if (url.indexOf('?') == -1) %7B url = url + '?' %7D%0A%09%09url
+%09%09url += (url.indexOf('?') == -1 && queryArr.length ? '?' : '')
  +
-=
  que
@@ -1362,33 +1362,37 @@
 %09data = 
-queryArr.join('&'
+json.stringify(params
 )%0A%09%7D%0A%09xh
@@ -1442,20 +1442,18 @@
 OST') %7B%0A
-    
+%09%09
 if (!hea
@@ -1688,12 +1688,10 @@
 ' %7D%0A
-    
+%09%09
 each

Fix POST data encoding - just json stringify the content