isc.defineClass("OPINIATOR_OpenEndedView",isc.ListGrid);
OPINIATOR_OpenEndedView.addProperties({

    // Cataegory id of the contents to be viewed
    catid:null,


    // Super class Properties
    canPickFields:false,
    canResizeFields:true,
    canFreezeFields:false,
    canReorderFields:false,
    canGroupBy:false,
    canHover:true,
    canEdit:false,
    leaveScrollbarGap:false,
    showAllRecords:false,
    showHeader:false,
    showHeaderContext:true,
    alternateRecordStyles:false,
    border:"1px solid #000000",
    headerBaseStyle:"kpiPaneHeader",
    baseStyle:"kpiPaneCell",
    styleName:"kpiPaneBody",
    bodyStyleName:"kpiPaneBody",
    bodyBackgroundColor:null,
    hoverWidth:300,
    wrapCells:false,
    fields: [ 
        { 
        name:"time", 
        title:"Time", 
        align:"left", 
        baseStyle:"kpiPaneCellSmall", 
        type:"date", 
        cellAlign:"left", 
        showHover:false,
        width:150,
        formatCellValue: function (value, record, rowNum, colNum, grid)
            { 
            if ( Date.compareLogicalDates(new Date(), new Date(record.time)) === 0 )
                {
                return "Today " + record.time.dFormat("h:MM TT"); 
                }
            else
                {
                return record.time.dFormat("mmm d h:MM TT"); 
                }
            }
        },
        {
		   	name:"url", 
		    title:"URL", 
		    type:"text", 
		    align:"center", 
		    cellAlign:"left",
		    showHover:false,
			width:25,
		    formatCellValue: function (value, record, rowNum, colNum, grid)
	        { 
				if(record.url != null && record.url != "noaudio"){
					return "<a href='#' onclick=\"playAudio('" + record.url + "');\"><img src='images/speaker.png' style='width:16px;height:16px;border: none;'/></a>";
				} else {
					return "";
				}
	        }
        },
        {
           	name:"download", 
            title:"Download", 
            type:"text", 
            align:"center", 
            cellAlign:"left",
            showHover:false,
    		width:25,
            formatCellValue: function (value, record, rowNum, colNum, grid)
            { 
    			if(record.url != null && record.url != "noaudio"){
    				return "<a href='download/" + record.url + "'><img src='images/download.png' style='width:16px;height:16px;border: none;'/></a>";
    			} else {
    				return "";
    			}
    		}
        },
        {
        name:"text", 
        title:"Text", 
        type:"text", 
        align:"center", 
        cellAlign:"left",
        showHover:true,
        formatCellValue: function (value, record, rowNum, colNum, grid)
            { return record.text; }
        }],

    initWidget: function () 
        { 
        this.Super("initWidget", arguments); 
        this._entitytype = "";
        this._entityid = -1;
        // Bind the widget to the WebService
        },

    destroy: function()
        {
        delete this._entitytype;
        delete this._entityid;
        delete this.catid;
        this.setDataSource(null);
        this.Super("destroy", arguments);
        },

    updateView: function ( entitytype, entityid )
        {
        this.invalidateCache();
        if ( entitytype != this._entitytype || entityid != this._entityid)
            {
            this._entitytype = entitytype;
            this._entityid = entityid;
            var ds = WebClientSvc.getFetchResponsesDS(this.fields, entitytype, entityid, this.catid); 			
            this.setDataSource(ds);
            this.fetchData();
            }
        }
    });


/**
 * @class OpenEndedSection    Class is used to create 
 * collapsable StackSections for the OpenEndedPane.  The class
 * can create and destory its contents on the fly.
 * 
 * @author ktyra (10/21/2008)
 *  
 */
isc.defineClass("OPINIATOR_OpenEndedSection", isc.SectionHeader);
OPINIATOR_OpenEndedSection.addProperties({

    //  The OpenEnded Category
    tcat: null,

    // Private Properties
    _contents:null,
    _views:null,

    // Superclass Properties
    /**
     *  Expand/Collapse icon properties 
     */
    iconWidth:24,
    iconHeight:24,
    skinImgDir:isc.Page.getAppDir()+"/images/skin/",
    baseStyle:"performanceSection",
    icon:"[SKIN]OpenEndedSection/opener.png",

    initWidget : function () 
        { this.Super("initWidget", arguments); },

    destroy: function()
        {
        this.tcat = null;
        this.destroyViewPort();
        this.Super("destroy", arguments);
        },

     /**
      * Destroys the sections contents
      */
    destroyViewPort: function () 
        {
        if ( isc.isAn.Object(this._contents) )
            { 
            this._views = null;
            isc.Log.logInfo("Destroying Section Contents");
            this._contents.destroy(); 
            this._contents = null;
            }
        },

    createViewPort: function ( catid )
        {
        // Destroy and preexisting contents
        this.destroyViewPort();
        this._contents = OPINIATOR_OpenEndedView.create({catid: catid, height:"100%"});
        return this._contents;
        },

    getViewPort: function ()
        { return this._contents; },

    updateView: function ( entitytype, entityid )
        {
        if ( isc.isAn.Canvas(this._contents) )
            { this._contents.updateView(entitytype, entityid); }
        }

    });


