﻿var swfu;

$().ready(function () {

    swfu = new SWFUpload({
        // Flash Settings
        flash_url: "/Media/script/swfupload/swfupload.swf",
        flash9_url: "/Media/script/swfupload/swfupload_fp9.swf",
        // Backend Settings
        upload_url: "/customer-issue-file",
        // File Upload Settings
        file_types: "*.jpg;*.gif;*.jpeg;*.png;*.zip;*.rar;*.doc;*.docx;*.pdf;*.xls;*.xlsx;*.rtf;*.txt",
        file_size_limit: 0,
        file_upload_limit: 0,

        custom_settings: {
            upload_target: "divFileProgressContainer"
        },


        // Button Settings
        button_image_url: "/Media/images/file_upload.png",
        button_width: 144,
        button_height: 30,
        button_text_top_padding: 3,
        button_text_left_padding: 36,
        button_text_style: ".button { font-family: Arial, sans-serif; font-size: 13px; }",
        button_placeholder_id: "FileUploadHandle",
        button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
        button_cursor: SWFUpload.CURSOR.HAND,

        // Event Handler Settings - these functions as defined in Handlers.js
        //  The handlers are not part of SWFUpload but are part of my website and control how
        //  my website reacts to the SWFUpload events.
        swfupload_preload_handler: preLoadSWF,
        swfupload_load_failed_handler: loadFailedSWF,
        file_queue_error_handler: fileQueueErrorSWF,
        file_dialog_complete_handler: fileDialogCompleteSWF,
        upload_progress_handler: uploadProgressSWF,
        upload_error_handler: uploadErrorSWF,
        upload_success_handler: uploadSuccessSWF,
        upload_complete_handler: uploadCompleteSWF,
        // Debug Settings
        debug: false

    });
});


function preLoadSWF() {
	if (!this.support.loading) {
		//alert("You need the Flash Player 9.028 or above to use SWFUpload.");
		return false;
	}
}

function loadFailedSWF() 
{
	alert("Something went wrong while loading SWFUpload. If this were a real application we'd clean up and then give you an alternative");
}


function fileQueuedSWF(file) {
	try {
	} catch (ex) {
		this.debug(ex);
	}
}

function fileQueueErrorSWF(file, errorCode, message) {
	try {
            switch (errorCode) {
                case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
                alert("Вы хотите загрузить слишком много файлов.");
                break;
            case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                alert("You have selected empty file.");
                break;
            case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                alert("Вы хотите загрузить слишком большой файл.");
                break;
            case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
            case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
            default:
                    alert(message);
                    break;
            }
	} catch (ex) {
		this.debug(ex);
	}

}

function fileDialogCompleteSWF(numFilesSelected, numFilesQueued) {
	try {
		if (numFilesQueued > 0) {
			this.startUpload();
		}
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadProgressSWF(file, bytesLoaded)
{
	try {
		var percent = Math.ceil((bytesLoaded / file.size) * 100);

		var progress = new FileProgress(file);
		progress.setProgress(percent);
		if (percent === 100) {
			progress.toggleCancel(false, this);
		} else {
			progress.toggleCancel(true, this);
		}
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadSuccessSWF(file, serverData)
{
    try {
        var arr;
        var str = serverData;
        eval("arr=" + str);
        if (arr.result == "ok") {
            customerIssueFiles.create(arr.data);
        } else {
            customerIssueFiles.showErrors(arr.errors);
        }
    } catch (ex) {
            this.debug(ex);
    }
}

function uploadCompleteSWF(file)
{
	try {
		/*  I want the next upload to continue automatically so I'll call startUpload here */
		if (this.getStats().files_queued > 0) {
			this.startUpload();
		} else {
			var progress = new FileProgress(file);
			progress.destroy();
		}
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadErrorSWF(file, errorCode, message) {
    var progress;
    try {
            switch (errorCode) {
            case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
            case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
                    try {
                            progress = new FileProgress(file);
                            progress.destroy();
                    }
                    catch (ex1) {
                            this.debug(ex1);
                    }
                    break;
            case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
            default:
                    alert(message);
                    break;
            }
    } catch (ex3) {
            this.debug(ex3);
    }
}


/* ******************************************
 *	FileProgress Object
 *	Control object for displaying file info
 * ****************************************** */

function FileProgress(file) {
	this.fileProgressID = "divFileProgress";
	this.fileProgressWrapper = $("#" + this.fileProgressID);

	if (this.fileProgressWrapper.length == 0) 
    {
        this.fileProgressWrapper = $("<div>").attr("class", "progressWrapper").attr("id", this.fileProgressID);
        this.fileProgressElement = $("<div>").attr("class", "progressContainer").appendTo(this.fileProgressWrapper);
        var progressCancel = $("<a>").attr("class", "progressCancel").attr("href", "#").text(" ").appendTo(this.fileProgressElement);
        progressCancel.hide();


        $("<div>").attr("class", "progressName").text(file.name).appendTo(this.fileProgressElement);
        var progressBar = $("<span>").attr("class", "progressBar").attr("id", "pb1").appendTo(this.fileProgressElement);
        $("<div>").attr("class", "progressBarStatus").html("&nbsp;").appendTo(this.fileProgressElement);
        $.blockUI({
            css: {
                border: 'none',
                backgroundColor: 'transparent',
                opacity : 0.6
            },
            message : this.fileProgressWrapper
        });
        progressBar.progressBar({showText: false});
	} else {
            this.fileProgressElement = $(".progressContainer", this.fileProgressWrapper);
            $(".progressName",this.fileProgressElement).text(file.name);
	}
}

FileProgress.prototype.setProgress = function (percentage) {
    $('#pb1').progressBar(percentage);
};
FileProgress.prototype.setComplete = function () {
    $(".progressBar", this.fileProgressElement).addClass("progressBar-Complete");
    $(".progressBar", this.fileProgressElement).css("width", "");
};

FileProgress.prototype.setError = function () {
    $(".progressBar", this.fileProgressElement).addClass("progressBar-Error");
    $(".progressBar", this.fileProgressElement).css("width", "");
};
FileProgress.prototype.setCancelled = function () {
    $(".progressBar", this.fileProgressElement).addClass("progressBar-Error");
    $(".progressBar", this.fileProgressElement).css("width", "");
    this.fileProgressWrapper.remove();
    $.unblockUI();
};

FileProgress.prototype.toggleCancel = function (show, swfuploadInstance) {
    if (show) {
       $(".progressCancel", this.fileProgressElement).show();
    } else {
        $(".progressCancel", this.fileProgressElement).hide();
    }
    if (swfuploadInstance) {
        var fileID = this.fileProgressID;
        $(".progressCancel", this.fileProgressElement).click(function () {
                swfuploadInstance.cancelUpload(fileID);
                return false;
        });
    }
};

FileProgress.prototype.destroy = function () {
    this.fileProgressWrapper.remove();
    $.unblockUI();
};

