/**
 * @class SurveySelector Class for the Selector of surveys which
 *        includes describing the originizational unit of the
 *        survyes.
 * 
 * @author ktyra (10/30/2008)
 */
isc.defineClass("OPINIATOR_SurveyTree", isc.TreeGrid);
OPINIATOR_SurveyTree.addProperties({

    //  Busy 
    showBusy: OPINIATOR_ShowBusy,
    destroyBusy: OPINIATOR_DestroyBusy,

    // Superclass properties
    loadDataOnDemand: false,
    selectionType: "single",
    styleName:"defaultCanvas",
    bodyStyleName:"surveySelectorBody",
    baseStyle:"surveySelectorCell",
    bodyBackgroundColor:null,
    showHeaderContextMenu:false, 
    showHeader:false, 
    showShadow:false, 
    shadowSize:0,
    iconSize:16,
    folderIcon:null,
    showOpenIcons:false,
    showDropIcons:false,
    openIconSuffix:"",
    closedIconSuffix:"",
    border:"0px",

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

    destroy: function()
        {
        this.destroyBusy();
        this.getData().data = null;
        this.Super("destroy", arguments);
        },

    getIcon: function( node )
        {
        if ( !node.isFolder  )
            {
            switch ( node.status )
                {
                case "OFF": 
                    return "icons/16/off.png";
                    break;

                case "ON": 
                    return "icons/16/on.png";
                    break;

                case "SCHEDULE": 
                    return "icons/16/schedule.png";
                    break;
                default:
                    break;
                }
            }
        return null;
        }

    });
	
isc.defineClass("OPINIATOR_SurveySelector", isc.Canvas);
OPINIATOR_SurveySelector.addClassProperties({
    lastSelectedRow:null
    });