isc.defineClass("OPINIATOR_OpenEndedPane", isc.SectionStack);
OPINIATOR_OpenEndedPane.addProperties({

    // Private properties
    _tcats: null,

    /// Super Class Properties
    leaveScrollbarGap:true,
    overflow:"auto",
    //  Only one section should be open at a time.  Memory consumption and performance become
    //  strained when more then one section open.  Potentially due to the number flash 
    //  objects opened.
    visibilityMode:"mutex", 
    sectionHeaderClass:"OPINIATOR_OpenEndedSection",
    headerHeight:40,
    animateSections:OPINIATOR.STACK_ANIMATE,
    animateMemberTime:OPINIATOR.STACK_ANIMATE_TIME,
    styleName: "performancePane",

    initWidget : function () 
        { this.Super("initWidget", arguments); },

    destroy: function( )
        {
        delete this._tcats;
        delete this._analytics;
        this.Super("destroy", arguments);
        },

    setAnalytics: function ( analytics )
        {
		var type = analytics.type;
        this._analytics = analytics;
        var acats = analytics.list;
        var newtcats = acats.findAll("type", "TEXT");

        if ( !isc.isAn.Array(newtcats) )
            { newtcats = []; }
			
		if (type == "ORG") {
			newtcats.sortByProperty("name", true);
		}
       // else
       //     { newtcats.sortByProperty("name"); }

        // Check for same structure.  If same structure then update the data for
        // the sections
        if ( OPINIATOR.listDiffer(this._tcats, newtcats, "id") )
            { 
            this._createSections(newtcats); 
            this._tcats = newtcats;
            }
        else
            {
            this._tcats = newtcats;
            this._updateSections();
            }
        },

    _updateSections: function ()
        {
        var ids = this.getSections();
        if ( isc.isA.List(ids) )
            {
            var len = ids.getLength();
            for (  var i = 0; i < len; i++  )
                { 
                var sec = this.getSectionHeader(ids[i]);
                if ( isc.isAn.Object(sec) )
                    { sec.updateView(this._analytics.type, this._analytics.id); }
                }
            }
        },

    /**
     * Create the properties for OpenEnded sections for data in 
     * the dataset properties 
     */
    _createSections: function (tcats)
        {
        var sections = this.getSections();
        for ( var i = sections.getLength() - 1; i >= 0; i-- )
            { this.removeSection(i); }

        if ( tcats !== null )
            {
            // Create a section for each category and place the sections in a stack widget.
            sections = new Array(len); 
            var len = tcats.getLength();
            for ( i = 0;  i < len; i++ )
                { sections[i] = {ID:i, tcatid:tcats[i].id, title:tcats[i].name, expanded:false}; }

            this.addSections(sections);
            }
        },

    /**
     *  Overrides the section expansion in order to create the
     *  contents of the section just before expansion.
     *  
     *  @param section  The section to be expanded supposedly can be
     *                  either a Section Object, Section Id, or
     *                  Section Name.  Currently we only support
     *                  object.
     *
     *  @param callback Method to be called once the expansion has
     *                  completed. So far does not appear to work.
     */
    expandSection: function ( section, callback )
        {
        var tcat = this._tcats.find("id", section.tcatid);
        var viewport = section.createViewPort(section.tcatid);
        section.updateView(this._analytics.type, this._analytics.id);
        this.addItem(section, viewport, 0);
        this.Super("expandSection", arguments);
        },

    _sectionCollapsed: function( section )
        {
        if ( section )
            {
            this.removeItem(section, section.getViewPort()); 
            section.destroyViewPort();
            }
        },

    _sectionExpanded: function( section )
        { this._prevSection = section; },

    /**
     *  The default behaviour of a Mutex SectionStack is not to
     *  collapse the Section if its openned.  In other words, unless
     *  we are openning another section the default behavour won't
     *  allow the current one to collapse.  We are overriding that
     *  behaviour here.
     * 
     */
    sectionHeaderClick: function ( section )
        {
        // If Expand and Collapsing the same section then just collapse or expand.  This is different
        // the the standard SmartClient Mutex logic
        if ( this._prevSection && (this._prevSection.ID == section.ID) )
            {
            if ( this.sectionIsExpanded(section) )
                { this.collapseSection(section, this.ID+"._sectionCollapsed("+this._prevSection.ID+")"); }
            else
                { this.expandSection(section); }
            }
        else
            {
            //  This is the standard SmartClient mutex logic except we are destroying the conents
            //  of the collapsed section after the animation as we do above. Because too many open
            //  flash charts chew up memory.
            if ( this._prevSection && this.sectionIsExpanded(this._prevSection) )
                { this.collapseSection(this._prevSection, this.ID+"._sectionCollapsed("+this._prevSection.ID+")"); }

            this.expandSection(section); 
            this._prevSection = section;
            }
        }        
    });

function playAudio(url) {
	var audio=document.createElement("div");
	document.body.appendChild(audio);
	audio.innerHTML = "<EMBED SRC=" + url + " WIDTH=1 HEIGHT=1 HIDDEN=\"true\" AUTOSTART=\"true\" LOOP=\"false\"></EMBED>";
	return false;
}
