// ----- GeneralForm -----------

isc.defineClass("OPINIATOR_KeywordStatusItem", isc.SelectItem);
OPINIATOR_KeywordStatusItem.addProperties({

    // Superclass properties
    animatePickList:true,
    showTitle:true,
    showIcons:true,
    showFocused:true,
    showFocusedAsOver:false,
    titleAlign:"left",
    titleOrientation:"left",
    align:"left",
    textAlign:"left",

    valueMap: { "OFF": "Off", "ON": "On", "SCHEDULE": "Scheduled" },
    imageURLPrefix:"icons/16/",
    imageURLSuffix:".png",
    valueIcons: { "OFF": "off", "ON": "on", "SCHEDULE": "schedule" },
    valueIconSize: 16,
    icons: null,

    initWidget: function () 
        {
        this.Super("initWidget", arguments);
        },

    /**
     *  Sets the icon stating whether or not the keyword is
     *  availabile
     */
    setKeywordCheck: function ( available, hint )
        {
        if ( available ) 
            {
            if ( !isc.isA.String(hint) )
                {
                hint = "Keyword Available";
                }
            this.setHint(hint);
            this.setIcons([{src: "available.png"}]);
            }
        else
            {
            if ( !isc.isA.String(hint) )
                {
                hint = "Check Keyword";
                }
            this.setHint(hint);
            this.setIcons([{
                src: "unavailable.png", 
                click: function ( form, item, icon )
                    {
                    var keyword = form.getValue("keyword");
                    if ( isc.isAn.emptyString(keyword) )
                        {
                        OPINIATOR.warn("You must set a keyword first");
                        return;
                        }
                    var v = item.getValue();
                    var surveyid = form.surveyid;
                    var startdate = null; 
                    var enddate = null;
                    if ( item.getValue() == "SCHEDULE" )
                        {
                        startdate = SEStartTimePickerID.getDateTime();
                        enddate = SEEndTimePickerID.getDateTime();
                        }
                    form.showBusy(true, 100);
                    WebClientSvc.checkKeywordAvailability(surveyid, keyword, startdate, enddate, 
                                                          {target:item, methodName:"checkKeywordReply"},
                                                          {target:item, methodName:"checkError"}
                                                          );
                    }
                }]);
            }

        this.redraw();
        },


    checkKeywordReply: function ( available )
        {
        this.form.showBusy(false);
        if ( !available )
            {
            OPINIATOR.warn("Keyword: '"+ this.form.getValue("keyword") +
                     "' is Unavailable for date range specified");
            }
        this.setKeywordCheck(available);
        },

    clearKeywordCheck: function ( available )
        {
        this.setHint(null);
        this.setIcons(null);
        },

    checkError: function ( code, msg )
        {
        this.form.showBusy(false);
        OPINIATOR.warn("checkAvailability(Failed): " + msg);
        },

    changed: function ( form, item, value )
        {
        switch ( value )
            {
            case "OFF": 
                {
                this.clearKeywordCheck();
                this.showSchedule(false);
                break;
                }

            case "SCHEDULE": 
                {
                this.setKeywordCheck(false);
                this.showSchedule(true);
                break;
                }

            case "ON": 
                {
                this.setKeywordCheck(false);
                this.showSchedule(false);
                break;
                }

            default: 
                break;
            }
        },

    setInitialStatus: function ( status )
        {
        this.setValue(status);

        switch ( status )
            {
            case "OFF": 
                {
                this.clearKeywordCheck();
                this.showSchedule(false);
                break;
                }

            case "SCHEDULE": 
                {
                this.setKeywordCheck(true, "Keyword Reserved");
                this.showSchedule(true);
                break;
                }

            case "ON": 
                {
                this.setKeywordCheck(true, "Keyword Reserved");
                this.showSchedule(false);
                break;
                }

            default:
                break;
            }
        },

    showSchedule: function ( show )
        {
        if ( show )
            {
            SEStartTimeID.show();
            SEEndTimeID.show();
            }
        else
            {
            SEStartTimeID.hide();
            SEEndTimeID.hide();
            }
        }

    });



