/// 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 class='uploading' id='" + id + "_uploading'>Uploading... <input type='button' value='Cancel'/></div>"));
            container.append($("<div id='" + id + "_swf' class='btnUpload'></div>"));
            container.append($("<div id='" + id + "_fileInfo' class='fileInfo'></div>"));
            container.append($("<input type='hidden' class='btnCancel' name='" + id + "_filename'/>"));
            container.append($("<div id='" + id + "_response' class='response'></div>"));
            $(this).before(container).remove();
            $("div.ProgressBar", container).hide();
            $("div[id$=_uploading]", container).hide();


            // Instantiate the uploader SWF
            //var swfu = null;
            // width and height is manipulated by functions below so we need to store it
            var width = 110, height = 22;
            
            if (options) {
                width = options.width || width;
                height = options.height || height;
            }
            var defaults = {
                flash_url: "swfupload.swf",
                upload_url: "/",
                file_size_limit: "200 MB",
                file_types: "*.*",
                file_types_description: "All Files",
				file_queue_limit: 5,
				hidden_on_load: 0,
                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: 20,
                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 upload failed: " + msg); },

                // Called when an error occurs during upload
                upload_error_handler: function(file, code, msg) { alert("Sorry, your file upload failed: " + msg); },

                // Called when upload is beginning (switches controls to uploading state)
                upload_start_handler: function(file) {
                    swfu.setButtonDimensions(0, height);
                    $("input[name$=_filename]", container).val("");
                    $("div[id$=_response]", container).html("");
                    $("div.ProgressBar div", container).css("width", "0px");
                    $("div.ProgressBar", container).show();
                    $("div[id$=_uploading]", container).show();
                    //$("div[id$=_fileInfo]", container).html("").hide();                   
                    $("div[id$=_fileInfo]", container).html("<b>{0}</b> ({1} KB)"
                                .replace("{0}", file.name)
                                .replace("{1}", Math.round(file.size / 1024))
                            ).show();

                    if (options.disableDuringUpload)
                        $(options.disableDuringUpload).attr("disabled", "disabled");
                    //SS: add a onUploadStart hook for the called to do something on upload complete
					if (options.onUploadStart)
                    	eval(options.onUploadStart);
                },

                // Called when upload completed successfully (puts success details into hidden fields)
                upload_success_handler: function(file, response) {
                	//console.log(response);
                	response = response.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
                    $("input[name$=_filename]", container).val(file.name); 
                    //SS: Handle JSON response (convert json string to json object)
                    if (response.charAt(0) == "{")
	                    response = (new Function("return " + response))();

                	if ((typeof response == "object" && response.status == "success") || response == "success"){
                    	$("div[id$=_response]", container).html('File successfully uploaded!').removeClass("error").addClass("success");
						//SS: add a onSuccess hook for the caller to do something on upload success
						if (options.onSuccess) {
							dispatch(options.onSuccess,[response]);		// execute callback function
                    		//eval(options.onSuccess);
							//options.onSuccess();
						}
                    }
                    else {
                    	$("div[id$=_response]", container).html(response).removeClass("success").addClass("error");
                    }
                },

                // 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();
                        //$("div[id$=_fileInfo]", container).show();
                        $("div[id$=_uploading]", container).hide();
						try{
                       		swfu.setButtonDimensions(width, height);
						}
						catch(e){}
                    };
                    if ($("input[name$=_filename]", 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");
                    //SS: add a onComplete hook for the caller to do something on upload complete
					if (options.onComplete) {
                    	//eval(options.onComplete);
						dispatch(options.onComplete);		// execute callback function
					}
                },

                // 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: 500, queue: false });
                }
				/*,
				swfupload_loaded_handler: function(){			
					if (options.hidden_on_load == 1) {       
						swfu.getMovieElement().style.display = "none";
					}			
				}*/
            };
			
            var swfu = new SWFUpload($.extend(defaults, options || {}));
			
			// SS: if the swf will be hidden on load (for eg, in a non-active tab) we need to explictly hide this object to prevent FF Win from crashing!		
			if (options.hidden_on_load == 1) {
				//alert('hi');                
				swfu.getMovieElement().style.display = "none";
			}				

            // Called when user clicks "cancel" (forces the upload to end, and eliminates progress bar immediately)
            $("div[id$=_uploading] input[type='button']", container).click(function() {
                swfu.cancelUpload(null, false);
            });

            // Give the effect of preserving state, if requested
            if (options.existingFilename || "" != "") {
                $("div[id$=_fileInfo]", container).html("<b>{0}</b> ({1} KB)"
                                .replace("{0}", options.existingFilename)
                                .replace("{1}", options.existingFileSize ? Math.round(options.existingFileSize / 1024) : "?")
                            ).show();
                $("input[name$=_filename]", container).val(options.existingFilename);
            }
            if (options.existingGuid || "" != "")
                $("div[id$=_response]", container).html(options.existingGuid);
        });
    };
    
    //SS: invoke a function dynamically
    dispatch = function (fn, args) {
        f = (typeof fn == "function") ? fn : window[fn];  // Allow fn to be a function object or the name of a global function
        if (f)
        	return f.apply(this, args || []);  // args is optional, use an empty array by default
        else
        	eval(fn);
    }

})(jQuery);
