/**
 * @author duy.chung
 */

isc.defineClass("OPINIATOR_AlertList", isc.ListGrid);
OPINIATOR_AlertList.addProperties({
    // Superclass Properties
    selectionType: "multi",
    canEdit:false,
    canReorderRecords:false,
    editEvent:"none",
    leaveScrollbarGap:false,
    showAllRecords:true,
    showHeader:true,
    showHeaderContext:false,
    alternateRecordStyles:false,
    border:"1px solid #000000",
    baseStyle:"choicelistCell",
    styleName:"choicelistBody",
    bodyStyleName:"choicelistBody",
    headerBaseStyle:"choicelistHeader",
    bodyBackgroundColor:null,
    headerBackgroundColor:null,
    cellHeight:20,
    cellPadding:2,
	height: "100%",
    modalEditing:true,

	// category id got from parent editor
	//catId: null,

    fields: [
            {
            name:"name", 
            title:"Alert", 
            align:"center", 
            width:"*",
           // editorProperties:{height:22},
            editorType:"OPINIATOR_TextItem",
            cellAlign:"left"
            }
        ],


    initWidget: function () { 
		this.Super("initWidget", arguments);		
	},

    destroy: function ()
        { 
        this.Super("destroy", arguments); 
        },
		
	setValue: function( alerts ) {
		this.setData(alerts);
	}
	
});


