/// class ProspectDirector.Web.UI.FeatureSets.Editors.FileUploadEditorDialog
/// using ProspectDirector.Web.UI.Dialog

/**
@class FileUploadEditorDialog
@namespace Web.UI.FeatureSets.Editors
@extends Web.UI.Dialog
@constructor
**/
ProspectDirector.Web.UI.FeatureSets.Editors.FileUploadEditorDialog = ProspectDirector.Web.UI.Dialog.extend({

    //================================
    // FIELDS
    //================================

    _uploadComponent: null,
    _result: null,

    //================================
    // CONSTRUCTOR
    //================================

    init: function (options) {

        this.options = $.extend(true, {
            config: {
                modal: true,
                iframe: false,
                height: 120,
                width: 400,
                minHeight: 120,
                minWidth: 400,
                resizable: false
            }
        }, options);

        this._super(this.options);

        this.render();
        this.activate();

    },

    //================================
    // PROPERTIES
    //================================

    get_container: function () {
        return this.get_window().DOM().get_content();
    },

    get_selectButtonWrapper: function () {
        return this.get_container().find("[data-id=upload-container-select-files-wrapper]");
    },

    get_uploadButton: function () {
        return this.get_container().find("[id=upload-container-select-files]");
    },

    get_okButton: function () {
        return this.get_container().find("BUTTON[data-id=ok]");
    },

    get_cancelButton: function () {
        return this.get_container().find("BUTTON[data-id=cancel]");
    },

    get_uploadComponent: function () {
        return this._uploadComponent;
    },

    get_progressText: function () {
        return this.get_container().find("DIV[data-id=progress-txt]");
    },

    get_progressBar: function () {
        return this.get_container().find("DIV[data-id=progress-bar]");
    },

    get_progressBarIcon: function () {
        return this.get_container().find("DIV[data-id=progress-bar-icon]");
    },

    get_progressWrapper: function () {
        return this.get_container().find("[data-id=progress-wrapper]");
    },

    //================================
    // EVENT HANDLERS
    //================================

    _okButton_onClick: function (e) {

        this.hide({
            command: "ok",
            data: this._result
        });

    },

    _cancelButton_onClick: function (e) {
        this.hide();
    },

    uploadComponent_onFilesAdded: function (sender, e) {

        var that = this;

        this.get_progressWrapper().show();
        this.get_selectButtonWrapper().hide();
        this._setProgressText("Preparing upload...");

        setTimeout(function () {
            that.get_uploadComponent().start();
        }, 250);
        
    },

    uploadComponent_onUploadProgress: function (sender, e) {

        this._setProgressText("Upload progress... {0}% complete.", e.percent);
        this.get_progressBarIcon().css({
            width: e.percent + "%"
        });

    },

    uploadComponent_onError: function (sender, e) {

        sender.stop();

        if (e.status === 400) {

            var response = JSON.parse(e.response);

            PD.Web.UI.MessageDialog.error({
                title: "Upload Error",
                message: response.error.message
            });

            this.close();

            return;

        }

        if (e.code === -300) {

            sender.stop();

            ProspectDirector.Types.Core.Confirmation.show({
                icon: "SIGN_WARNING.PNG",
                title: "Cannot Read File",
                message: "The file \"" + e.file.name + "\" is being used by another process and cannot be uploaded.<br/><br/>This may be due to the file be open for editing in another program.",
                commands: [{ command: "ok", label: "OK" }]
            });

        }

        this.get_progressBarIcon().css({
            backgroundImage: "url(" + ProspectDirector.RUNTIME.resolveUrl("~/Application/Icons/Misc/ProgressBar_Error.gif") + ")"
        });

    },

    uploadComponent_onUploadComplete: function (sender, e) {

        this.hide({
            command: "ok",
            data: {
                id: e[0].target_name,
                name: e[0].name
            }
        });

    },

    //================================
    // PUBLIC METHODS
    //================================

    activate: function () {

        var that = this;

        this._uploadComponent = new plupload.Uploader({
            runtimes: "html5,silverlight,flash,html4",
            browse_button: "upload-container-select-files",
            container: "upload-container",
            urlstream_upload: true,
            multi_selection: false,
            max_file_size: "2gb",
            chunk_size: "1024kb",
            unique_names: true,
            url: ProspectDirector.RUNTIME.resolveUrl("~/application/handlers/Uploads.ashx"),
            flash_swf_url: ProspectDirector.RUNTIME.resolveUrl("~/areas/shared/assets/external/misc/plupload/moxie.swf"),
            silverlight_xap_url: ProspectDirector.RUNTIME.resolveUrl("~/areas/shared/assets/external/misc/plupload/moxie.xap")
        });

        this.get_uploadComponent().bind('FilesAdded', $.proxy(this.uploadComponent_onFilesAdded, this));
        this.get_uploadComponent().bind('UploadProgress', $.proxy(this.uploadComponent_onUploadProgress, this));
        this.get_uploadComponent().bind('UploadComplete', $.proxy(this.uploadComponent_onUploadComplete, this));
        this.get_uploadComponent().bind('Error', $.proxy(this.uploadComponent_onError, this));

        this.get_uploadComponent().init();
        this.get_uploadComponent().refresh();

        this.get_okButton().on("click", $.proxy(this._okButton_onClick, this));
        this.get_cancelButton().on("click", $.proxy(this._cancelButton_onClick, this));

        this.get_window().DOM().resize();


        // Below "onmouseover" handler is required to get plupload to play nice with IE v9 and IE v10.
        this.get_uploadButton().on("mouseover", function () {
            if (that.get_uploadComponent() != null) {
                that.get_uploadComponent().refresh();
            }
        });

    },

    render: function () {

        var content = [
            "<div id='upload-container' style=\"position:absolute;top:10px;left:10px;right:10px;bottom:10px;box-sizing:border-box;\">",
                "<div data-id='upload-container-select-files-wrapper' style='height:70px;'>",
                    "<table style='height:100%;width:100%;'>",
                        "<tr>",
                            "<td style='vertical-align:middle;text-align:center;'>",
                                "<button id='upload-container-select-files' data-id=\"select\" class=\"-pd-button\" style='margin-right:10px;font-size:13px;'>",
                                    "<img src='" + ProspectDirector.RUNTIME.resolveUrl("~/Areas/Shared/Assets/Internal/Icons/32x32/folder_document.png") + "'/>",
                                    "<br/>",
                                    "Select File...",
                                "</button>",
                            "</td>",
                        "</tr>",
                    "</table>",
                "</div>",
                "<div data-id='progress-wrapper' style='display:none;padding-top:12px;'>",
                    "<div data-id='progress-txt' style='height:19px;font-size:12px;'>Pending...</div>",
                    "<div data-id='progress-bar' style='position:relative;overflow:hidden;height:19px;border:1px solid #CCCCCC;background-image:url(" + ProspectDirector.RUNTIME.resolveUrl("~/Application/Icons/Misc/ProgressBar_Background.gif") + ");'>",
                        "<div data-id='progress-bar-icon' style='width:0;height:19px;background-image:url(" + ProspectDirector.RUNTIME.resolveUrl("~/Application/Icons/Misc/ProgressBar.gif") + ");'>&nbsp;</div>",
                    "</div>",
                "</div>",
                "<div style='position:absolute;right:2px;bottom:0px;'>",
                    "<button data-id=\"ok\" class=\"-pd-button\" style='display:none;'>OK</button>",
                    "<button data-id=\"cancel\" class=\"-pd-button\" style='margin-left:10px;'>Cancel</button>",
                "</div>",
            "</div>"
        ]

        this.get_container().empty();
        this.get_container().append(content.join(""));

    },

    //================================
    // PRIVATE METHODS
    //================================

    _setProgressText: function (text) {

        var index = 1;

        for (index; index < arguments.length; index++) {
            text = text.replace("{" + (index - 1) + "}", arguments[index]);
        }

        this.get_progressText().empty();
        this.get_progressText().append(text);

    }

});

//================================
// SHARED METHODS
//================================

ProspectDirector.Web.UI.FeatureSets.Editors.FileUploadEditorDialog.open = function (options) {
    return new ProspectDirector.Web.UI.FeatureSets.Editors.FileUploadEditorDialog(options);
};