
isc.defineClass("OPINIATOR_UserEditor", isc.DynamicForm);
OPINIATOR_UserEditor.addProperties({

    // Constructor Properties
    toolstrip:null,
    selector:null,

    // Private Properties
    _saveButton: null,
    _cancelButton: null,
    _user: null,

    showBusy:OPINIATOR_ShowBusy,
    destroyBusy:OPINIATOR_DestroyBusy,

    // Superclass Properties
    width:"100%",
    height:"100%",
    minColWidth:10,
    cellPadding:2,
    numCols:2,
    fixedColWidths:true,
    titleWidths:80,
    cellBorder:0,
    showResizeBar:false,
    layoutAlign:"left",
    itemHoverDelay:3000,
    items:[
        { height:5, editorType:"RowSpacerItem" },
        {
        name:"loginid",
        title:"Login Id",
        type:"text",
        width:125,
        height:25,
        hint:"@domain",
        hintStyle:"staticText",
        editorType:"OPINIATOR_TextItem"
        },
        //  First Name
        {
        name:"firstname",
        title:"First Name",
        type:"text",
        width:250,
        height:25,
        editorType:"OPINIATOR_TextItem"
        },
        { height:5, startRow:true, editorType:"rowSpacer" },
        //  Last Name
        {
        name:"lastname",
        title:"Last Name",
        type:"text",
        startRow:true,
        width:250,
        height:25,
        editorType:"OPINIATOR_TextItem"
        },
        { height:5, type:"rowSpacer" },

        //  Email Address
        {
        name:"email",
        title:"Email Address",
        type:"text",
        startRow:true,
        width:250,
        height:25,
        editorType:"OPINIATOR_TextItem"
        },
        { height:5, type:"rowSpacer" },
        {
        name:"active",
        title:"Login Enabled",
        type:"boolean",
        startRow:true,
        height:25
        },
        { height:5, type:"rowSpacer" },

        //  Password
        {
        type:"section",
        defaultValue:"Password",
        sectionExpanded:true,
        canCollapse:false,
        itemIds:["password", "sp1", "verifypassword"]
        },
        {
        name:"password",
        title:"Password",
        titleOrientation:"left",
        startRow:true,
        type:"text",
        width:150,
        height:25,
        editorType:"OPINIATOR_PasswordItem"
        },
        { name:"sp1", height:5, startRow:true, editorType:"rowSpacer" },
        {
        name:"verifypassword",
        title:"Verify",
        titleOrientation:"left",
        startRow:true,
        type:"text",
        width:150,
        height:25,
        editorType:"OPINIATOR_PasswordItem"
        },
        // Roles
        {
        type:"section",
        defaultValue:"Roles",
        sectionExpanded:true,
        canCollapse:false,
        itemIds:["analyst", "designer", "orgadmin", "sysadmin"]
        },
        {
        name:"analyst",
        title:"Analyst",
        type:"boolean",
        startRow:true,
        height:25
        },
        {
        name:"designer",
        title:"Designer",
        type:"boolean",
        startRow:true,
        height:25
        },
        {
        name:"orgadmin",
        title:"Organization Admin",
        type:"boolean",
        startRow:true,
        height:25
        },
        {
        name:"sysadmin",
        title:"System Admin",
        visibility:"hidden",
        type:"boolean",
        startRow:true,
        height:25
        }
        ],

    initWidget: function ()
        { 
        this.Super("initWidget", arguments); 

        this._saveButton = OPINIATOR_Button.create({
            title:"Save",
            visibility: "hidden",
            target:this,
            layoutAlign:"center",
            icon: "icons/16/save.png",
            click: function ()
                { this.target.save(); return true;}
            });

        this._cancelButton = OPINIATOR_Button.create({
            title:"Cancel",
            layoutAlign:"center",
            visibility: "hidden",
            icon: "icons/16/cancel.png",
            target:this,
            click: function ()
                { this.target.cancel(true); return true;}
            });

        this.toolstrip.addMember(this._cancelButton);
        this.toolstrip.addMember(this._saveButton);

        delete this.toolstrip;
        },

    destroy: function ()
        {
        delete this._saveButton;
        delete this._cancelButton;
        delete this._user;
        this.destroyBusy();
        this.Super("destroy", arguments);
        },

    itemChange: function (item, newValue, oldValue)
        { this.enableSave(); },

    _editValues: function () 
        {
        var user = this._user;
        var loginname = new String(user.loginName);
        var lname = loginname.substring(0, loginname.indexOf("@"));
        var ldomain = user.loginName.substring(loginname.indexOf("@"), loginname.length);
        this.setValue("loginid", lname);
        this.getItem("loginid").hint = ldomain;


        this.setValue("firstname", user.firstName);
        this.setValue("lastname", user.lastName);
        this.setValue("email", user.emailAddress);
        this.setValue("active", user.active);
        this.setValue("password", "");
        this.setValue("verifypassword", "");

        OPINIATOR.addRoleFunctions(user);
        this.setValue("analyst", user.hasAnalystRole());
        this.setValue("designer", user.hasDesignerRole());
        this.setValue("orgadmin", user.hasOrgAdminRole());
        if ( OPINIATOR_MAIN.user.hasSysAdminRole() && user.orgUnitRef.isRootOrg)
            {
            this.getItem("sysadmin").show();
            this.setValue("sysadmin", user.hasSysAdminRole());
            }
        else
            { 
            this.getItem("sysadmin").hide(); 
            this.setValue("sysadmin", false);
            }

        this.focusInItem("loginid");
        },

    _verifyValues: function ()
        {
        var password = this.getValue("password");
        if ( isc.isA.nonemptyString(password) )
            {
            var verifypassword = this.getValue("verifypassword");
            if ( password != verifypassword )
                {
                OPINIATOR.warn("Passwords do not match");
                return false;
                }
            }
        else
            {
            if ( !isc.isA.Number(this._user.id) )
                { 
                OPINIATOR.warn("You must specifiy a password"); 
                return false;
                }
            }

        var loginid = new String(this.getValue("loginid"));
        if ( isc.isA.nonemptyString(loginid) )
            {
            if ( loginid.hasInvalidChars() )
                {
                OPINIATOR.warn("Login name has one or more of these invalid characters:<br>!@#$%^&*()+=-[]\\\';,./{}|\":<>?");
                return false;
                }
            }

        var emailAddress = this.getValue("email");
        if ( isc.isA.nonemptyString(emailAddress) )
            {
            if ( !(emailAddress.contains("@") && emailAddress.contains(".")) )
                {
                OPINIATOR.warn("Invalid email address");
                return false;
                }
            }

        return true;
        },
        
    _getCleanString: function ( itemname )
        {
        value = this.getValue(itemname);
        var str = new String("");
        if ( isc.isA.nonemptyString(value) )
            {
            str = new String(value);
            str.trim();
            }

        return str;
        },

    _saveValues: function ()
        {
        var user = this._user;
        var lname = this._getCleanString("loginid");
        user.loginName = lname + this.getItem("loginid").hint;
        user.firstName = this._getCleanString("firstname");
        user.lastName = this._getCleanString("lastname");
        user.emailAddress = this._getCleanString("email");
        var password = this.getValue("password");
        if ( isc.isA.nonemptyString(password) )
            { user.password = sha1(password); }
        else
            { delete user.password; }
        user.active = this.getValue("active");

        user.roles = new Array();
        if ( this.getValue("analyst") )
            user.roles.add('ANALYST');
        if ( this.getValue("designer") )
            user.roles.add('DESIGNER');
        if ( this.getValue("orgadmin") )
            user.roles.add('ORGADMIN');
        if ( OPINIATOR_MAIN.user.hasSysAdminRole() && this.getValue("sysadmin") )
            user.roles.add('SYSADMIN');
        },
            enableSave: function ()
        {
        this._saveButton.show();
        this._cancelButton.show();
        },

    enableCancel: function ()
        {
        this._saveButton.hide();
        this._cancelButton.show();
        },

    disableSave: function ()
        {
        this._saveButton.hide();
        this._cancelButton.hide();
        },

    wasModified: function ()
        { return this._saveButton.isVisible(); },

    cancel: function ()
        {
        this.disableSave();
        this.edit(this._user);
        },

    save: function ()
        {
        if ( this._verifyValues() )
            {
            this.showBusy(true, OPINIATOR.BUSY_DELAY);
            this.disableSave();
            this._saveValues();
            WebClientSvc.saveUser(this._user, this.callback("_save"), this.callback("error"));
            }
        },

    _save: function ( user )
        {
        this._user = user;
        this.selector.refreshUserNode(user);
        this.showBusy(false);
        },

    edit: function ( user )
        {
        if ( isc.isA.Number(user) )
            {
            var userid = user;
            this.showBusy(true, OPINIATOR.BUSY_DELAY);
            WebClientSvc.getUser(userid, this.callback("edit"), this.callback("error"));
            return;
            }

        this.showBusy(false);

        //  Keep the category around
        this._user = user; 
        this._editValues();
        },

    checkSave: function ( )
        {
        if ( this.wasModified() )
            {
            OPINIATOR.askOk("You have made changes that will be lost! Would you like to save first?", this.callback("checkSaveReply"));
            }
        },

    checkSaveReply: function ( value )
        { if ( value ) { this.save(); } },

    error: function (code, msg)
        {
        this.enableCancel();
        this.showBusy(false);
        switch ( msg )
            {
            case "StaleState":
                OPINIATOR.warn("Changes were made to the user information by another user while you were editing.\nYour changes were lost! Please re-login.");
                OPINIATOR_MAIN.close();
                break;

            case "DeletedState":
                OPINIATOR.warn("This user has been deleted by another administrator.");
                OPINIATOR_MAIN.close();
                break;

            default:
                OPINIATOR.warn(msg);
                break;
            }
        },

    callback: function (methodName)
        { return {target:this, methodName:methodName}; }

    });