isc.defineClass("OPINIATOR_AlertForm", isc.DynamicForm);
OPINIATOR_AlertForm.addProperties({
    // Constructor Properties 
    parentEditor: null,

    // Superclass Properties
    showBusy:OPINIATOR_ShowBusy,
    destroyBusy:OPINIATOR_DestroyBusy,

    // Superclass Properties
    width:"100%",
    height:"200",
    minColWidth:10,
    cellPadding:2,
    numCols:2,
    fixedColWidths:false,
    titleWidths:80,
    cellBorder:0,
    showResizeBar:false,
    layoutAlign:"left",
    itemHoverDelay:3000,
    selectOnFocus:true,
	
	/* max text length for message */
	maxTextLength: null,
	_alert: null,
	
    items:[
        {type:"rowSpacer", height:18},               
        
		{
			name:"alertName",
			title: "Name",
			titleAlign:"left",
	        align:"left",
			tabIndex:1,
	        startRow:true,
	        wrapTitle:false,
			type:"text",
			width: 130,
			height: 25,
			length:100,
			_constructor:"OPINIATOR_TextItem"
		},
		
		{
	        name:"type",
	        title:"Type",
	        titleAlign:"left",
	        align:"left",
	        tabIndex:2,
	        startRow:true,
	        wrapTitle:false,
	        type:"enum",
	        valueMap: { 
	            "SINGLE_RESPONSE_BELOW": "Single response below", 
	            "SINGLE_RESPONSE_ABOVE": "Single response above",
	            "AVERAGE_RESPONSE_BELOW": "Average response below", 
	            "AVERAGE_RESPONSE_ABOVE": "Average response above"			
	            }, 
			defaultValue: "SINGLE_RESPONSE_BELOW",
	        width:230,
	        height:25
        },
		
		{
			name:"period",
	        title:"Period",
	        titleAlign:"left",
	        align:"left",
	        tabIndex:3,
	        startRow:true,
	        wrapTitle:false,
	        type:"enum",
	        valueMap: { 
	            "MONTH": "MTD", 
	            "YEAR": "YTD"
	            }, 
	        width:130,
	        height:25		
		}, 
		
		{
			name:"valueCompare",
			title: "Value",
			titleAlign:"left",
	        align:"left",
			tabIndex:4,
	        startRow:true,
	        wrapTitle:false,
			type:"text",
			width: 130,
			height: 25,
			_constructor:"OPINIATOR_TextItem"
		},
		
		{
			name:"message",
			title: "Message",
			titleAlign:"left",
	        align:"left",
			tabIndex:5,
	        startRow:true,
	        wrapTitle:false,
			type:"textArea",												
			width: 230,	
			height: 55,		
			_constructor:"OPINIATOR_TextAreaItem"
		},
		
		{
	        name:"spacer",
	        type:"textArea",
	        startRow:true,
	        endRow:false,
	        _constructor:"SpacerItem"
        },
		
		{
			name:"tlen",
	        type:"text",
			title:"dasdas",
	        startRow:false,
	        endRow:true,
	        showTitle:false,
	        defaultValue:"0/0",
	        textBoxStyle:"mobilenTextItem",
	        align:"left",			
	        hieght:25,				
	        textAlign:"left",
	        _constructor:"StaticTextItem"
		},		
		{
	        name:"spacer",
	        type:"textArea",
	        startRow:true,
	        endRow:false,
	        _constructor:"SpacerItem"
        },
		{
			name:"legend",	        			
	        startRow:false,
	        endRow:true,
	        showTitle:false,
	        defaultValue:"Want to include dynamic data?",	
			textBoxStyle:"dynamicData",       
	        align:"left",			
	        hieght:25,				
	        textAlign:"left",
			click: function () {
					isc.showMessage(
						"<b>&lt;number&gt;</b>: This will be replaced with the phone number associated with the survey session."
						+'<br>'+
						"<b>&lt;response&gt;</b>: This will be replaced with the user's response."
						+'<br>'+
						"<b>&lt;potential&gt;</b>: For numeric or performance questions, this will be replaced with the maximum possible score."
						+'<br>'+
						"<b>&lt;survey&gt;</b>: This will be replaced with the name of the current survey."
						+'<br>'+	
						"<b>&lt;question&gt;</b>: This will be replaced with the name of the question."
						+'<br>'+
						"<b>&lt;response:question_number&gt;</b>: The question number will specify the question, based on order in the survey."
					);						
					return true;					
				},
	        _constructor:"StaticTextItem"
		}
		
        ],		

    initWidget: function ()	
    { 
		this.Super("initWidget", arguments);		
		this.updateFields(this._alert);
		
	},	
	updateFields: function( alert ) {
		var period = this.getItem("period");
		period.hide();	
		
		// loading alert if it exists
		var obj = alert ;
		
		if (obj != null){
			var name = this.getItem("alertName");
			var type = this.getItem("type");
			var value = this.getItem("valueCompare");
			var message = this.getItem("message");
			
			name.setValue(obj.name);
			type.setValue(obj.type);
			period.setValue(obj.period);
			value.setValue(obj.valueCompare);			
			message.setValue(obj.alertText);
			
			if (type.getValue() == "AVERAGE_RESPONSE_BELOW" || type.getValue() == "AVERAGE_RESPONSE_ABOVE") {
				period.show();
			}
			var text = "";
			var tlen_item = this.getItem("tlen");
			if(message.getValue() != "") {
				text = message.getValue();
			}
			if(text == null) {
				text = "";
			}
			tlen_item.setValue("" + text.length + "/" + this.maxTextLength);
		}
	},

	_setText: function ( text )
        {
        var text_item = this.getItem("message");
        var tlen_item = this.getItem("tlen");

        if ( isc.isA.String(text) )
            {
            text_item.setValue(text);
            if ( new Number(text.length) > new Number(this.maxTextLength) )
                { tlen_item.textBoxStyle = "mobilenTextItemMaxed"; }
            else
                { tlen_item.textBoxStyle = "mobilenTextItem"; }
            tlen_item.updateState();
            tlen_item.setValue("" + text.length + "/" + this.maxTextLength);
            }
        else
            {
            text_item.setValue("");
            tlen_item.setValue("0/"+ this.maxTextLength);
            tlen_item.textBoxStyle = "mobilenTextItem";
            tlen_item.updateState();
            }
        },	
		
	itemChange: function (item, newValue, oldValue) {
		var iname = item.getFieldName();
		var period = this.getItem("period");
        switch ( iname )
            {                    
            case "message":
				var tlen_item = this.getItem("tlen");
				var messageText = 0;
                var test = newValue.length > (this.maxTextLength - 0);                
				if(newValue) {
					messageText = newValue.length;
				}
				tlen_item.setValue("" + messageText + "/" + this.maxTextLength);
                this._setText(newValue);
				this._alert.alertText = newValue;                
                break;
			case "type":
				if (newValue == "SINGLE_RESPONSE_BELOW" || newValue == "SINGLE_RESPONSE_ABOVE") {
					period.hide();			
					period.setValue("");		
					// reset period
					this._alert.period = null;
				} else if (newValue == "AVERAGE_RESPONSE_BELOW" || newValue == "AVERAGE_RESPONSE_ABOVE") {
					period.show();
				}
				this._alert.type = newValue;
				break;
			case "period":
				this._alert.period = newValue;
				break;
			case "alertName":
				this._alert.name = newValue;
				break;
			case "valueCompare":
				this._alert.valueCompare = newValue;
				break;
            default:
                break;
            }
		
        return true;
	},
	
    destroy: function ()
        {               
		delete this._alert;
        this.destroyBusy();		
        this.Super("destroy", arguments);
        },
	
	getAlert: function() {
		return this._alert;
	},
	
	setAlert: function( object ) {
		this._alert = object;
		this.updateFields(this._alert);
	}
});