isc.defineClass("OPINIATOR_SEGeneralForm", isc.DynamicForm);
OPINIATOR_SEGeneralForm.addProperties({
    // Constructor Properties 
    parentEditor: null,
	
	// recipients
	globalRecipients: null,
	surveyRecipients: null,
	fullscreenlinks: null,
	
    // Superclass Properties
    showBusy:OPINIATOR_ShowBusy,
    destroyBusy:OPINIATOR_DestroyBusy,

    // Superclass Properties
    width:"100%",    
    minColWidth:10,
    cellPadding:2,
    numCols:2,
    fixedColWidths:false,
    titleWidths:80,
    cellBorder:0,
    showResizeBar:false,
    layoutAlign:"left",
    itemHoverDelay:3000,
    selectOnFocus:true,
    items:[
        { height:5, startRow:true, editorType:"rowSpacer" },
        //  Survey Name Row
        {
        name:"name",
        type:"text",
        title:"Survey Name",
        width:250,
        height:25,		
        _constructor:"OPINIATOR_TextItem"
        },
        { height:5, startRow:true, editorType:"rowSpacer" },

        //  Survey Description Row
        {
        startRow:true,
        title:"Survey Description",
        type:"text",
        name:"description",
        rowSpan:2,
        width:250,
        _constructor:"OPINIATOR_TextAreaItem"
        },
        { height:5, startRow:true, _constructor:"RowSpacerItem" },

        //  Survey Frequency
        {
        name:"respFreq",
        title:"Respondent Frequency",
        titleAlign:"left",
        align:"left",
        startRow:true,
        type:"enum",
        valueMap: { 
            "UNLIMITED": "Unlimited", 
            "HOURLY": "Hourly",
            "DAILY": "Daily",
            "WEEKLY": "Weekly",
            "MONTHLY": "Monthly",
            "YEARLY": "Yearly",
            "ONCE": "Once"
            }, 
        width:120,
        height:25
        },
        { height:5, startRow:true, _constructor:"RowSpacerItem" },

        //  Survey Keyword Row
        {
        title:"Keyword",
        name:"keyword",
        startRow:true,
        type:"text",
        width:100,
        height:25,
        hoverWidth:300,
        itemHoverHTML: function () 
             { 
             return "The keyword is a text word sent by the user to initiate a Survey.  Keywords can be shared amongst Surveys running at different times but only one keyword can be active at a time.";
             },
        _constructor:"OPINIATOR_TextItem"
        },
        { height:5, startRow:true, editorType:"rowSpacer" },

        { height:5, startRow:true, editorType:"rowSpacer" },
		
		{
	        name:"mobileUrl",
	        type:"text",
	        title:"Mobile URL",
	        startRow:true,
			length:100,
	        width:250,
	        height:25,		
	        _constructor:"OPINIATOR_StaticTexttem"
        },
        //Allow MobiSurvey without Mobile Number
		{
			name:"mobileNotRequired",
        	type:"boolean",
        	title:"Mobile Number Not Required",
        	startRow:true,		       
        	height:25       
        },
        
        {
        name:"code",
        type:"text",
        title:"Coupon Code",
        startRow:true,
		length:30,
        width:250,
        height:25,		
        _constructor:"OPINIATOR_TextItem"
        },
		
		{
			name:"displaycode",
        	type:"boolean",
        	title:"Display Coupon Code",
			defaultValue:"true",
        	startRow:true,		       
        	height:25       
        },
		
		{
	        name:"limit_by_ip",
	        title:"Limit by IP Address",
	        type:"boolean",
	        startRow:true,
	        height:25
        },
		
		{
	        name:"onetimeevent",
	        title:"One Time Event",
	        type:"boolean",
	        startRow:true,
	        height:25
        },
		
		 {
        name:"surveyPhoneNumber",
        type:"long",
        title:"Survey Phone Number",
        startRow:true,
		length:30,
        width:250,
        height:25,		
        _constructor:"OPINIATOR_TextItem"
        },
		
		 {
        name:"surveyCode",
        type:"long",
        title:"Survey Code",
        startRow:true,
		length:30,
        width:250,
        height:25,		
        _constructor:"OPINIATOR_TextItem"
        },
		
		{ height:5, startRow:true, editorType:"rowSpacer" },
		
        {
	        type:"section",
	        defaultValue:"Survey Limit",
	        sectionExpanded:false,
	        canCollapse:true,			
	        itemIds:["survey_limit", "height_space1",
					 "survey_taken", "height_space2",
					 "survey_remain", "height_space3",
					 "trigger_alert", "height_space4",
					 "survey_recipient", "height_space5",
					 "global_recipient", "height_space6",
					 "toolbar_button"]
        },
		
		// Survey Limit
        {
	        name:"survey_limit",
	        type:"text",
	        title:"Survey Limit",
	        width:100,
	        height:25,
	        _constructor:"OPINIATOR_TextItem"
        },
        { height:5, startRow:true, editorType:"rowSpacer", name: "height_space1" },

		// survey taken
		{
	        name:"survey_taken",
	        type:"text",
	        title:"Survey Taken",
	        width:100,
	        height:25,
	        _constructor:"OPINIATOR_TextItem"
        },
        { height:5, startRow:true, editorType:"rowSpacer" , name: "height_space2"},
		
		// survey remain		
		{
	        name:"survey_remain",
	        type:"text",
	        title:"Survey Remain",
	        width:100,
	        height:25,
	        _constructor:"OPINIATOR_TextItem"
        },
        { height:5, startRow:true, editorType:"rowSpacer", name: "height_space3" },
		
		// Trigger Alert When Below
		{
	        name:"trigger_alert",
	        type:"text",
	        title:"Trigger Alert When Below",
	        width:100,
	        height:25,
	        _constructor:"OPINIATOR_TextItem"
        },
        { height:5, startRow:true, editorType:"rowSpacer", name: "height_space4"  },
		
		// Alert Recipients
		{
        ID:"AlertRecicipientSurveyID",
		name: "survey_recipient",
		title: "",
        startRow:true,
        height:30,
		width: 250,
        type:"canvas",
        showTitle:true,
        showFocused:true,
        showFocusedAsOver:false,
        titleAlign:"right",
        titleOrientation:"left",
        align:"left",
        textAlign:"left",
        canvasConstructor:"OPINIATOR_RecipientList",
        canvasProperties:{ID:"AlertRecicipientSurvey",
						  fields: [
	            					{
										target: this,
					            		name:"name", 	         
										title: "Assigned Recipients",  
					            		align:"center", 
					            		width:"*",
					            		editorType:"OPINIATOR_TextItem",
					            		cellAlign:"left"
	            					}			
        				 		]	
						 }
        },	

		// toolbar button
		{
			ID:"ToolBarRecipientID",
			name: "toolbar_button",
			title: "",
	        startRow:true,
	        height:30,			
	        type:"canvas",
	        showTitle:true,
	        showFocused:true,
	        showFocusedAsOver:false,
	        titleAlign:"left",
	        titleOrientation:"left",
	        align:"left",
	        textAlign:"left",
	        canvasConstructor:"OPINIATOR_ButtonBar",
	        canvasProperties: {
				ID: "ToolBarRecipient",
				align: "left",
				layoutAlign: "center",
				canFocus: false,
				defaultWidth: 80,
				height: 30,
				width: 290,
				target: this,
				buttons: [
					{
		                ID: "addRecipientSurvey",
		                title: "Add",
						target: this,
		                visibility:"visible",
		                tabIndex:1,
		                icon: "icons/16/category.png",
		                click: function () {
							this.target.SEGeneralFormID.addRecipient();
							return true;
						}
                	},
				
                	{
		                ID: "removeRecipientSurvey",
		                title: "Remove",
		                visibility:"visible",
		                tabIndex:2,
		                icon: "icons/16/down.png",
		                width:110,
		                click: function () { 
							this.target.SEGeneralFormID.removeRecipient();
							return true; 
						}
               		 }
				]
			}
		},		
		// Global Recipients
		{
        ID:"GlobalRecicipientSurveyID",
		name: "global_recipient",
        startRow:true,
        height:30,
		width: 250,
        type:"canvas",		
        showTitle:true,
		title: "",
        showFocused:true,
        showFocusedAsOver:false,
        titleAlign:"right",
        titleOrientation:"left",
        align:"left",
        textAlign:"left",
        canvasConstructor:"OPINIATOR_RecipientList",
        canvasProperties:{ID:"GlobalRecicipientSurvey",
						  fields: [
	            					{
										target: this,
					            		name:"name", 	         
										title: "Global Recipients",  
					            		align:"center", 
					            		width:"*",
					            		editorType:"OPINIATOR_TextItem",
					            		cellAlign:"left"
	            					}			
        				 		]	
						 }
        },		
				
		{
	        type:"section",
			name: "section_present",
	        defaultValue:"Presentation mode",
	        sectionExpanded:true,
	        canCollapse:false,
	        itemIds:["presentation_mode", "space_presentation", "fullscreen_list"]
        },
		
		// checkbox presentation mode
		{
	        name:"presentation_mode",
	        title:"Enable Presentation Mode",
	        type:"boolean",
	        startRow:true,
	        height:25
        },
		
		{ name:"space_presentation", height:5, startRow:true, editorType:"rowSpacer" },
		
		{
        ID:"FullScreenListID",
		name: "fullscreen_list",
        startRow:true,
        height:30,
		width: 250,
        type:"canvas",		
        showTitle:true,
		title: "",
        showFocused:true,
        showFocusedAsOver:false,
        titleAlign:"right",
        titleOrientation:"left",
        align:"left",
        textAlign:"left",
        canvasConstructor:"OPINIATOR_FullScreenLinkList",
        canvasProperties:{ID:"FullScreenList",
						  fields: [
						  
						  			{
										target: this,
										name: "title",					            		
										title: "Title",  
					            		align:"center", 
					            		width:"*",
					            		editorType:"OPINIATOR_TextItem",
					            		cellAlign:"left"									
	            					}	
        				 		]	
						 }
        },
		
        {
        type:"section",
        defaultValue:"Survey Status",
        sectionExpanded:true,
        canCollapse:false,
        itemIds:["space1", "status", "start", "end"]
        },

        //  Status Row
        { name:"space1", height:5, startRow:true, editorType:"rowSpacer" },
        {
        ID:"SEStatusID",
        title:"",
        name:"status",
        width:150,
        hoverWidth:300,
        itemHoverHTML: function () { return "Sets the running status of the Survey.  If set to <b>On</b> the survey will run infinitely until turned off.  If set to <b>Scheduled</b> the survey will be active only during the specified date range.  If set to <b>Off</b> the Survey will not be active and the keyword associated with the Survey may be used by other surveys."; },

        type:"enum",
        _constructor:"OPINIATOR_KeywordStatusItem"
        },
        
        { height:15, startRow:true, _constructor:"RowSpacerItem" },

        //  Start Time
        {
        ID:"SEStartTimeID",
        title:"Start",
        name:"start",
        startRow:true,
        height:30,
        type:"canvas",
        showTitle:true,
        showFocused:true,
        showFocusedAsOver:false,
        titleAlign:"right",
        titleOrientation:"left",
        align:"left",
        textAlign:"left",
        canvasConstructor:"OPINIATOR_DateTimePicker",
        canvasProperties:{ID:"SEStartTimePickerID"}
        },

        { height:2, startRow:true, _constructor:"RowSpacerItem" },

        //  End Time
        {
        ID:"SEEndTimeID",
        title:"End",
        name:"end",
        startRow:true,
        height:30,
        showTitle:true,
        showFocused:true,
        showFocusedAsOver:false,
        titleAlign:"right",
        titleOrientation:"left",
        align:"left",
        textAlign:"left",
        type:"canvas",
        canvasConstructor:"OPINIATOR_DateTimePicker",
        canvasProperties:{ID:"SEEndTimePickerID"}
        } 
        ],

	
	addRecipient:function() {
		//alert(GlobalRecicipientSurvey.data);
		var item = this.getSelectedItem(GlobalRecicipientSurvey);
		
		if (item != null) {
			this.surveyRecipients.add(item);
			this.globalRecipients.remove(item);	
		}
		/* FIXME @author Huy.Tran (09/03/2010)
		 * Fix bug# 123
		*/
		this.parentEditor.enableSave();
	},
	
	removeRecipient:function() {
		var item = this.getSelectedItem(AlertRecicipientSurvey);
		
		if (item != null) {
			this.globalRecipients.add(item);
			this.surveyRecipients.remove(item);	
		}
		/* FIXME @author Huy.Tran (09/03/2010)
		 * Fix bug# 123
		*/
		this.parentEditor.enableSave();
	},
	
    initWidget: function ()
	{
        this.Super("initWidget", arguments);		
    },

    destroy: function ()
        {
        this.parentEditor = null;
        this.destroyBusy();
        this.Super("destroy", arguments);
        },

    edit: function ( survey )
        {
        this.surveyid = survey.id;
        this.setValue("name", survey.name);
        this.setValue("description", survey.description);
        this.setValue("respFreq", isc.isA.String(survey.respFreq) ? survey.respFreq : "UNLIMITED");
        this.setValue("keyword", survey.keyword);
		this.setValue("code", survey.code);		
		this.setValue("survey_limit", survey.surveyLimit);
		this.setValue("trigger_alert", survey.triggerAlert);
		this.setValue("presentation_mode", survey.presentationMode);
		this.setValue("limit_by_ip", survey.limitByIPAddress);
		this.setValue("onetimeevent", survey.oneTimeEvent);
		this.setValue("displaycode", survey.displayCode);
		this.setValue("mobileUrl", "http://srv.opiniator.com/mobi/m/" + (survey.keyword != null ? survey.keyword : ""));
		this.setValue("mobileNotRequired", survey.mobileNotRequired);
		this.setValue("surveyPhoneNumber", survey.surveyPhoneNumber);
		this.setValue("surveyCode", survey.surveyCode);
		
		var limit = parseInt(survey.surveyLimit, 10);
		var taken = parseInt(survey.surveyTaken, 10);
		
		/* FIXME @author Huy.Tran (09/01/2010)
		 * Fix bug# 126,122
		*/
		if (isc.isA.Number(limit)) {
			if (!isc.isA.Number(taken)) {
				taken = 0;
			}
			this.setValue("survey_taken", taken);
			var remain = limit - taken;
			if (isc.isA.Number(remain)) {
				this.setValue("survey_remain", remain);
			}
		}else{
			this.setValue("survey_taken","");
			this.setValue("survey_remain","");
		}
		//End fix bug# 126,122	
		
        this.getItem("status").setInitialStatus(survey.status);		
        //this.focusInItem("name");

		if (isc.isA.Number(survey.alertId)) {
			this.surveyRecipients = OPINIATOR.toArray(survey.recipients);			
		} else {
			this.surveyRecipients = [];		
		}
		
		if (this.surveyRecipients == null) {
			this.surveyRecipients = [];
		}
		this.getGlobalRecipients();
		AlertRecicipientSurvey.setValue(this.surveyRecipients);
		

        SEStartTimePickerID.parentEditor = this.parentEditor;
        SEStartTimePickerID.setDateTime(survey.startDate);

        SEEndTimePickerID.parentEditor = this.parentEditor;
        if ( !isA.Date(survey.endDate) )
            {
            var now = new Date();
            survey.endDate = new Date(now.getTime() + 86400000);
            }
        SEEndTimePickerID.setDateTime(survey.endDate);
		
		this.showFullScreenList(survey.presentationMode);
		this.getFullscreenList(survey);		
		this.disableSurveyTaken();
        },

    save: function ( survey ) {
        survey.name = this.getValue("name");
        survey.description = this.getValue("description");
        survey.keyword = this.getValue("keyword");
		survey.code = this.getValue("code");
		survey.displayCode = this.getValue("displaycode");
        survey.respFreq = this.getValue("respFreq");
        survey.status = this.getValue("status");
		survey.surveyLimit = this.getValue("survey_limit");
		survey.triggerAlert = this.getValue("trigger_alert");
		survey.mobileNotRequired = this.getValue("mobileNotRequired");
		survey.surveyPhoneNumber = this.getValue("surveyPhoneNumber");
		survey.surveyCode = this.getValue("surveyCode");
		/* FIXME @author Huy.Tran (09/01/2010)
		 * Fix bug# 126
		*/		
		var limit = parseInt(survey.surveyLimit, 10);		
		var triggerAlert = parseInt(survey.triggerAlert, 10);
		if(!isc.isA.Number(limit)){
			survey.surveyLimit="undefined";
		} 
		if(!isc.isA.Number(triggerAlert)){
			survey.triggerAlert="undefined";
		}								
		//End fix bug# 126			
		survey.presentationMode = this.getValue("presentation_mode");
		survey.limitByIPAddress = this.getValue("limit_by_ip");
		survey.oneTimeEvent = this.getValue("onetimeevent");
		
        if ( survey.status == "SCHEDULE" )
            {
            survey.startDate = SEStartTimePickerID.getDateTime(); 
            survey.endDate = SEEndTimePickerID.getDateTime();
            }
        else
            {
            survey.startDate = null;
            survey.endDate = null;
            }
			
		// set recipients for survey
		survey.recipients = this.surveyRecipients; 
		this.getFullscreenList(survey);
		this.disableSurveyTaken();
    },

    itemChange: function (item, newValue, oldValue)
        {
        var start;
        var end;
        if ( oldValue != newValue  ) {
            this.parentEditor.enableSave();
            if ( item.getFieldName() == "keyword" ) {
                if ( isc.isAn.emptyString(newValue) ) {
                	SEStatusID.setInitialStatus("OFF"); 
                } else if ( this.getValue("status") != "OFF" ) {
                   	SEStatusID.setKeywordCheck(false); 
                }
                //Autoset mobile URL
				var mobileURL="http://srv.opiniator.com/mobi/m/";						
				if(newValue!=null && newValue!=""){
					mobileURL+=newValue;
				}
				this.setValue("mobileUrl", mobileURL);			
            }
		}
		
		// auto update calculation for survey remain
		if (item.getFieldName() == "survey_limit") {
			var limit = parseInt(newValue, 10);
			var taken = parseInt(this.getValue("survey_taken"), 10);
			
			if (!isc.isA.Number(taken)) {
				taken = 0;
			}
			this.setValue("survey_taken", taken);
			var remain = limit - taken;
			if (isc.isA.Number(remain)) {
				this.setValue("survey_remain", remain);
			}
		}		
        },
		
	// get all recipients
	getGlobalRecipients: function() {
		this.showBusy(true, OPINIATOR.BUSY_DELAY);
		WebClientSvc.findRecipient(null, false, recipientOrgId, this.callback("setAllRecipientForList"), this.callback("error"));
	},
	
	// callback function when get all recipients successfully.
	setAllRecipientForList: function( recipients ) {
		this.showBusy(false);
		
		if (recipients.list == 'undefined') {
			recipients.list = [];
		}
		
		this.globalRecipients = OPINIATOR.toArray(recipients.list);
		var list = this.surveyRecipients;			
		for (var i=0 ; i < list.length; i++) {
			var index = this.globalRecipients.findIndex("id", list[i].id);
			if (index > -1) {
				this.globalRecipients.removeAt(index);	
			}
		}
		GlobalRecicipientSurvey.setValue(this.globalRecipients);
		
	},

	// get recipients belong to survey
	getSurveyRecipients: function() {
		this.surveyRecipients = [];
		AlertRecicipientSurvey.setValue(this.surveyRecipients);
	},

	getSelectedItem:function( grid ) {
		var sel = grid.getSelectedRecord();
		return sel;
	},
		
	getFullscreenList: function( survey ) {
		this.fullscreenlinks = OPINIATOR.toArray(survey.links);
		
		var links = [];
		
		for (var i = 0 ; i < this.fullscreenlinks.length; i++) {
			var obj = this.fullscreenlinks[i];
			obj.code = location.href + "chart?h=" + obj.code;
			obj.title = "<a href=\"" + obj.code + "\" target=\"_blank\" class=\"chart-link\">" + obj.title + "</a>";
			links.add(obj);
		}
		
		FullScreenList.setValue(links);
	},
		
	showFullScreenList: function( value ) {
        if (value == true) {
			this.getItem("fullscreen_list").show();
        }
        else if (value == false || typeof(value) == "undefined") {
           this.getItem("fullscreen_list").hide();
        }
	},
	
	disableSurveyTaken: function() {
		this.getItem("survey_taken").disable();
		this.getItem("survey_remain").disable();
		if(typeof(this.surveyid) == "undefined") {
			this.setValue("code", "N/A");
			this.getItem("code").disable();
		} else if(parseInt(this.surveyid) > 0) {
			this.getItem("code").enable();
		}
	},
	
	error: function (code, msg)
    {        
        switch ( msg )
    	{
        	default:
            OPINIATOR.warn(msg);
            break;
		}
	},
	
	callback: function (methodName) { 
		return {target:this, methodName:methodName};
	}   
	
});


