(function($) {

ItfFileUpload = function(file, Q) {
    this.uploaded = false;
    this.file = file;
    this.Q = Q;
    this.$li = this.getLi().prependTo('#photosContainer');    
};


ItfFileUpload.prototype.upload = function() {
    var that = this;
    var Q = that.Q;
    var fil = this.file;
//  console.log("uploading", fil);
    var data = Q.getData(fil);
//    this.$li = this.getLi().appendTo(that.Q.$elem);
    this.Q.isUploading = true;
    var url = Q.options.addURL;
    this.showProgress();
//  $('#progressbar').show();
//    $li.addClass("uploading");
    this.chunkUploader = ChunkUploader({
        'file': fil,
        'url': url,
        'data': data,
        'extra_data': that,
        'callback': function(response) {
            var data = JSON.parse(response.responseText);
      //console.log("data", data);
            if (data.resultUrl) {
                that.markDone(data);              
            } else {
                that.$li.find(".progressStatus").html(response.status);
            }
        },
        'progress': that.doProgress
    });
};

ItfFileUpload.prototype.markDone = function(data) {
    var that = this;
    //console.log(data);
    //alert("hi");
    this.uploaded = true;
    //var d = JSON.parse(data.responseText);
    this.$li.removeClass("uploadFileItem").addClass("photoContainer").empty();
    var $img = $('<img />').attr("src", data.thumbnail).appendTo(that.$li);
    var $title = $('<input />').addClass("photoTitle").val(data.title).appendTo(that.$li);
    var $delete = $('<span />').addClass("deleteItem").text("X").appendTo(that.$li);
    var $id = $('<input />').attr("hidden", "hidden").addClass("photoId").val(data.id).appendTo(that.$li);
    this.Q.uploadNext();
};


ItfFileUpload.prototype.showProgress = function() {
    var that = this;
    //console.log(that);
    this.$li.find(".fileProgress").show();
};

ItfFileUpload.prototype.doProgress = function(progress) {
//    console.log(progress);
//    var that = this;
//    console.log(that);
//    console.log(progress);
//    GLOB = progress;
    var widthPercent = progress.progress * 100;
    progress.extra.$li.find(".progressBar").css({'width': widthPercent + "%"});
    //progress.extra.$li.find(".progressBar").text(progress.progress);
};

ItfFileUpload.prototype.getLi = function() {
    var that = this;
    var $li = $('<li />').addClass("uploadFileItem");
    var $title = $('<div />').addClass("uploadFileTitle").text(that.file.name).appendTo($li);
    var $progress = $('<div />').addClass("fileProgress").hide().appendTo($li);
    var $progressBar = $('<div />').addClass("progressBar").appendTo($progress);
    var $progressStatus = $('<div />').addClass("progressStatus").appendTo($progress);
    return $li; 
};

ItfUploadQueue = function(options, $elem) {
    var that = this;
    this.options = options;
    this.files = [];    
    this.isUploading = false;
    this.len = function() {
        return this.files.length;
    }
    this.$elem = $elem;
    this.$ul = $("<ul />").addClass("uploadFileList").appendTo($elem);
};

ItfUploadQueue.prototype.uploadNext = function() {
    for (var i=0; i<this.files.length; i++) {
        if (this.files[i].uploaded === false) {
            this.files[i].upload();
            return;
        }
    }        
    this.isUploading = false;
    return;
};


ItfUploadQueue.prototype.addFile = function(f) {
    var that = this;
    var fileUpload = new ItfFileUpload(f, that);
    this.files.push(fileUpload);
//    this.addToList(f);
//    var no = this.len() - 1;
    if (!this.isUploading) {
        fileUpload.upload();
    }
};

ItfUploadQueue.prototype.getData = function(f) {
    var that = this;
    return {
        'name': f.name,
        'id': that.options.id
        //FIXME: add 'type'
    }
};



$.fn.uploadQueue = function(options) {
    var that = this;
    var dataOptions = {
    //add data- options    
    }        
    var o = $.extend({
        'id': '0',
        'addURL': '/add'
    }, options, dataOptions);    
    
    //console.log("o", o);
    var Q = new ItfUploadQueue(o, that);
   
    var $fileInput = $(this).find('input[type=file]'); //If there are any <input type=file> elements with the file drop container, bind to their change event.
    if ($fileInput.length > 0) {
        $fileInput.change(function() {
            var t = this;
            for (var i=0; i<t.files.length;i++) {
                var f = t.files[i];
                Q.addFile(f);      
            }
        });        
    }



    var f = this.get(0); //get DOM object, not jquery element, enable drag / droppability of files from desktop
    f.addEventListener("dragenter", function(e) { e.stopPropagation(); e.preventDefault(); return false; }, false);
    f.addEventListener("dragover", function(e) { e.stopPropagation(); e.preventDefault(); return false; }, false);
    f.addEventListener("drop", function(e) {
        e.preventDefault();
        e.stopPropagation();  
        var files = e.dataTransfer.files;
        for (var i=0; i<files.length; i++) {
            var fil = files[i];
            Q.addFile(fil);
        }
    }, false);
};


})(jQuery);
