isc.defineClass("OPINIATOR_CategoryList", isc.ListGrid);
OPINIATOR_CategoryList.addProperties({

    // Busy
    showBusy: OPINIATOR_ShowBusy,
    destroyBusy: OPINIATOR_DestroyBusy,

    // Superclass Properties
    selectionType: "multi",
    canPickFields:false,
    canResizeFields:false,
    canFreezeFields:false,
    canReorderFields:false,
    canGroupBy:false,
    canSort:false,
    canEdit:false,
    leaveScrollbarGap:false,
    showAllRecords:false,
    showHeader:true,
    showHeaderContext:false,
    alternateRecordStyles:false,
    border:"1px solid #000000",
    baseStyle:"catlistCell",
    styleName:"catlistBody",
    bodyStyleName:"catlistBody",
    headerBaseStyle:"catlistHeader",
    bodyBackgroundColor:null,

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

    destroy: function ()
        {
        this.destroyBusy();
        this.Super("destroy", arguments);
        }
    });


isc.defineClass("OPINIATOR_CategoryPicker", OPINIATOR_CategoryList);
OPINIATOR_CategoryPicker.addProperties({

    // Private Properties
    _filterlist: null,

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

    destroy: function ()
        {
        delete this._filterlist;
        this.Super("destroy", arguments);
        },

    setFilter: function ( filterlist )
        {
        this._filterlist = filterlist;
        if ( isc.isAn.Object(OPINIATOR_MAIN.user.catrefs) )
            { this._filterCatRefs(); }
        else
            { this._loadCatRefs(); }
        },

    _filterCatRefs: function ()
        {
        var data = isc.clone(OPINIATOR_MAIN.user.catrefs);

        if ( isc.isAn.Array(this._filterlist) )
            {
            var len = this._filterlist.getLength();
            for ( var i = 0; i < len; i++ )
                {
                var index = data.findIndex("id", this._filterlist[i].catref.id);
                if ( index > (-1) )
                    { data.removeAt(index); }
                }
            }

        this.setData(data);
        },

    _loadCatRefs : function()
        {
        this.showBusy(true, OPINIATOR.BUSY_DELAY);
        WebClientSvc.getUserCategoryRefList(this.callback("_catRefsLoaded"), this.callback("error"));
        },

    _catRefsLoaded : function( refs )
        {
        OPINIATOR_MAIN.user.catrefs = OPINIATOR.toArray(refs.list);
        OPINIATOR_MAIN.user.catrefs.sortByProperty("title", true);
        this._filterCatRefs();
        this.showBusy(false);
        },

    error: function ( code, msg )
        {
        this.showBusy(false);
        OPINIATOR.warn("Error: " + msg);
        },

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

    });

/**
 * Selects a Category.  But allows adding and deleting
 */
