
/* Display image preview 
 * input : .thumb_image 
 * output : set id with name like "thumb_{image field name}"
 * */
function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#thumb_' + input.name).attr('src', e.target.result);
        };
        reader.readAsDataURL(input.files[0]);
    }
}
$(document).on('change', '.thumb_image', function() {
    readURL(this);
});


$(document).ready(function () {
    $('body').on('submit', '.ajax_progress', function (e) {
        e.preventDefault();
        $(this).ajaxSubmit({
            target: '#targetLayer',
            beforeSubmit: function () {
                $("#progress-bar").width('0%');
                $("#progress-bar").addClass('active');
                $("#div-progress").show();
            },
            uploadProgress: function (event, position, total, percentComplete) {
                $("#progress-bar").width(percentComplete + '%');
                $("#progress-bar").html('<div id="progress-status">' + percentComplete + ' %</div>')
            },
            error: function (result) {
                //redirect if not authenticated user.
                if (result.status == 422) {
                    $('.form-group').each(function () {
                        $(this).removeClass('has-error');
                        $(this).children(".help-block").html("");
                    });

                    var json = result.responseJSON;
                    $.each(json, function (key, value) {
                        $("input[name='" + key + "'],textarea[name='" + key + "'],select[name='" + key + "'] ").parent().addClass("has-error");
                        $("input[name='" + key + "'],textarea[name='" + key + "'],select[name='" + key + "'] ").next(".help-block").html("<strong>" + value[0] + "</strong>");
                    });
                }
                return false;
            },
            success: function (json) {
                //$('#loader-icon').hide();
                //$("#div-progress").css('display','none');
                //console.log(json);
                
                
            },
            complete: function (json) {
                //$("#div-progress").hide();
                $("#progress-bar").removeClass('active');
                $("#progress-bar").html('<div id="progress-status">completed</div>');
                window.location = json.responseJSON.url;
                //alert(json.responseJSON.result);
                //alert(data.result);
            },
            resetForm: true
        });
    });
}); 
