﻿/// jQuery plugin to add support for SwfUpload
/// (c) 2008 Steven Sanderson

(function($) {
    $.fn.makeAsyncUploader = function(options) {
        return this.each(function() {
            // Put in place a new container with a unique ID
            var id = $(this).attr("id");
            var container = $("<div class='asyncUploader'/>");
            container.append($("<div class='ProgressBar'> <div>&nbsp;</div> </div>"));
            container.append($("<div id='" + id + "_completedMessage' class='completedMessage'/>"));
            container.append($("<div id='" + id + "_uploading' class='uploading'>Uploading...</div>"));
            container.append($("<div id='" + id + "_swf'/>"));
            container.append($("<a href='#' onclick='return false;' id='"+ id +"_cancel' class='cancelUpload'>Cancel</a>"));
            container.append($("<a href='#' onclick='return false;' id='"+ id +"_remove' class='removeFile'>Remove</a>"));
            container.append($("<input type='hidden' name='img_name[]'/>"));
            container.append($("<input type='hidden' name='img[]'/>"));
			container.append($("<div class='fileupload-wrap_mask'></div>"));
            $(this).before(container).remove();
            $("div.ProgressBar", container).hide();
            $("div[id$=_completedMessage]", container).hide();
            $("div[id$=_uploading]", container).hide();
            $("a[id$=_cancel]", container).hide();
            $("a[id$=_remove]", container).hide();
			

            // Instantiate the uploader SWF
            var swfu;
            var width = 241, height = 20;
            if (options) {
                width = options.width || width;
                height = options.height || height;
            }
            var defaults = {
                flash_url: "/js/fileupload/swfupload.swf",
                upload_url: "/Home/AsyncUpload",
                file_size_limit: "3 MB",
				file_queue_limit : 0,

                file_types: "*.*",
                file_types_description: "All Files",
                debug: false,

                button_image_url: "blankButton.png",

                button_width: width,
                button_height: height,
                button_placeholder_id: id + "_swf",
                //button_text: "<font face='Arial' size='13pt'>Choose file</font>",
                button_text_left_padding: (width - 70) / 2,
                //button_text_top_padding: 1,

                // Called when the user chooses a new file from the file browser prompt (begins the upload)
                file_queued_handler: function(file) { swfu.startUpload(); },

                // Called when a file doesn't even begin to upload, because of some error
                file_queue_error_handler: function(file, code, msg) { alert("Sorry, your file wasn't uploaded: " + msg); },

                // Called when an error occurs during upload
                upload_error_handler: function(file, code, msg) { alert("Sorry, your file wasn't uploaded: " + msg); },

                // Called when upload is beginning (switches controls to uploading state)
                upload_start_handler: function() {
                    swfu.setButtonDimensions(0, height);
                    $("input[name$='img_name[]']", container).val("");
                    $("input[name$='img[]']", container).val("");
                    $("div.ProgressBar div", container).css("width", "0px");
                    $("div.ProgressBar", container).show();
                    $("div[id$=_uploading]", container).show();
                    $("a[id$=_cancel]", container).show();
                    $("div[id$=_completedMessage]", container).html("").hide();

                    if (options.disableDuringUpload)
                        $(options.disableDuringUpload).attr("disabled", "disabled");
                },

                // Called when upload completed successfully (puts success details into hidden fields)
                upload_success_handler: function(file, response) {
                    response = response.replace('_x100.','.').replace('_100x.','.').replace('_100x100.php','.jpg');
                    $("input[name$='img_name[]']", container).val(file.name);
                    $("input[name$='img[]']", container).val(response);
                    $("div[id$=_completedMessage]", container).html("{0}"
                                .replace("{0}", abridge(file.name, 20))
                                .replace("{1}", Math.round(file.size / 1024))
                            );
                },
				

                // Called when upload is finished (either success or failure - reverts controls to non-uploading state)
                upload_complete_handler: function() {
                    var clearup = function() {
                        $("div.ProgressBar", container).hide();
                        $("a[id$=_cancel]", container).hide();
                        $("div[id$=_completedMessage]", container).show();
                        $("a[id$=_remove]", container).show();
                        $("div[id$=_uploading]", container).hide();
                        swfu.setButtonDimensions(width, height);
                    };
                    if ($("input[name$='img_name[]']", container).val() != "") // Success
                        $("div.ProgressBar div", container).animate({ width: "100%" }, { duration: "fast", queue: false, complete: clearup });
                    else // Fail
                        clearup();

                    if (options.disableDuringUpload)
                        $(options.disableDuringUpload).removeAttr("disabled");
                },

                // Called periodically during upload (moves the progess bar along)
                upload_progress_handler: function(file, bytes, total) {
                    var percent = 100 * bytes / total;
                    $("div.ProgressBar div", container).animate({ width: percent + "%" }, { duration: 250, queue: false });
                }
            };
            swfu = new SWFUpload($.extend(defaults, options || {}));

            // Called when user clicks "cancel" (forces the upload to end, and eliminates progress bar immediately)
            $("a[id$='_cancel']", container).click(function() {
                swfu.cancelUpload(null, false);
            });
			
            // Called when user clicks "remove" (removes input values and completed message, and tries to unlink file)
            $("a[id$='_remove']", container).click(function() {
				$.ajax({
				   url: "?kep_torles=" + $("input[name$='img[]']", container).val(),
				   success: function(){
					    $("input[name$='img_name[]']", container).val("");
						$("input[name$='img[]']", container).val("");
						$("div[id$=_completedMessage]", container).hide();
						$("a[id$=_remove]", container).hide();
					}
				});
            });

            // Give the effect of preserving state, if requested
            if (options.existingFilename || "" != "") {
                $("div[id$=_completedMessage]", container).html("Uploaded <b>{0}</b> ({1} KB)"
                                .replace("{0}", options.existingFilename)
                                .replace("{1}", options.existingFileSize ? Math.round(options.existingFileSize / 1024) : "?")
                            ).show();
                $("input[name$='img_name[]']", container).val(options.existingFilename);
            }
            if (options.existingGuid || "" != "")
                $("input[name$='img[]']", container).val(options.existingGuid);
            
            // Levágja a megjelenítendő szöveget
            function abridge(text, maxLength) {
                if (text.length > maxLength) {
                    separator = "...";
                    //a 4 karaketrnyi kiterjesztés miatt van -2 a számítás végén. Így az eleje 2-vel rövidebb, a vége pedig 2-vel hosszabb.
                    textStart = text.substr(0, ((maxLength-separator.length)/2)-2);
                    textEnd = text.substr((text.length-(maxLength-separator.length)/2)-2);
                    text = textStart + separator + textEnd;
                }
                return text;
            }
        });
    }
})(jQuery);