(function($){

    $.fn.fileUploader = function(options){
        var that = {};
        that.options = {
            filesMaxCount: 10,
            savePhotoUrl: null,
            deletePhotoUrl: null
        };
        that.options = $.extend(that.options, options);
        
        var $this = $(this);
        
        that.init = function(){

            new $.AjaxUpload('uploadGalleryImageButton', {
                action: that.options.savePhotoUrl,
                name: 'photo',
                data: that.options.data,
                responseType: 'json',
                onSubmit: function(){
                    $("#responseMessage").text("Uploading...").addClass("waiting").show();
                },
                onComplete: function(file, response){
                    
                    $('#responseMessage').hide().removeClass('waiting');
                    
                    if (typeof response === 'undefined' || response.status == "error") {
                        if (response === 'undefined') {
                            var errorMessage = "Can't connect to server";
                        }
                        else {
                            var errorMessage = response.errorMessage;
                        }
                        
                        $('#responseMessage').fadeOut(1000, function(){
                            $(this).html($("<span>" + errorMessage + "</span>").css("color", "#f00")).fadeIn(1000)
                        });
                    }
                    else {
                        that.addPhoto(response.photo);
                    }
                }
                
            });
            
            $this.append($('<div id="uploadedFilesStats" class="uploadedFilesStats"></div>'), $('<div id="responseMessage"></div>'), $('<ul id="uploadedFiles"></ul>'));
            
            $(".delete").livequery('click', function(){
                $(this).unbind('click');
                that.deletePhoto($(this));
            });

            that.updateCounter();
            if (options.photos) {
                for (var i in options.photos) {
                    that.addPhoto(options.photos[i]);
                }
            }
        }
        
        that.addPhoto = function(photo){
            var photoImage = new Image();
            
            $(photoImage).attr({
                src: photo.thumbSrc,
                width: 120,
                height: 90
            }).addClass('uploaded');
            
            $new = $('<div class="fileInfo"></div>');
            $delete = $('<div id="' + photo.photoId + '" class="delete" title="delete file"></div>');

            $new.append($(photoImage));
            $delete.data("photoId", photo.photoId);
            
            $("#uploadedFiles").append($('<li></li>').append($delete, $new).hide().fadeIn(1000));

            if (photo.name) {
                var responseMessage = setting.lang["File"] + " <span>" + photo.name + "</span> " + setting.lang["was uploaded sucessfully"];
                $('#responseMessage').fadeOut(100, function(){
                    $(this).html(responseMessage).fadeIn(1000)
                });
            }
            
            that.updateCounter();
        }
        
        that.deletePhoto = function(toDelete){
            var data = {
                photoId: toDelete.data("photoId")
            };
            
            if (that.options.data && that.options.data.tempId) {
                data.tempId = that.options.data.tempId;
            }
            
            $.post(that.options.deletePhotoUrl, data, function(response){
                toDelete.parents('li').fadeOut(300, function(){
                    $(this).remove();
                    that.updateCounter()
                });
            });
        }
        
        that.updateCounter = function(){
            var uploadedPhotosCount = $("#uploadedFiles").children('li').size();
            $("#uploadedFilesStats").text(uploadedPhotosCount + " " + setting.lang["of"] + " " + that.options.filesMaxCount + " " + setting.lang["available photos uploaded"]);
            $('#upFrame').css({
                opacity: (uploadedPhotosCount == that.options.filesMaxCount) ? 0 : 1
            });
        }
        
        return this.each(function(){
            that.init();
        });
    }
})(jQuery);