// ----------------
isc.defineClass("OPINIATOR_SurveyEditor", OPINIATOR_TabSet);
OPINIATOR_SurveyEditor.addProperties({

    // Constructor Properties

    /**
     * The selector that contains the key node to this survey for 
     * refresh purposes 
     */
    selector: null,
    
    /**
     * Toolstrip to add save and cancel buttons
     */
    toolstrip: null,

    // Private Properties

    // The save button in the toolstrip
    _saveButton: null,

    // The cancel button in the toolstrip
    _cancelButton: null,

    // The Survey we are editing
    _survey: null,


    initWidget: function ()
        {
        this._saveButton = OPINIATOR_Button.create({
            ID:"SESaveID",
            title:"Save",
            visibility: "hidden",
            target:this,
            icon: "icons/16/save.png",
            layoutAlign:"center",
            click: function ()
                { this.target.save(); return true;}
            });

        this._cancelButton = OPINIATOR_Button.create({
            ID:"SECancelID",
            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);

        this.tabs = new Array();

        this.tabs.add({
            ID:"SEGeneralID",
            title:"General", 
            openPane: function ( parent, pane, survey ) 
                {
                if ( !isc.isAn.Object(pane) ) 
                    { pane = OPINIATOR_SEGeneralForm.create({ID:"SEGeneralFormID", parentEditor:parent}); }
                pane.edit(survey);
                return pane;
                },
            savePane: function ( parent, pane, survey )  
                { pane.save(survey); }
            });

        if ( !OPINIATOR_MAIN.user.orgUnitRef.isRootOrg )
            {
            this.tabs.add({
                ID:"SEQuestionnaireID",
                title:"Questionnaire",
                openPane: function ( parent, pane, survey ) 
                    {
                    if ( !isc.isAn.Object(pane) ) 
                        { pane = OPINIATOR_QuestionnaireEditor.create({ID:"SEQuestionnaireEditorID", parentEditor:parent}); }
                    pane.edit(survey);
                    return pane;
                    },
                savePane: function ( parent, pane, survey )  
                    { pane.save(survey); }
                });
            this.tabs.add({
                title:"KPI",
                ID:"SEKPIID",
                openPane: function ( parent, pane, survey ) 
                    {
                    if ( !isc.isAn.Object(pane) ) 
                        { 
                        pane = OPINIATOR_KPIListEditor.create({parentEditor:parent});
                        SEQuestionnaireEditorID.onSequenceChange({target:pane, methodName:"refreshSeqList"});
                        }

                    pane.editSeqList(survey.sequence, survey.kpis);
                    return pane;
                    },

                savePane: function ( parent, pane, survey )
                    { survey.kpis = pane.getList(); }

                });
            }

        this.Super("initWidget", arguments);

        },

    destroy: function ()
        {
        this.toolstrip = null;
        this.selector = null;
        this._saveButton = null;
        this._cancelButton = null;
        this.Super("destroy", arguments);
        },

    enableSave: function ()
        {
        this._saveButton.show();
        this._cancelButton.show();
        },

    disableSave: function ()
        {
        this._saveButton.hide();
        this._cancelButton.hide();
        },


    _verifySurvey: function ( survey )
        {
        if ( survey.status != "OFF" && isc.isAn.emptyString(survey.keyword) )
            {
            OPINIATOR.warn("You must specify a Keyword in order to turn on a survey");
            return false;
            }
        else if ( survey.status == "SCHEDULE" )
            {
            if ( survey.startDate.getTime() >= survey.endDate.getTime())
                {
                OPINIATOR.warn("The End Date of the Survey must be later in time than the Start Date");
                return false;
                }
            }

        return true;
        },

    cancel: function ( reedit )
        {
        this.disableSave();
        if ( reedit )
            { this.edit(this._survey.id); }
        },

    save: function ( callback )
        {
        if ( isc.isAn.Object(callback) )
            { this._callbackOnSave = callback; }
        else
            { delete this._callbackOnSave; }

        this.savePanes(this._survey);

        this._cleanupSurvey(this._survey);

        if ( this._verifySurvey(this._survey) )
            {
            this.showBusy(true, OPINIATOR.BUSY_DELAY);
            WebClientSvc.saveSurvey(this._survey, this.callback("_saveDone"), this.callback("error"));
            }
        },

    _cleanupSurvey: function ( survey )
        {
        // Remove KPI's no longer associated with the survey
        var chash = {};
        var len = survey.sequence.getLength();
        for ( var i = 0; i < len; i++ )
            { chash[survey.sequence[i].catref.id] = survey.sequence[i].catref; }

        len = survey.kpis.getLength();
        for ( i = len - 1; i >= 0; i-- )
            { 
            var kpi = survey.kpis[i];
            if ( !isc.isAn.Object(chash[kpi.catid]) )
                { survey.kpis.removeAt(i); }
            }
        },
        
    _saveDone: function ( survey )
        {
        this.showBusy(false);
        this.selector.refreshSurveyNode(survey);
        if ( isc.isAn.Object(this._callbackOnSave) )
            { Class.fireCallback(this._callbackOnSave); }
        else
            { 
            this._survey = survey;
            this.disableSave();
            this.openPanes(survey); 
            }
        },

    /**
     * Edits the given survey.  If the survey is passed in as a 
     * number its assumed to be the survey id and the record will be 
     * retrieved from the surver. 
     * 
     * @author ktyra (3/27/2009)
     */
    edit: function ( survey )
        {
        if ( isc.isA.Number(survey) )
            {
            this.showBusy(true, OPINIATOR.BUSY_DELAY);
            WebClientSvc.getSurvey(survey, this.callback("edit"), this.callback("error"));
            }
        else
            {
            // Update the survey node from a potential reload
            this._survey = survey;
            if ( isc.isA.Number(survey.id) )
                {
                this.selector.refreshSurveyNode(survey);
                this.disableSave();
                }
            else
                { this.enableSave(); }
            // Ensure that the all the survey's lists are indeed lists
            this.openPanes(survey);
            this.showBusy(false);
            }
        },

    openPanes : function (survey)
        {
        survey.kpis = OPINIATOR.toArray(survey.kpis);
        survey.sequence = OPINIATOR.toArray(survey.sequence);
        survey.overrides = OPINIATOR.toArray(survey.overrides);
        this.Super("openPanes", arguments);
        },

    wasModified: function ()
        { return this._saveButton.isVisible(); },

    error: function (code, msg)
        {
        this.showBusy(false);
        switch ( msg )
            {
            case "StaleState":
                OPINIATOR.warn("Changes were made to the survey by another user while you were editing.\nYour changes were lost! Please re-edit the survey.");
                break;

            case "DeletedState":
                OPINIATOR.warn("This survey has been deleted by another user.");
                this.selector.refresh();
                this.hide();
                break;

            default:
                OPINIATOR.warn("Unhandled Exception: " + msg);
                break;
            }
        },

    callback: function (methodName)
        { return {target:this, methodName:methodName}; }

    });

