{% load i18n %}
<script type="text/javascript">
function changeAvatar(chg_btn, input, form) {
    var chg_btn_orig_bg = chg_btn.css('background-color'); // ie 7,8: chg_btn.css('background') gets 'undefined'
    form.css({'width': chg_btn.outerWidth()});
    input
    .css({'height': chg_btn.outerHeight()})
    .hover(
        function() {
            chg_btn.css({'background': '#fff'});
        },
        function() {
            chg_btn.css({'background': chg_btn_orig_bg});
        }
    );

    input.change(function() {
        chg_btn.css({'background': chg_btn_orig_bg});
        // check file extension
        var file, filename, ext;    
        var allow = false;
        var allowed_ext = ['jpg','jpeg', 'png', 'gif'];
        if (this.files) { // IE: version lower than 10 doesn't have 'files'
            file = this.files[0];
            filename = file.name || file.fileName;
        } else {
            filename = this.value;
        }
        if (filename.lastIndexOf('.') != -1) { // ext exists
            ext = filename.substr((filename.lastIndexOf('.') + 1)).toLowerCase();
        }
        if (ext) {
            for (var i = 0, len = allowed_ext.length; i < len; i++) {
                if (ext == allowed_ext[i]) {
                    allow = true;
                    break;
                }
            }
        } else {
            feedback(filename + "{% trans " is not supported. Please choose an image file." %}", 'error');
            return false;
        }

        if (!allow) {
            var err_msg = filename + "{% trans " is not supported. File extensions can only be " %}" + allowed_ext.join(', ');
            feedback(err_msg, 'error');
            return false;        
        }

        // check if file size is less than 1MB
        if (file && file.size > 1024*1024) {
            feedback(filename + "{% trans " is too large. Allowed maximum size is 1MB." %}", 'error');
            return false;        
        }

        form.submit();
        return false;
    });
}
</script>