isc.defineClass("OPINIATOR_CategorySelector", isc.Canvas);
OPINIATOR_CategorySelector.addProperties({

    // Constructor properties

    /**
     *  If defined then then buttons will be added to the tool strip
     *  to add and delete surveys
     */
    toolstrip: null,

    /**
     *  Called when a survey has been selected or a new survey is
     *  created.
     *  
     *  @param survey   May either be a survey object or a survey
     *  id. Check type to determine what to do with the function
     */
    onCategoryOpen: function ( survey ) {},

    /**
     * Called when there is not currently a selection
     */
    onNothingOpen: function () {},

    onCategoryAdded: function () {},


    // Superclass properties
    showResizeBar:true,
    styleName:"defaultCanvas",

    // Private Properties
    _listgrid: null,
    _newButton: null,
    _delButton: null,
    _catrefs:null,

    initWidget : function ()
        {
        if ( isc.isAn.Object(this.toolstrip) )
            {
            this._newButton = OPINIATOR_Button.create({
                target: this,
                layoutAlign:"center",
                title: "New",
                icon: "icons/16/category.png",
                click: function ()
                    {
                    this.target.newCategory("New Category", "NUMERIC");
                    return true;
                    }
                });

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

            this.toolstrip.addMember(this._deleteButton, 0);
            this.toolstrip.addMember(this._newButton, 0);
            }

        this._listgrid = OPINIATOR_CategoryList.create({
            width:"100%",
            height:"100%",
            selectionType: "single",
            target:this,
            showHeader:false,
            bodyStyleName:"catselBody",
            fields: [{
                name:"title", 
                title:"", 
                align:"Center", 
                cellAlign:"left",
                formatCellValue: function (value, record, rowNum, colNum, grid)
                    { return record.title; }
                }],

            rowClick: function( catref, recordNum )     
                { this.target._openCatref(catref); }
            });

        this.children = [this._listgrid];
        this.Super("initWidget", arguments);
        this.delayCall("refresh");
        },

    destroy: function()
        {
        delete this._listgrid.target;
        delete this._listgrid;
        delete this._newButton;
        delete this._deleteButton;
        delete this._catrefs;
        delete this.toolstrip;
        this.Super("destroy", arguments);
        },
	
	// override hide method
	hide:function() {
		_hide(this);
	},
	
	// override show method
	show:function() {
		_show(this);
	},
    /**
     * Show the busy indicator in the tree grid
     */
    showBusy: function ( state, delay )
        { this._listgrid.showBusy(state, delay); },

    refreshCategory : function( category )
        {
        var catref = this._findCatref(category);
        if ( catref === null  )
            { this._addCatref(category); }
        else
            {
            catref.title = category.title;
            this._listgrid.refreshRow(this._listgrid.getRecordIndex(catref));
            }
        },

    /**
     *  Re-loads the entire category reflist from the server
     */
    refresh : function()
        {
        this.showBusy(true, OPINIATOR.BUSY_DELAY);
        WebClientSvc.getUserCategoryRefList(this.callback("_setCatrefs"), this.callback("error"));
        },

    /**
     *  Sets a survey tree 
     */
    _setCatrefs: function ( refs )
        {
        this.showBusy(false);
        this._catrefs = OPINIATOR.toArray(refs.list);
        OPINIATOR_MAIN.user.catrefs = this._catrefs;
        this._catrefs.sortByProperty("title", true);
        this._listgrid.setData(this._catrefs);
        },

    _findCatref: function( category )
        {
        var len = this._catrefs.getLength();
        for ( var i = 0; i < len; i++ )
            {
            var catref = this._catrefs[i];
            if ( catref.id == category.id )
                { return catref; }
            }
        return null;
        },


    _addCatref: function ( category )
        {
        // Create a new record and add it to the tree
        var catref = {
            id:category.id, 
            title:category.title,
            type:category.type
            }; 

        // Force the cache to be re-read
        // OPINIATOR_MAIN.user.catrefs = null;
        this._catrefs.add(catref);
        this._catrefs.sortByProperty("title", true);
        this._listgrid.deselectAllRecords();
        this._listgrid.selectRecord(catref);
        this._deleteButton.show();
        this.onCategoryAdded(category);
        },

    /**
     *  Opens the catref.  If the catref is not specified the
     *  selection will be used.
     */
    _openCatref: function ( catref )
        {
        if ( !isc.isAn.Object(catref) )
            { catref = this._listgrid.getSelectedRecord(); }

        if ( isc.isAn.Object(catref) )
            {
            if ( isc.isAn.Object(this._deleteButton) )
                {
                if ( catref.type != "WELCOME" && 
                     catref.type != "THANKYOU" && 
                     catref.type != "NETPROMOTER" )
                    { this._deleteButton.show(); }
                else
                    { this._deleteButton.hide(); }
                }
            this.onCategoryOpen(catref.id); 
            }
        else
            {
            this._deleteButton.hide();
            this.onNothingOpen(); 
            }
        },

    _deleteCategory: function ( catid )
        {
        this.showBusy(false);
        var category = { id:catid };
        var catref = this._findCatref(category);
        if ( isc.isAn.Object(catref) )
            { 
            var list = this._listgrid.getData();
            row = list.indexOf(catref);
            list.remove(catref); 
            this._listgrid.removeSelectedData();
            this._reselectRow(row);
            }

        },

    _reselectRow: function( row )
        {
        this._listgrid.deselectAllRecords();
        var list = this._listgrid.getData();
        var len = list.getLength();
        if ( len > 0 )
            {
            if ( row > (len-1) )
                {
                row = len - 1;
                if ( row < 0  )
                    { row = 0; }
                }
            this._listgrid.selection.select(list[row]);
            this._openCatref();
            }
        else
            {
            this._deleteButton.hide();
            this.onNothingOpen(); 
            }
        },

    selectCategory: function( category )
        {
        var catref = this._findCatref(category);
        if ( isc.isAn.Object(catref) )
            {
            this._listgrid.deselectAllRecords();
            this._listgrid.selectRecord(catref);
            }
        },

    newCategory: function ( title, type )
        { 
        WebClientSvc.newCategory(title, type, this.callback("_newCategory"), this.callback("error") ); 
        },

    _newCategory: function ( category )
        {
        this._deleteButton.hide();
        this.showBusy(false);
        this._listgrid.deselectAllRecords();
        this.onCategoryOpen(category);
        },

    deleteCategory: function ()
        {
        var catref = this._listgrid.getSelectedRecord();
        switch ( catref.type )
            {
            case "PERFORMANCE":
            case "NUMERIC":
            case "TEXT":
            case "CHOICE":
			case "ALERT":
            case "BOOLEAN":
                this._pendingDelete = catref.id;
                OPINIATOR.askOk("Delete the category '<b>"+catref.title+"</b>'? <br> <b>Note</b>: All responses and analytics will be deleted!", 
                      this.callback("deleteCategoryReply"));
                break;
            default:
                OPINIATOR.warn("You cannot delete categories of type: <b>"+catref.type+"</b>");
                break;
            }
        },

    deleteCategoryReply: function ( ok )
        { 
        if ( ok )
            { WebClientSvc.deleteCategory(this._pendingDelete, this.callback("_deleteCategory"), this.callback("error") ); }
        delete this._pendingDelete;
        },

    error : function( code, msg )
        {
        this._listgrid.showBusy(false);
        switch ( msg )
            {
            case "DeletedState":
                OPINIATOR.warn("This survey has been deleted by another user.");
                this.refresh();
                break;

            default:
                OPINIATOR.warn("Unhandled Exception: " + msg);
                break;
            }
        },

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

    });

