$(function() {
    var $upload_file = $('.upload_file');

    function endsWith(str, suffix) {
        return str.indexOf(suffix, str.length - suffix.length) !== -1;
    }
    var validateImage = function(file) {
        var types = $upload_file.attr('data-file-type').split(",");
        var check = false;
        $.each(types, function(n, e) {
            if (endsWith(file.name, e)) {
                check = true;
            }
        });
        if (!check) {
            alert($upload_file.attr("data-type-support-message") + $upload_file.attr("data-file-type"));
            return false;
        }
        if (file.size && file.size > parseInt($upload_file.attr('data-max-file-size'))) {
            alert($upload_file.attr("data-max-file-size-message"));
            return false;
        }
        return true;
    };
    $('.upload_file').fileupload({
        url: '/upload_avatar.json?source_type=' + $('.upload_file').attr('data-source-type') +
            '&source_id=' + $('.upload_file').attr('data-source-id'),
        add: function(e, data) {
            if (!validateImage(data.files[0])) {
                return false;
            }
            data.submit();
        },
        formData: function(form) {
            var data = form.serializeArray();
            var auth = null;
            for (var key in data) {
                if (data[key].name == "authenticity_token") {
                    auth = data[key];
                    break;
                }
            }
            return [auth];
        },
        done: function(e, data) {
            var imgSpan = jQuery('#avatar_image');
            var result = data.result.text ? data.result.text() : data.result;
            if(result){
              var o = JSON.parse(result);
              if(o.status == 0){
                imgSpan.attr({
                  "src": o.url
                });
              } else {
                alert(o.message);
              }
            }

        }
    });
});