isc.defineClass("OPINIATOR_AlertResponseEditor", isc.HLayout);
OPINIATOR_AlertResponseEditor.addProperties({
	showBusy: OPINIATOR_ShowBusy,
	// Constructor Properties
    parentEditor: null,
	_alerts: null,
	
	_alertlist: null,
    _toolbar: null,
	_alertFormToolBar: null,
	_alertform: null,
	
	_category: null,
	
	_survey: null,
	
	_globalRecipientList: null,
	
	_assignRecipientList: null,
	
	_updownToolBar: null,
	
	_assignRecipients: null,
	 
	_globalRecipients: null,
	
	initWidget : function () {
		this._alertlist = OPINIATOR_AlertList.create({
            height:"*",						
            target:this,
			cellClick: function() {
				this.target.refreshEditButton();
				this.target.editItem();
			}
		});		
		
		this._toolbar = OPINIATOR_ButtonBar.create({
            align:"left",
            layoutAlign:"center",
            canFocus:false,
            defaultWidth:80,
            height:30,
            width:"100%",
            target:this,
            buttons: [
                {
	                ID: "AlertAddID",
	                title: "Add",
	                visibility:"visible",
	                tabIndex:1,
	                icon: "icons/16/category.png",
	                click: function () {
						this.target._showAlertForm( null ); 
						return true;
					}
                },
                {
                ID: "AlertRemoveID",
                title: "Remove",
                visibility:"hidden",
                tabIndex:2,
                icon: "icons/16/delete.png",
                width:110,
                click: function () {
					this.target.removeItem(); 
					return true;
				}
                },
                
				{
                ID: "AlertEditID",
                title: "Edit",
                visibility:"hidden",
                tabIndex:4,               
				icon: "icons/16/pencil.png",				
                click: function () {
					this.target.editItem(); 
					return true;
				}
                }
				]
            });
		
		this._alertFormToolBar = OPINIATOR_ButtonBar.create({
            align:"right",
            layoutAlign:"center",
            canFocus:false,
            defaultWidth:80,
            height:30,
            width:290,
            target:this,
            buttons: [
                {
	                ID: "alertCancel",
	                title: "Cancel",
	                visibility:"visible",
	                tabIndex:1,
	                icon: "icons/16/cancel.png",
	                click: function () {
						this.target._hideAlertForm();
						return true;
					}
                },
				
                {
	                ID: "alertSave",
	                title: "Save",
	                visibility:"visible",
	                tabIndex:2,
	                icon: "icons/16/save.png",
	                width:110,
	                click: function () { 
						if (selectedSurvey == null) {
							OPINIATOR.warn("You must save survey first !");
							return true;
						}
						this.target._saveAlert();
						return true; 
					}
                }
				
				]
            });
		
		this._updownToolBar= OPINIATOR_ButtonBar.create({
            align:"left",
            layoutAlign:"left",
            canFocus:false,
            defaultWidth:80,
            height:30,
            width:290,
            target:this,
            buttons: [
                {
	                ID: "addRecipient",
	                title: "Add",
	                visibility:"visible",
	                tabIndex:1,
	                icon: "icons/16/category.png",
	                click: function () {
						this.target.addAssignRecipient();
						return true;
					}
                },
				
                {
	                ID: "removeRecipient",
	                title: "Remove",
	                visibility:"visible",
	                tabIndex:2,
	                icon: "icons/16/down.png",
	                width:110,
	                click: function () { 
						this.target.removeAssignRecipient();
						return true; 
					}
                }
				
				]
            });
		
		this._alertform = OPINIATOR_AlertForm.create({
				target: this,
				parentEditor: this.parentEditor,				
				title: "Alert Form",				
				maxTextLength:160
			});
		
		// recipient list belong to alert
		this._assignRecipientList = OPINIATOR_RecipientList.create({
			ID: "AlertRecicipient",			
			fields: [
	            {
					target: this,
		            name:"name", 	         
					title: "Assigned Recipients",  
		            align:"center", 
		            width:"*",
		            editorType:"OPINIATOR_TextItem",
		            cellAlign:"left"
	            }			
        	],
			width: 330,
			height: 120,
			target:this
		});
		
		this._globalRecipientList = OPINIATOR_RecipientList.create({
			ID: "GlobalRecicipient",			
			fields: [
	            {
					target: this,
		            name:"name", 	         
					title: "Global Recipients",  
		            align:"center", 
		            width:"*",
		            editorType:"OPINIATOR_TextItem",
		            cellAlign:"left"
	            }			
        	],
			width: 330,
			height: 120,
			target:this
		});
		
		this.members = [
                        isc.VLayout.create({
							width: 200, 
							height: 250,
							align: "left",
							members:[this._alertlist, OPINIATOR.vSpacer(5), this._toolbar]}
						),
						OPINIATOR.hSpacer(20),
						isc.VLayout.create({
							ID: "alertFormCanvas",
							members:[this._alertform, 
									 this._assignRecipientList,
									 OPINIATOR.vSpacer(2),
									 this._updownToolBar,
									 this._globalRecipientList,
									 OPINIATOR.vSpacer(5),
									 this._alertFormToolBar],	
							visibility: "hidden",								
							width: 400,
							height:500
						}),
                        OPINIATOR.hSpacer("20%")];

        this.layoutLeftMargin = 5;
		
		// call superclass implementation
        this.Super("initWidget", arguments);

		// get existing alert, add them to listgrid
		this.getAlertForSurveyCategory(this._survey, this._category.id);
		
		
	},
	
	destroy: function()
    {
        delete this._alerts;
        delete this._toolbar.target;
        delete this._toolbar;
        delete this._alertlist;
        delete this.parentEditor;
        this.Super("destroy", arguments);
     },
	 
	 // show alert form
	 _showAlertForm: function( obj ) {	 	
	 	if ( obj == null ) {
			obj = {
				orgUnitId: this._category.ownerId, 
	   			name: null,
	    		type: "SINGLE_RESPONSE_BELOW",
	    		period: null,
	    		valueCompare: null,    
	    		alertText: null,
	    		surveyId: this._survey,
	    		catId: this._category.id
			};
		}
		
		this._alertform.setAlert(obj);
		
		// get assign Recipient
		this.getAssignedRecipients(obj);
		
		// get all recipients
		this.getGlobalRecipients();

	 },
	 
	 // hide alert form
	 _hideAlertForm: function() {
		alertFormCanvas.hide();
	 },
	
	_saveAlert: function() {
		// validate alert properties
		var name = this._alertform.getItem("alertName");
		var message = this._alertform.getItem("message");
		var valueCompare = this._alertform.getItem("valueCompare");
		
		if (name.getValue() == null || name.getValue() == '') {
			OPINIATOR.warn("Alert name must be inputed !");
			return;
		}
		
		if (valueCompare.getValue() == null || valueCompare.getValue() == '') {
			OPINIATOR.warn("Value must be inputed !");
			return;
		}
		
		if (valueCompare.getValue() != null && !isc.isAn.Number(parseFloat(valueCompare.getValue()))) {
			OPINIATOR.warn("Value is not valid, please input valid number !");
			return;
		}
		
		if (message.getValue() != null && message.getValue().length > 200) {
			OPINIATOR.warn("Message length can not be greater than 200 characters !");
			return;
		} 
		
		
		var object = this._alertform.getAlert();	
		object.recipients = this._assignRecipients;	
		WebClientSvc.updateAlert("SURVEY_CATEGORY", object, this.callback("saveAlertSuccess"), this.callback("error") );
	},
	
	saveAlertSuccess: function( alertDTO ) {
		// update the list
		var index = this._alerts.findIndex("id", alertDTO.id);
		if (index > -1) {
			this._alerts.removeAt(index);
			this._alerts.addAt(alertDTO, index);
		} else {
			this._alerts.add(alertDTO);
		}
		
		
		// hide new alert area when saving successfully.
		this._hideAlertForm();			
	},
	
	// get existing alert for category
	getAlertForSurveyCategory: function( surveyId, catId ) {
		if (surveyId != null) {
			WebClientSvc.findAlert("SURVEY_CATEGORY", surveyId, catId, this.callback("setAlertForCategory"), this.callback("error"));
		}
	},
	
	setAlertForCategory: function( alerts ) {
		this._alerts = OPINIATOR.toArray(alerts.list);
		this._alertlist.setValue(this._alerts);
	},
	
	// enable edit button
	refreshEditButton: function() {
		var deleteBtn = AlertRemoveID;
		deleteBtn.show();
	},
	
	removeItem: function() {
		var sel = this._alertlist.getSelectedRecord();
		if (sel != null) {
			this._pendingAlert = sel.id;
			OPINIATOR.askOk("Do you want to delete the alert ?", this.callback("deleteAlertReply"));	
		}
		
	},
	
	deleteAlertReply: function( ok ) {
		if ( ok ) {
			WebClientSvc.deleteAlert(this._pendingAlert, this.callback("_deleteAlert"), this.callback("error"));
			delete this._pendingAlert;
		}
	},
	
	_deleteAlert: function( alertId ) {
		var index = this._alerts.findIndex("id", alertId);
		if (index > -1) {
			this._alerts.removeAt(index);
			this._hideAlertForm();		
		}
		
		// hide Remove button when list has no record.
		if (this._alerts.length == 0) {
			AlertRemoveID.hide();
		}		
		
	},
	
	// edit item
	editItem: function() {
		var listgrid = this._alertlist;
		var sel = listgrid.getSelectedRecord();
		this._showAlertForm( sel );
	},
	
	showRecipients: function() {
		this._globalRecipientList.show();
		this._assignRecipientList.show();
		this._updownToolBar.show();
	},
	
	hideRecipients: function() {
		this._globalRecipientList.hide();
		this._assignRecipientList.hide();
		this._updownToolBar.hide();
	},
	
	// 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._assignRecipients;
		for (var i=0 ; i < list.length; i++) {
			var index = this._globalRecipients.findIndex("id", list[i].id);
			if (index > -1) {
				this._globalRecipients.removeAt(index);	
			}
		}
		this._globalRecipientList.setValue(this._globalRecipients);
		alertFormCanvas.show();
	},
	
	// get assigned recipient to alert
	getAssignedRecipients: function( sel ) {
		//var sel = this.getSelectedItem(this._alertlist);
		if (sel.id != null) {			
			WebClientSvc.findRecipient(sel.id, true, null, this.callback("setAssignedRecipientForList"), this.callback("error"));
		} else  {
			//if (!isc.isAn.Array(this._assignRecipients)) {
				this._assignRecipients = [];
				this._assignRecipientList.setValue(this._assignRecipients);
			//}
		}
	},
	
	// callback function when get assigned recipients successfully.
	setAssignedRecipientForList: function( recipients ) {				
		this._assignRecipients = OPINIATOR.toArray(recipients.list);
		this._assignRecipientList.setValue(this._assignRecipients);
	},
	
	// add a recipient in assign Recipient
	addAssignRecipient: function() {
		var item = this.getSelectedItem(this._globalRecipientList);
		
		if (item != null) {
			this._assignRecipients.add(item);
			this._globalRecipients.remove(item);	
		}
	},
	
	// remove assignd recipient
	removeAssignRecipient: function() {
		var item = this.getSelectedItem(this._assignRecipientList);
		
		if (item != null) {
			this._assignRecipients.remove(item);
			this._globalRecipients.add(item);	
		}
	},
	
	getSelectedItem:function( grid ) {
		var sel = grid.getSelectedRecord();
		return sel;
	},
	
	// filter global recipients
	filterRecipients: function() {
		var assign = this._assignRecipients;
		
		if (assign == null) {
			return;
		}
		
		for (var i=0 ; i < assign.length; i++) {
			var index = this._globalRecipients.findIndex("id", assign[i].id);
			if (index > -1) {
				this._globalRecipients.removeAt(index);	
			}
		}
	},
	
	error: function (code, msg)
        {        
        switch ( msg )
            {
                default:
                OPINIATOR.warn(msg);
                break;
            }
        },
	
	callback: function (methodName) { 
		return {target:this, methodName:methodName};
	}    
});
	
