﻿var EDMS = function (config) {

    this.atomUId = config.atomUId || -1;
    this.renderTo = ('edms' + config.atomUId);
    this.infoContainerId = ('edms' + config.atomUId + '-info');
    this.rootObjectId = config.rootObjectId;
    this.userObjectId = config.userObjectId || -1;
    this.pageObjectId = config.pageObjectId || -1;
    this.isEditor = config.isEditor || false;
    this.maxDepth = config.maxDepth;
    this.isModerator = config.isModerator || false;
    this.orderByDirection = config.orderByDirection || 'asc';
    this.orderByName = config.orderByName || 'ObjectName';

    var _documentTypeId = 40000;
    var _folderTypeId = 2;
    var _moderatedFolderTypeId = 5;
    var _compilationTypeId = 40001;

    var _downloadIframe = null; //hidden iframe added on first load, used to stream downloads transparently
    var _pendingModerationsData = null; //source data for an ext datastore loaded on first load, contains a list of items the need moderating.

    var _dataUrl = '/icms/ibis2_editor/cms/atoms/edms/edms-cmd.aspx';

    this.tree = null;
    this._initTree = function (openPath) {

        this.tree = new Ext.tree.TreePanel({
            id: 'edmstree' + this.atomUId,
            cls: 'edms-tree',
            edms: this,
            border: false,
            renderTo: this.renderTo,
            iconCls: 'icon-nav-explorer',
            useArrows: true,
            autoScroll: true,
            rootVisible: false,
            animate: true,
            enableDD: false,
            containerScroll: true,
            listeners: { dblclick: function (node, e) { node.ownerTree.edms.download(); }, contextmenu: function (node, e) {
                //  alert(node.getPath());
                var edms = node.ownerTree.edms;

                e.stopEvent();
                node.select();
                var coords = e.getXY();
                var mi;

                var menu = new Ext.menu.Menu({  edms: this.edms });

                var nodeModStatus = node.attributes.ModeratedStatus;
                if (!nodeModStatus) { nodeModStatus = -1; }
                nodeModStatus = parseInt(nodeModStatus);

                mi = new Ext.menu.Item({ text: 'Download', cls: '', iconCls: 'edms-icon-download', disabled: true, handler: function (mi, e) { mi.parentMenu.edms.download(); } });
                if (this.edms.isDocumentSelected()) { mi.enable(); };
                menu.add(mi);

                if (edms.userObjectId > 0) {

                    menu.addSeparator();

                    if (parseInt(node.attributes.typeid) == _folderTypeId || parseInt(node.attributes.typeid) == _documentTypeId || parseInt(node.attributes.typeid) == _moderatedFolderTypeId || parseInt(node.attributes.typeid) == _compilationTypeId) {

                        var addSubMenu = new Ext.menu.Menu({ edms: this.edms });

                        if (parseInt(node.attributes.typeid) == _folderTypeId || parseInt(node.attributes.typeid) == _moderatedFolderTypeId) {

                            mi = new Ext.menu.Item({ text: 'Add Folder', cls: '', iconCls: 'edms-icon-add-folder', handler: function (mi, e) { mi.parentMenu.edms.addContainer(_moderatedFolderTypeId); } });
                            addSubMenu.add(mi);

                        }

                        mi = new Ext.menu.Item({ text: 'Add Document', cls: '', iconCls: 'edms-icon-add-document', handler: function (mi, e) { mi.parentMenu.edms.addDocument(); } });
                        addSubMenu.add(mi);

                        if (parseInt(node.attributes.typeid) == _folderTypeId || parseInt(node.attributes.typeid) == _moderatedFolderTypeId) {

                            mi = new Ext.menu.Item({ text: 'Add Compilation', cls: '', iconCls: 'edms-icon-add-compilation', handler: function () { mi.parentMenu.edms.addContainer(_compilationTypeId); } });
                            addSubMenu.add(mi);

                        }

                        menu.add({ text: 'Add', menu: addSubMenu });

                        menu.addSeparator();
                    };

                    mi = new Ext.menu.Item({ text: 'Edit Document', cls: '', iconCls: 'edms-icon-edit-document', disabled: true, handler: function (mi, e) { mi.parentMenu.edms.editDocument(); } });
                    if (edms.isDocumentSelected()) { mi.enable(); };
                    menu.add(mi);

                    if (this.edms.isModerator) {

                        if (edms.isDocumentSelected()) {

                            mi = new Ext.menu.Item({ text: 'Versions', cls: '', iconCls: 'edms-icon-versions', handler: function (mi, e) { mi.parentMenu.edms.showVersions(); } });
                            menu.add(mi);

                        } else {

                            var modSubMenu = new Ext.menu.Menu({ edms: this.edms });

                            mi = new Ext.menu.Item({ text: 'Approve', cls: '', iconCls: 'edms-icon-moderate-approve', handler: function () { mi.parentMenu.edms.moderateApproveContainer(); } });
                            if (nodeModStatus != 1) { mi.disable(); }
                            modSubMenu.add(mi);

                            /*mi = new Ext.menu.Item({ text: 'Approve & Set Default', cls: '', iconCls: 'edms-icon-moderate-approve-set-default', disabled: true, handler: function() { } });
                            if (parseInt(node.attributes.typeid) == 40000) { mi.enable(); };
                            modSubMenu.add(mi);*/

                            mi = new Ext.menu.Item({ text: 'Decline', cls: '', iconCls: 'edms-icon-moderate-decline', handler: function (mi, e) { mi.parentMenu.edms.moderateDeclineContainer(); } });
                            modSubMenu.add(mi);

                            menu.add({ text: 'Moderate', menu: modSubMenu });

                        }

                    }

                    menu.addSeparator();

                    mi = new Ext.menu.Item({ text: 'Delete', cls: '', iconCls: 'edms-icon-delete', handler: function (mi, e) { mi.parentMenu.edms.deleteSelectedObject(); } });
                    menu.add(mi);

                }

                menu.showAt([coords[0], coords[1]]);
                e.preventDefault(); //disables the standard browser context/right-click menu
            }
            },
            dataUrl: _dataUrl + '?cmd=list&startnode=' + this.rootObjectId + '&maxdepth=' + this.maxDepth + '&oname=' + this.orderByName + '&odur=' + this.orderByDirection,
            root: { nodeType: 'async', text: 'Home/Root', draggable: false, id: this.rootObjectId, expanded: true }
        });

        if (openPath) { this.tree.selectPath(openPath, null, function (success, node) { if (node) { node.expand(); } }); }

    };

    //gets the ObjectId of the selected item in the tree
    this.getSelectedObjectId = function () {
        return parseInt(this.tree.getSelectionModel().getSelectedNode().id);
    };

    //gets the parentid of the selected node
    this.getSelectedParentObjectId = function () {
        return parseInt(this.tree.getSelectionModel().getSelectedNode().parentNode.id);
    }

    //returns the parent id for a new document checking to see if the selected object is a folder or a document.
    this.getNewDocumentParentId = function () {
        if (this.getSelectedObjectTypeId() == _documentTypeId) {
            return this.getSelectedParentObjectId();
        } else {
            return this.getSelectedObjectId();
        }
    }

    //gets the ObjectTypeId of the selected item in the tree
    this.getSelectedObjectTypeId = function () {
        return parseInt(this.tree.getSelectionModel().getSelectedNode().attributes.typeid);
    };

    //gets the ObjectName of the selected item in the tree
    this.getSelectedObjectName = function () {
        return this.tree.getSelectionModel().getSelectedNode().text;
    };

    //returns true if the selected item in the tree is a document
    this.isDocumentSelected = function () {
        var typeid = this.getSelectedObjectTypeId();
        var objectId = this.getSelectedObjectId();
        if (typeid == _documentTypeId && objectId > 0) { return true; } else { return false; }
    };

    //returns the current path of the currently selected item in the tree
    this.getSelectedPath = function () {
        return this.tree.getSelectionModel().getSelectedNode().getPath();
    };

    //destroy's and rebuilds the tree
    this.reloadTree = function (selectNodeObjectId) {
        //var currentPath = this.tree.getSelectionModel().getSelectedNode().getPath() + '/' + selectNodeObjectId;
        var currentPath = this.getSelectedPath() + '/' + selectNodeObjectId;
        this.tree.destroy();
        this._initTree(currentPath);
    };

    //download a document (componentId as yet not used)
    this.download = function (objectId, versionId, componentId) {
        if (!objectId) {
            if (!this.isDocumentSelected()) { return false; } //only download a document
            objectId = this.getSelectedObjectId();
        }
        //_downloadIframe.src = '/doc/' + objectId + '.aspx';
        var url = '/idocument/stream_document.aspx?objectid=' + objectId;
        if (versionId) { url += '?versionid=' + versionId; }
        document.location.href = url;
    };

    /* ====================================== Add Folder ====================================== */

    this._win_addFolder = null;
    this.addContainer = function (objectTypeId) {

        if (!objectTypeId) { objectTypeId = _moderatedFolderTypeId; } //default to a new folder
        switch (objectTypeId) {
            case _moderatedFolderTypeId:
                title = 'New Folder';
                msg = 'Folders are moderator controlled. You may add a new folder here and continue to add content within that folder but it will not be generally available until approved by a system moderator.<br/><br/>Folders will not be sent to moderators for approval until content has been added to them.<br/><br/>';
                break;
            case _compilationTypeId:
                title = 'New Compilation';
                msg = 'Document Compilations are moderator controlled. You may add a new compilation here and continue to add content within that compilation but it will not be generally available until approved by a system moderator.<br/><br/>Compilations will not be sent to moderators for approval until a document has been added to them.<br/><br/>';
                break;
        }

        //if (!this._win_addFolder) {

        var fieldName = new Ext.form.TextField({ fieldLabel: 'Name', name: 'name', anchor: '100%', allowBlank: false });

        var form = new Ext.form.FormPanel({
            edms: this,
            fieldName: fieldName,
            url: _dataUrl,
            labelWidth: 75,
            frame: false,
            width: 400,
            defaults: { width: 293 },
            defaultType: 'textfield',
            baseCls: '',
            bodyStyle: 'padding:5px 5px 0',
            items: [{ xtype: 'label', html: msg }, fieldName]
        });

        var w = new Ext.Window({
            title: title,
            layout: 'fit',
            width: 400,
            height: 195,
            closeAction: 'close',
            plain: true,
            modal: true,
            items: [form],
            buttons: [
					{ text: 'Submit', handler: function () {
					    if (form.getForm().isValid()) {
					        form.getForm().submit({
					            params: { 'cmd': 'add-container', 'objecttypeid': objectTypeId, 'parentobjectid': this.getSelectedObjectId() },
					            success: function (form, action) {
					                this.reloadTree(action.result.returnvalue);
					                w.hide();
					            },
					            failure: function (form, action) { ShowErrorMsg(action.result.msg); },
					            scope: this
					        });
					    }
					},
					    scope: this
					},
					{ text: 'Cancel', handler: function () { w.hide(); }, scope: this }
				]
        });
        w.show();
        this._win_addFolder = w;
        //}

        //this._win_addFolder.show();

    };

    /* ====================================== END: Add Folder ====================================== */

    /* ===================================== Add/Edit Document ===================================== */

    this._win_addDocument = null;
    this.addDocument = function () {

        if (!this._win_addDocument) {

            var fieldTitle = new Ext.form.TextField({ fieldLabel: 'Title', name: 'title', anchor: '100%', allowBlank: false });

            var fieldFileUpload = new Ext.form.FileUploadField({
                emptyText: 'Browse...',
                fieldLabel: 'File',
                name: 'file-path',
                buttonCfg: { text: '', iconCls: 'upload-icon' }
            });

            var form = new Ext.form.FormPanel({
                edms: this,
                url: _dataUrl,
                labelWidth: 75,
                frame: false,
                fileUpload: true,
                width: 400,
                defaults: { width: 293 },
                defaultType: 'textfield',
                baseCls: '',
                bodyStyle: 'padding:5px 5px 0',
                items: [
					{ xtype: 'label', html: 'Documents are moderator controlled, and will not be generally available until approved by a system moderator.<br/><br/>This document will be automatically submitted to moderators on creation.<br/><br/>' },
					fieldTitle,
					fieldFileUpload
				]
            });

            var w = new Ext.Window({
                title: 'New Document',
                layout: 'fit',
                width: 405,
                height: 215,
                closeAction: 'hide',
                plain: true,
                modal: true,
                items: [form],
                buttons: [
					{ text: 'Submit', handler: function () {
					    if (form.getForm().isValid()) {
					        form.getForm().submit({
					            waitMsg: 'Uploading, please wait...',
					            params: { 'cmd': 'add-document', 'pageobjectid': this.pageObjectId, 'parentobjectid': this.getNewDocumentParentId(), 'path': this.getSelectedPath() },
					            success: function (form, action) {
					                this.reloadTree(action.result.returnvalue);
					                w.hide();
					                this._win_addDocument = null;
					            },
					            failure: function (form, action) { ShowErrorMsg(action.result.msg); },
					            scope: this
					        });
					    }
					},
					    scope: this
					},
					{ text: 'Cancel', handler: function () { w.hide(); }, scope: this }
				]
            });
            this._win_addDocument = w;
        }

        this._win_addDocument.show();

    };

    this._win_editDocument = null;
    this.editDocument = function () {

        if (!this._win_editDocument) {

            var fieldTitle = new Ext.form.TextField({ fieldLabel: 'Change Title', name: 'title', anchor: '100%', allowBlank: false, value: this.getSelectedObjectName() });
            var fieldFileUpload = new Ext.form.FileUploadField({
                emptyText: 'Browse...',
                fieldLabel: 'Replace File',
                name: 'file-path',
                buttonCfg: { text: '', iconCls: 'upload-icon' }
            });

            var form = new Ext.form.FormPanel({
                edms: this,
                url: _dataUrl,
                labelWidth: 75,
                frame: false,
                fileUpload: true,
                width: 400,
                defaults: { width: 293 },
                defaultType: 'textfield',
                baseCls: '',
                bodyStyle: 'padding:5px 5px 0',
                items: [
					{ xtype: 'label', html: 'Changes to documents will be made and sent to moderators for approval. Your changes will not be published until approved by a moderator.<br/><br/>' },
					fieldTitle,
					fieldFileUpload
				]
            });

            var w = new Ext.Window({
                form: form,
                title: 'Edit Document',
                layout: 'fit',
                width: 405,
                height: 195,
                closeAction: 'hide',
                plain: true,
                modal: true,
                items: [form],
                buttons: [
					{ text: 'Submit', handler: function () {

					    var form = this.ownerCt.form;
					    if (form.getForm().isValid()) {
					        form.getForm().submit({
					            waitMsg: 'Uploading, please wait...',
					            params: { 'cmd': 'edit-document', 'pageobjectid': form.edms.pageObjectId, 'objectid': form.edms.getSelectedObjectId(), 'path': form.edms.getSelectedPath() },
					            success: function (form, action) {
					                form.edms.reloadTree(action.result.returnvalue);
					                form.edms._win_editDocument.hide();
					            },
					            failure: function (form, action) { ShowErrorMsg(action.result.msg); }
					        });
					    }
					}
					},
					{ text: 'Cancel', handler: function () { w.hide(); } }
				]
            });

            this._win_editDocument = w;

        }

        this._win_editDocument.show();

    };

    /* ================================== END: Add/Edit Document =================================== */

    /* ========================================= Moderation ======================================== */

    this._initModeration = function () {

        var conn = new Ext.data.Connection({});
        conn.request({
            edms: this,
            url: _dataUrl,
            method: 'POST',
            params: { atomuid: this.atomUId, cmd: 'list-pending-moderations', rootobjectid: this.rootObjectId },
            success: function (responseObject, req) {

                var pending = eval('(' + responseObject.responseText + ')');

                req.edms._pendingModerationsData = pending;

                var d = document.createElement('div');
                d.className = 'edms-info-content';

                var info = document.createElement('div');
                info.innerHTML = '<div style="padding-bottom:5px;">There are ' + pending.totalCount + ' items that require moderator approval.</div>';
                d.appendChild(info);

                var detail = document.createElement('div');

                var detailItem = null;
                for (var i = 0; i < pending.pendingobjects.length; i++) {

                    detailItem = document.createElement('div');
                    detailItem.className = 'edms-moderator-pending-item';
                    detailItem.setAttribute('path', pending.pendingobjects[i].Path + '/' + pending.pendingobjects[i].ObjectId);
                    detailItem.setAttribute('edmstreeid', req.edms.tree.id);
                    detailItem.onclick = function () {
                        var ed = Ext.ComponentMgr.get(this.getAttribute('edmstreeid')).edms;
                        var p = this.getAttribute('path');
                        ed.tree.selectPath(p, null);
                    };
                    detailItem.innerHTML = '<a>' + pending.pendingobjects[i].ObjectName + ' (' + pending.pendingobjects[i].ObjectId + ')</a>';
                    if (pending.pendingobjects[i].RequestStatus == '3') { detailItem.innerHTML += ' [delete request]'; }
                    detail.appendChild(detailItem);

                }
                d.appendChild(detail);

                var p = document.getElementById(req.edms.infoContainerId);
                p.innerHTML = ''; //clear the container
                p.className = 'edms-info';
                p.appendChild(d);

            },
            failure: function (responseObject, req) { }
        });

    };

    this._moderate = function (objectId, cmd) {

        if (!this.isModerator) { return; }

        var conn = new Ext.data.Connection({});
        conn.request({
            edms: this,
            url: _dataUrl,
            method: 'POST',
            params: { atomuid: this.atomUId, cmd: cmd, objectid: objectId },
            success: function (responseObject, req) { req.edms.reloadTree(req.edms.getSelectedPath()); req.edms._initModeration(); },
            failure: function (responseObject, req) { }
        });

    };

    this.moderateApproveContainer = function () {
        Ext.Msg.show({
            title: 'Confirm',
            msg: 'Approve and Set Default (publish) the selected item?',
            buttons: Ext.Msg.YESNO,
            fn: function (btn) {
                if (btn == 'yes') {
                    this._moderate(this.getSelectedObjectId(), 'mod-approve');
                }
            },
            icon: Ext.MessageBox.WARNING,
            scope: this
        });
    };

    this.moderateDeclineContainer = function () {
        Ext.Msg.show({
            title: 'Confirm',
            msg: 'Decline/depublish the selected item?',
            buttons: Ext.Msg.YESNO,
            fn: function (btn) {
                if (btn == 'yes') {
                    this._moderate(this.getSelectedObjectId(), 'mod-decline');
                }
            },
            icon: Ext.MessageBox.WARNING,
            scope: this
        });
    };

    this.deleteSelectedObject = function () {

        var msg;
        if (!this.isModerator) {
            msg = 'A delete request will be sent to moderators for approval. Once approved the selected item will be deleted. Continue?';
        } else {
            msg = 'Are you sure you want to delete this item?';
        }
        Ext.Msg.show({
            title: 'Confirm',
            msg: msg,
            buttons: Ext.Msg.YESNO,
            fn: function (btn) {
                if (btn == 'yes') {
                    var conn = new Ext.data.Connection({});
                    conn.request({
                        edms: this,
                        url: _dataUrl,
                        method: 'POST',
                        params: { atomuid: this.atomUId, cmd: 'delete', objectid: this.getSelectedObjectId(), pageobjectid: this.pageObjectId, path: this.getSelectedPath() },
                        success: function (responseObject, req) { var result = getJsonObject(responseObject.responseText); req.edms.reloadTree(decodeHttpUtilUrlEncode(result.returnvalue)); },
                        failure: function (responseObject, req) { var result = getJsonObject(responseObject.responseText); ShowErrorMsg(result.msg); }
                    });
                }
            },
            icon: Ext.MessageBox.WARNING,
            scope: this
        });
    };

    /* ====================================== END: Moderation ====================================== */

    /* ====================================== Versions Popup ======================================= */

    this._win_versions = null;
    this.showVersions = function () {

        if (!this._win_versions) {

            var versions = new Ext.Panel({
                html: '<iframe src="/iexplorer/object_versions.aspx?standalone=true&objectid=' + this.getSelectedObjectId() + '" frameborder=0 style="height:100%;width:100%;"></iframe>'
            });

            var w = new Ext.Window({
                edms: this,
                versions: versions,
                title: 'Document Versions',
                layout: 'fit',
                width: 780,
                height: 580,
                closeAction: 'hide',
                plain: true,
                modal: true,
                items: [versions],
                buttons: [{ text: 'Close', handler: function () { w.hide(); } }],
                listeners: { hide: function (win) { win.edms._initModeration(); } }
            });
            this._win_versions = w;
        } else {
            //this._win_versions.versions.rebind();
        }
        this._win_versions.show();
    };

    /* ==================================== END: Versions Popup ==================================== */

    /* ============================================ INIT =========================================== */

    if (!this._isLoaded) {

        this._initTree(request('enp')); //autoload tree on first load

        if (this.isModerator) { this._initModeration(); }

        //add a hidden iframe to handle downloads
        _downloadIframe = document.createElement('iframe');
        _downloadIframe.style.display = 'none';
        document.getElementById(this.infoContainerId).appendChild(_downloadIframe);

    };

    /* ========================================= END: INIT ========================================= */

}

function initEDMS(rootObjectId, atomUId, userObjectId, pageObjectId, isEditor, isModerator, maxDepth, orderByName, orderByDirection ) {

	Ext.BLANK_IMAGE_URL = '/pixel.gif';

	Ext.onReady(function() {

		var edms = new EDMS({
			rootObjectId: rootObjectId,
			atomUId: atomUId,
			userObjectId: userObjectId,
			pageObjectId: pageObjectId,
			isEditor: isEditor,
			isModerator: isModerator,
			maxDepth: maxDepth,
			orderByName: orderByName,
			orderByDirection: orderByDirection
		});

	});

}