$(function(){
	
    var dropbox = $('#dropbox'),
    message = $('.message', dropbox);
	
    dropbox.filedrop({
        // The name of the $_FILES entry:
        paramname:'pic',
		
        maxfiles: 5,
        maxfilesize: 3,
        url: 'UploadImagesControl',
		
        uploadFinished:function(i,file,response){
            $.data(file).addClass('done');
        // response is the JSON object that ServletUploadImages returns
        },
		
        error: function(err, file) {
            switch(err) {
                case 'BrowserNotSupported':
                    showMessage('Trình duyệt không hỗ trợ HTML5!');
                    break;
                case 'TooManyFiles':
                    alert('Số file được upload chi nhỏ hơn hoặc bằng 5!');
                    break;
                case 'FileTooLarge':
                    alert(file.name+' quá lớn! Vui lòng chọn file nhỏ hơn 3mb.');
                    break;
                default:
                    break;
            }
        },
		
        // Called before each upload is started
        beforeEach: function(file){
            if(!file.type.match(/^image\//)){
                alert('Chỉ là file hình ảnh!');
				
                // Returning false will cause the
                // file to be rejected
                return false;
            }
        },
		
        uploadStarted:function(i, file, len){
            createImage(file);
            // co the xoa
            $.data(file).addClass('done');
        //
        },
		
        progressUpdated: function(i, file, progress) {
            $.data(file).find('.progress').width(progress);
        }
    	 
    });
	
    var template = '<div class="preview">'+
    '<span class="imageHolder">'+
    '<img />'+
    '<span class="uploaded"></span>'+
    '</span>'+
    '<div class="progressHolder">'+
    '<div class="progress"></div>'+
    '</div>'+
    '</div>'; 
	
	
    function createImage(file){

        var preview = $(template), 
        image = $('img', preview);
			
        var reader = new FileReader();
		
        image.width = 100;
        image.height = 100;
		
        reader.onload = function(e){
			
            // e.target.result holds the DataURL which
            // can be used as a source of the image:
			
            image.attr('src',e.target.result);
        };
		
        // Reading the file as a DataURL. When finished,
        // this will trigger the onload function above:
        reader.readAsDataURL(file);
		
        message.hide();
        preview.appendTo(dropbox);
		
        // Associating a preview container
        // with the file, using jQuery's $.data():
		
        $.data(file,preview);
    }

    function showMessage(msg){
        message.html(msg);
    }

});