/**
 * Emulate FormData for some browsers
 * MIT License
 * (c) 2010 François de Metz
 * 
 * USAGE:
 *
 * var data = new FormData();
 * data.append('file', document.getElementById('file').files[0]);
 * 
 * xhr.open('POST', '/', true);
 * xhr.setRequestHeader("Cache-Control", "no-cache");
 * xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
 * // this is really bad
 * if (data.fake) {
 *    xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary="+ data.boundary);
 *    xhr.sendAsBinary(data.toString());
 * } else {
 *    xhr.send(data);
 * }
 *  */
(function(w) {
    if (w.FormData)
        return;
    function FormData() {
        this.fake = true;
        this.boundary = "--------FormData" + Math.random();
        this._fields = [];
    }
    FormData.prototype.append = function(key, value) {
        this._fields.push([key, value]);
    }
    FormData.prototype.toString = function() {
        var boundary = this.boundary;
        var body = "";
        this._fields.forEach(function(field) {
            body += "--" + boundary + "\r\n";
            // file upload
            if (field[1].name) {
                var file = field[1];
                body += "Content-Disposition: form-data; name='"+ field[0] +"'; filename='"+ file.name +"'\r\n";
                body += "Content-Type: application/octet-stream\r\n\r\n";
                body += file.getAsBinary() + "\r\n";
            } else {
                body += "Content-Disposition: form-data; name='"+ field[0] +"';\r\n\r\n";
                body += field[1] + "\r\n";
            }
        });
        body += "--" + boundary +"--";
        return body;
    }
    w.FormData = FormData;
})(window);