OPINIATOR_SurveySelector.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
     */
    onSurveyOpen: function ( survey ) {},

    /**
     *   Called when an orgunit has been selected
     * 
     *   @param orgid   The orgunit id
     */
    onOrgUnitOpen: function ( orgid ) {},

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

    onSurveyAdded: function () {},


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


    // Private Properties
    _treegrid: null,
    _surveyTree: null,
    _addButton: null,
    _delButton: null,	

    initWidget : function ()
        {
        if ( isc.isAn.Object(this.toolstrip) )
            {
            if ( !OPINIATOR_MAIN.user.orgUnitRef.isRootOrg )
                {
                this._addButton = OPINIATOR_Button.create({
                    target: this,
                    layoutAlign:"center",
                    visibility: "hidden",
                    title: "Add Survey",
                    width: 120,
                    icon: "icons/16/survey.png",
                    click: function ()
                        {
                        this.target.createSurvey();
                        return true;
                        }
                    });
                }

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

        if ( isc.isA.Object(this._deleteButton) )
            { this.toolstrip.addMember(this._deleteButton, 0); }
        if ( isc.isA.Object(this._addButton) )
            { this.toolstrip.addMember(this._addButton, 0); }

        this._treegrid = OPINIATOR_SurveyTree.create({
            width:"100%",
            height:"100%",
            target:this,
            nodeClick: function( tree, node, recordNum )     
                { this.target._openNode(node); }
            });		
		this.children = [this._treegrid];	
        this.Super("initWidget", arguments);
        //this.delayCall("refresh");
        },

	 // override hide method
	hide: function() {		
		_hide(this);
	},
	
	// override show method	
	show: function() {
		_show(this);
	},
	
    destroy: function()
        {
        delete this._surveyTree;
        delete this._treegrid.target;
        delete this._treegrid;
        delete this._addButton;
        delete this._deleteButton;
        delete this.toolstrip;
        this.Super("destroy", arguments);
        },


    /**
     * Show the busy indicator in the tree grid
     */
    showBusy: function ( state, delay )
        { this._treegrid.showBusy(state, delay); },

    refreshSurveyNode : function( survey )
        {
        var node = this._findSurveyNode(survey);
        if ( node === null  )
            { this._addSurveyNode(survey); }
        else
            {
            node.levelName = survey.name;
            node.status = survey.status;
            this._treegrid.refreshRow(this._treegrid.getRecordIndex(node));
            }
        },

    /**
     *  Re-loads the entire from the server
     */
    refresh : function()
        {
        this.showBusy(true, OPINIATOR.BUSY_DELAY);
        WebClientSvc.getSurveyTree(this.callback("_setSurveyTree"), this.callback("error"));
        },
	
	_getTreeGrid: function() {
		return this._treegrid;	
	},		
	
	setSurveyTree: function() {
		this._surveyTree = globalTree;
		this._surveyTree.nodes = globalData;
	},
	
    /**
     *  Sets a survey tree 
     */
    _setSurveyTree: function ( surveyTree )
        {
        this.showBusy(false);
        this._surveyTree = isc.isAn.Object(surveyTree) ? surveyTree : {nodes:[]};
        this._surveyTree.nodes = OPINIATOR.toArray(this._surveyTree.nodes);

        var tree = isc.Tree.create({
            modelType: "parent",
            rootValue: 0,
            nameProperty: "levelName",
            titleProperty: "levelName",
            idField: "id",
            parentIdField: "parentId",
            showRoot: false,			
            data: surveyTree.nodes
            });
		
        this._treegrid.setData(tree);
		
		globalTree = tree;
		globalData = this._surveyTree.nodes;
		
		// expand all, then collapse on so that all icon will be loaded correctly.
		tree.openAll();
		tree.closeAll();
		
		// open again at level 1
		tree.openFolder(tree.data[0]);			
		
        if ( OPINIATOR_SurveySelector.lastSelectedRow !== null )
            { 
            this._treegrid.selectSingleRecord(OPINIATOR_SurveySelector.lastSelectedRow); 
            this._openNode(this._treegrid.getRecord(OPINIATOR_SurveySelector.lastSelectedRow)); 
            }
        },

    _findSurveyNode: function( survey )
        {
        var nodes = this._surveyTree.nodes;
        for ( var i = 0; i < nodes.length; i++ )
            {
            var node = nodes[i];
            if ( !node.isFolder && (node.recordId == survey.id) )
                { return node; }
            }
        return null;
        },


    _addSurveyNode: function ( survey )
        {
        var nodes = this._surveyTree.nodes;
        // Find the next id
        var nextid = 0;
        for ( var i = 0; i < nodes.length; i++ )
            {
            var node = nodes[i];
            if ( nextid <= node.id )
                { nextid = node.id + 1; }
            }

        // Find the parent node
        var parentnode;
        for ( i = 0; i < nodes.length; i++ )
            {
            parentnode = nodes[i];
            if ( parentnode.isFolder && (parentnode.recordId == survey.orgUnitId) )
                { break; }
            }
        parentnode.isOpen = true;

        // Create a new node and add it to the tree
        var newnode = {
            id:nextid, 
            parentId:parentnode.id, 
            levelName:survey.name, 
            recordId:survey.id, 
            status:"OFF", 
            enabled:true, 
            isOpen:true, 
            isFolder:false
            }; 

        nodes.add(newnode);
        this._treegrid.getData().linkNodes([newnode]);
        this._treegrid.deselectAllRecords();
        this._treegrid.selectRecord(newnode);
        if ( isc.isA.Object(this._addButton) )
            { this._addButton.hide(); }
        if ( isc.isA.Object(this._deleteButton) )
            { this._deleteButton.show(); }
        this.onSurveyAdded(survey);
		//Fix bug 132				
		_show();
        },

    /**
     * 
    _getSelectedRow: function ()
        {
        var rec = this.treegrid.getSelectedRecord();
        if ( isc.isAn.Object(rec) )
            { return this.getRecordIndex(); }
        else
            return -1;
        },
     */

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

        OPINIATOR_SurveySelector.lastSelectedRow = this._treegrid.getRecordIndex(node);

        ViewPortID.setSubtitle(node.levelName);

        if ( isc.isAn.Object(node) )
            {
            if ( node.isFolder )
                { 
                if ( isc.isA.Object(this._addButton) )
                    { this._addButton.show(); }
                if ( isc.isAn.Object(this._deleteButton) )
                    { this._deleteButton.hide(); }
                this.onOrgUnitOpen(node.recordId); 
                }
            else
                { 
                if ( isc.isAn.Object(this._addButton) )
                    { this._addButton.hide(); }
                if ( isc.isA.Object(this._deleteButton) )
                    { this._deleteButton.show(); }
                this.onSurveyOpen(node.recordId); 
                }
            }
        else
            {
            this.onNothingOpen(); 
            }
        },

    _deleteSurvey: function ( surveyid )
        {
        this.showBusy(false);

        var node = null;
        var nodes = this._surveyTree.nodes;

        // Find the node
        for ( var i = 0; i < nodes.length; i++ )
            {
            node = nodes[i];
            if ( !node.isFolder && (node.recordId == surveyid) )
                { break; }
            }

        if ( node !== null )
            { this._treegrid.getData().remove(node); }

        // Open the selected node if a new node was selected.
        this._openNode();
        },

    _newSurvey: function( survey )
        {
        this.showBusy(false);
        if ( isc.isAn.Object(this._addButton) )
            { this._addButton.hide(); }
        if ( isc.isAn.Object(this._deleteButton) )
            { this._deleteButton.hide(); }
        this.onSurveyOpen(survey);
        },


    selectSurvey: function( survey )
        {
        // Find the surveys node
        var node = this._findSurveyNode(survey);
        if ( isc.isAn.Object(node) )
            {
            this._treegrid.deselectAllRecords();
            this._treegrid.selectRecord(node);
            }
        },

    getSurveyTree: function()
        { return this._surveyTree; },

    createSurvey: function ()
        {
        this.showBusy(true, OPINIATOR.BUSY_DELAY);
        var orgnode = this._treegrid.getSelectedRecord();
        if ( orgnode.isFolder )
            { WebClientSvc.newSurvey(orgnode.recordId, this.callback("_newSurvey"), this.callback("error") ); }
        },

    deleteSurvey: function ()
        {
        var surveynode = this._treegrid.getSelectedRecord();
        if ( !surveynode.isFolder )
            {
            this._pendingDelete = surveynode.recordId;
            OPINIATOR.askOk("Delete the survey '<b>"+surveynode.levelName+"</b>'? <br> <b>Note</b>: All survey responses will be deleted!", 
                          this.callback("deleteSurveyReply"));
            }
        },

    deleteSurveyReply: function ( ok )
        { 
        if ( ok )
            { 
            WebClientSvc.deleteSurvey(this._pendingDelete, this.callback("_deleteSurvey"), this.callback("error") ); 
            delete this._pendingDelete;
            }
        },

    error : function( code, msg )
        {
        this._treegrid.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}; }

    });

