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

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

    // Private Properties
    _saveButton: null,
    _cancelButton: null,
    _org: 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:"name",
        title:"Name",
        type:"text",
        width:250,
        height:25,
        editorType:"OPINIATOR_TextItem"
        },
        //  First Name
        {
        name:"description",
        title:"Description",
        type:"text",
        width:250,
        height:25,
        editorType:"OPINIATOR_TextItem"
        },
        { height:5, startRow:true, editorType:"rowSpacer" },
        {
        name:"active",
        title:"Login's Enabled",
        type:"boolean",
        startRow:true,
        height:25
        },
        { height:5, type:"rowSpacer" },
        //  Password
        {
        type:"section",
        name:"domain",
        defaultValue:"Domain",
        sectionExpanded:true,
        canCollapse:false,
        itemIds:["domainname", "sp1", "maxusers", "display-maxusers"]
        },
        {
        name:"domainname",
        title:"Domain Name",
        titleOrientation:"left",
        startRow:true,
        type:"text",
        width:250,
        height:25,
        editorType:"OPINIATOR_TextItem"
        },
        { name:"sp1", height:5, startRow:true, editorType:"rowSpacer" },
        {
        name:"maxusers",
        title:"Max Users",
        titleOrientation:"left",
        titleAlign:"left",
        textAlign:"right",
        visible:false,
        startRow:true,
        showFocused:true,
        showFocusedIcons:true,
        type:"integer",
        width:50,
        height:24,
        iconHeight:24,
        valueIconHeight:25,
        min:0,
        max:50,
        editorType:"SpinnerItem"
        },
        {
        name:"display-maxusers",
        title:"Max Users",
        titleAlign:"left",
        titleOrientation:"left",
        visible:false,
        startRow:true,
        type:"text",
        width:40,
        height:19,
        editorType:"StaticTextItem"
        },

        { name:"sp2", height:5, startRow:true, editorType:"rowSpacer" },
        {
        name:"sms-available",
        title:"Availble SMS Messages",
        titleAlign:"left",
        titleOrientation:"left",
        startRow:true,
        wrapTitle:false,
        type:"text",
        width:40,
        height:19,
        textBoxStyle:"hilightText",
        editorType:"StaticTextItem"
        },

        { name:"sp3", height:5, startRow:true, editorType:"rowSpacer" },
        {
        name:"smsreg-enable",
        title:"Regulate SMS Messages",
        titleAlign:"left",
        titleOrientation:"left",
        visible:false,
        startRow:true,
        type:"boolean",
        height:25
        },
        {
        name:"smsreg-max",
        title:"Max Messages",
        titleAlign:"left",
        titleOrientation:"left",
        titleAlign:"left",
        textAlign:"right",
        visible:false,
        startRow:true,
        showFocused:true,
        showFocusedIcons:true,
        type:"integer",
        width:65,
        height:24,
        iconHeight:24,
        valueIconHeight:25,
        min:1,
        max:10000,
        editorType:"SpinnerItem"
        },
        {
        name:"smsreg-freq",
        title:"",
        titleAlign:"left",
        visible:false,
        align:"left",
        startRow:false,
        type:"enum",
        valueMap: { 
            "HOURLY": "Hourly",
            "DAILY": "Daily",
            "WEEKLY": "Weekly",
            "MONTHLY": "Monthly",
            "YEARLY": "Yearly"
            }, 
        width:120,
        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;

        this._adjustSpinnerIcons("maxusers", 14, 12);
        },

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

    _adjustSpinnerIcons: function ( itemname, width, height )
        {
        var item = this.getItem(itemname);
        for ( var i = 0; i < 2; i++ )
            {
            item.icons[i].width = width;
            item.icons[i].height = height;
            }
        },

    _smsregChanged : function( enabled )
        {
        var org = this._org;
        var max;
        var frequency;
        var count = new Number(org.smsCount);
        if ( isc.isAn.Object(org.regulator) )
            {
            max = org.regulator.max;
            frequency = org.regulator.frequency;
            }
        else
            {
            max = 500;
            frequency = "MONTHLY";
            }
        if ( enabled )
            {
            this.setValue("smsreg-max", max);
            this.getItem("smsreg-max").show();
            this.setValue("smsreg-freq", frequency);
            this.getItem("smsreg-freq").show();
            this.setValue("sms-available", max - count);
            }
        else
            {
            this.getItem("smsreg-max").hide();
            this.getItem("smsreg-freq").hide();
            this.setValue("sms-available", "UNLIMITED");
            }
        },

    _smsmaxChanged : function( max )
        {
        var count = new Number(this._org.smsCount);
        this.setValue("smsreg-max", max);
        this.setValue("sms-available", max - count);
        },

    itemChange: function (item, newValue, oldValue)
        {
        var iname = item.getFieldName();
        switch ( iname )
            {
            case "smsreg-enable":
                this._smsregChanged(newValue);
                break;
            case "smsreg-max":
                this._smsmaxChanged(newValue);
                break;
            default:
                break;
            }
        this.enableSave();
        return true;
        },

    _editValues: function () 
        {
        var org = this._org;

        this.setValue("name", org.levelName);
        this.setValue("description", org.description);
        this.setValue("active", org.active);
        if ( org.isDomainOrg === true )
            {
            this.getItem("domain").show();
            this.getItem("domainname").show();
            this.getItem("maxusers").show();
            this.setValue("domainname", org.domainName);

            if ( isc.isAn.Object(org.regulator) )
                {
                var max = new Number(org.regulator.max);
                var count = new Number(org.smsCount);
                this.setValue("sms-available", max - count);
                }
            else
                {
                this.setValue("sms-available", "UNLIMITED");
                }

            if ( OPINIATOR_MAIN.user.hasSysAdminRole() )
                {
                this.setValue("maxusers", org.maxUsers);
                this.getItem("maxusers").show();
                this.getItem("display-maxusers").hide();

                this.getItem("smsreg-enable").show();

                if ( isc.isAn.Object(org.regulator) )
                    {
                    this.getItem("smsreg-enable").setValue(true);
                    this.setValue("smsreg-max", org.regulator.max);
                    this.getItem("smsreg-max").show();
                    this.setValue("smsreg-freq", org.regulator.frequency);
                    this.getItem("smsreg-freq").show();
                    }
                else
                    {
                    this.getItem("smsreg-enable").setValue(false);
                    this.getItem("smsreg-max").hide();
                    this.getItem("smsreg-freq").hide();
                    }
                }
            else
                {
                this.getItem("maxusers").hide();
                this.setValue("display-maxusers", org.maxUsers);
                this.getItem("display-maxusers").show();

                this.getItem("smsreg-enable").hide();
                this.getItem("smsreg-max").hide();
                this.getItem("smsreg-freq").hide();
                }

            }
        // Is this the root?
        else if ( org.parentId == -1 )
            {
            this.setValue("domainname", org.domainName);
            this.getItem("description").hide();
            this.getItem("maxusers").hide();
            this.getItem("display-maxusers").hide();
            this.getItem("sms-available").hide();
            this.getItem("smsreg-enable").hide();
            this.getItem("smsreg-max").hide();
            this.getItem("smsreg-freq").hide();
            }
        else
            {
            this.getItem("domain").show();
            this.getItem("domain").hide();
            this.getItem("domainname").hide();
            this.getItem("maxusers").hide();
            this.getItem("display-maxusers").hide();
            this.getItem("sms-available").hide();
            this.getItem("smsreg-enable").hide();
            this.getItem("smsreg-max").hide();
            this.getItem("smsreg-freq").hide();
            }

        this.focusInItem("name");
        },

    _verifyValues: function ()
        {
        var domainname = this.getValue("domainname");
        if ( this._org.isDomainOrg && isc.isA.emptyString(domainname) )
            {
            OPINIATOR.warn("You must supply a domain name");
            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 org = this._org;
        var lname = this._getCleanString("loginid");
        org.levelName = this._getCleanString("name");
        org.description = this._getCleanString("description");
        org.active = this.getValue("active");
        if ( org.isDomainOrg )
            { 
            org.domainName = this.getValue("domainname"); 
            org.maxUsers = this.getValue("maxusers");
            if ( this.getValue("smsreg-enable") )
                {
                org.regulator = 
                    {
                    max:this.getValue("smsreg-max"), 
                    frequency:this.getValue("smsreg-freq")
                    };
                }
            else
                {
                delete org.regulator;
                }
            }
        },

    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._org);
        },

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

    _save: function ( org )
        {
        this._org = org;
        this.edit(org);
        this.selector.refreshOrgNode(org);
        this.showBusy(false);
        },

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

        this.showBusy(false);

        //  Keep the category around
        this._org = org; 
        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 org information by another user while you were editing.\nYour changes were lost! Please re-login.");
                OPINIATOR_MAIN.close();
                break;

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

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

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

    });

