/**
 * @author duy.chung
 */

isc.defineClass("OPINIATOR_RecipientForm", isc.DynamicForm);
OPINIATOR_RecipientForm.addProperties({
    // Constructor Properties 
    //parentEditor: null,

    // Superclass Properties
    showBusy:OPINIATOR_ShowBusy,
    destroyBusy:OPINIATOR_DestroyBusy,

    // Superclass Properties
    width:"100%",
    height:"100%",
    minColWidth:10,
    cellPadding:2,
    numCols:2,
    fixedColWidths:false,
    titleWidths:80,
    cellBorder:0,
    showResizeBar:false,
    layoutAlign:"left",
    itemHoverDelay:3000,
    selectOnFocus:true,

	_recipient: null,

    items:[
        {type:"rowSpacer", height:18},               
        
		{
			name:"recipientName",
			title: "Name",
			titleAlign:"left",
	        align:"left",
			tabIndex:1,
	        startRow:true,
	        wrapTitle:false,
			type:"text",
			width: 230,
			height: 25,
			_constructor:"OPINIATOR_TextItem"
		},
		
		{
			name:"phoneNumber",
			title: "Phone Number",
			titleAlign:"left",
	        align:"left",
			tabIndex:4,
	        startRow:true,
	        wrapTitle:false,
			type:"text",
			width: 230,
			height: 25,
			_constructor:"OPINIATOR_TextItem"
		},
		
		{
			name:"email",
			title: "Email",
			titleAlign:"left",
	        align:"left",
			tabIndex:4,
	        startRow:true,
	        wrapTitle:false,
			type:"text",
			width: 230,
			height: 25,
			_constructor:"OPINIATOR_TextItem"
		}
		
    ],

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

	itemChange: function (item, newValue, oldValue) {
		var iname = item.getFieldName();
		switch ( iname ) {
			case "recipientName":
				this._recipient.name = newValue;
				break;
			case "phoneNumber":
				this._recipient.phoneNumber = newValue;
				break;
			case "email":
				this._recipient.email = newValue;
				break;
			default:
				break;
		}
	},
	
	updateFields: function( recipient ) {
		
		// load attributes of recipient if it exists.
		var obj = recipient;
		if (obj != null) {
			var name = this.getItem("recipientName");
			var phone = this.getItem("phoneNumber");
			var email = this.getItem("email");
			
			// set value
			name.setValue(obj.name);
			phone.setValue(obj.phoneNumber);
			email.setValue(obj.email);
		}		
	},

	destroy: function () {               
		delete this._recipient;
        this.Super("destroy", arguments);
    },
	
	getRecipient: function() {
		return this._recipient;
	},
	
	setRecipient: function( recipient ) {
		this._recipient = recipient;
		this.updateFields(recipient);
	}
});

isc.defineClass("OPINIATOR_RecipientList", isc.ListGrid);
OPINIATOR_RecipientList.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,

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

    destroy: function ()
        { 
        this.Super("destroy", arguments); 
        },
		
	setValue: function( recipients ) {
		recipients = OPINIATOR.toArray(recipients);		
		recipients.sortByProperty("name", true);
		this.setData(recipients);
	}
	
});

isc.defineClass("OPINIATOR_RecipientDesigner", isc.HLayout);
OPINIATOR_RecipientDesigner.addProperties({
	
	recipientList: null,
	
	recipientForm: null,
	
	toolbar: null,
	
	recipientFormToolBar: null,
	
	_recipients: null,
	
	orgUnitId: null,
	
	initWidget: function() {
		
		this.toolbar = OPINIATOR_ButtonBar.create({
            align:"left",
            layoutAlign:"center",
            canFocus:false,
            defaultWidth:80,
            height:30,
            width:"100%",

            target:this,
            buttons: [
                {
	                ID: "RecipientAddID",
	                title: "Add",
	                visibility:"visible",
	                tabIndex:1,
	                icon: "icons/16/category.png",
	                click: function () {
						this.target.showRecipientForm();
						return true;
					}
                },
                {
	                ID: "RecipientRemoveID",
	                title: "Remove",
	                visibility:"hidden",
	                tabIndex:2,
	                icon: "icons/16/delete.png",
	                width:110,
	                click: function () {
						this.target.removeItem(); 
						return true;
					}
                }
				
				]
            });
		
		this.recipientFormToolBar = OPINIATOR_ButtonBar.create({
            align:"right",
            layoutAlign:"center",
            canFocus:false,
            defaultWidth:80,
            height:30,
            width:280,
            target:this,
            buttons: [
                {
	                ID: "recipientCancel",
	                title: "Cancel",
	                visibility:"visible",
	                tabIndex:1,
	                icon: "icons/16/cancel.png",
	                click: function () {
						this.target.hideRecipientForm();
						return true;
					}
                },
				
                {
	                ID: "recipientSave",
	                title: "Save",
	                visibility:"visible",
	                tabIndex:2,
	                icon: "icons/16/save.png",
	                width:110,
	                click: function () { 
						this.target.saveRecipient();
						return true; 
					}
                }
				
				]
            });
		
		this.recipientList = OPINIATOR_RecipientList.create({
			ID: "RecicipientList",
			_title: "Recipients",
			target:this,			
			fields: [
	            {
					target: this,
		            name:"name", 	  
					title: "Recipients",
		            align:"center", 
		            width:"*",
		            editorType:"OPINIATOR_TextItem",
		            cellAlign:"left"
	            }			
        	],
			cellClick: function() {
				this.target.showRemoveButton();
				this.target.editItem();
				return true;
			}
		});
		
		this.recipientForm = OPINIATOR_RecipientForm.create({
			ID: "RecipientForm"			
		});
		
		this.members = [OPINIATOR.hSpacer(50), 
						isc.VLayout.create({
							width: 200, 
							height: 400,
							align: "left",
							members:[this.recipientList, OPINIATOR.vSpacer(5), this.toolbar]}
						),
						OPINIATOR.hSpacer(20),
						isc.VLayout.create({
							ID: "recipientFormCanvas",
							members:[this.recipientForm, OPINIATOR.vSpacer(5), this.recipientFormToolBar],	
							visibility: "hidden",	
							height: 150,
							width: 400
						}),
                        OPINIATOR.hSpacer("20%")];
		
		// call superclass implementation
        this.Super("initWidget", arguments);
		
		// get existing recipients 
		this.getExistingRecipients();
	},
	
	saveRecipient: function() {
		// validate Recipient
		var form = this.recipientForm;
		var name = form.getValue("recipientName");
		var phone = form.getValue("phoneNumber");
		var email = form.getValue("email");
		
		if (!isc.isA.nonemptyString(name)) {
			OPINIATOR.warn("Recipient's name must be input!");
			return;
		}
		
		if (name != null &&  name.length > 20) {
			OPINIATOR.warn("Recipient's name must be less than 20 characters!");
			return;
		}
		
		// at least enter email or sms number
		if ( (phone == null && email == null) ||
			((phone != null && phone.length == 0) && (email != null && email.length == 0))) {
			OPINIATOR.warn("You must enter at least phone number or email !");	
			return;		
		}
		
		if ( email != null && email.length > 0 && !(email.contains("@") && email.contains("."))) {
             OPINIATOR.warn("Invalid email address");
             return;
		}
		
		var object = this.recipientForm.getRecipient();		
		object.orgId = this.orgUnitId;
		WebClientSvc.updateRecipient(object, this.callback("saveRecipientSuccess"), this.callback("error"));
	},
	
	saveRecipientSuccess: function( object ) {
		// update the list
		var index = this._recipients.findIndex("id", object.id);
		if (index > -1) {
			this._recipients.removeAt(index);
			this._recipients.addAt(object, index);
		} else {
			this._recipients.add(object);
		}
		
		// sort recipients
		this._recipients.sortByProperty("name", true);
		
		this.hideRecipientForm();
	},
	
	// Show input form
	showRecipientForm: function( recipient ) {
		if (recipient == null) {
			recipient = {
				name: null,
				phoneNumber: null,
				email: null,
				orgId: null
			};
		}
		this.recipientForm.setRecipient(recipient);
		recipientFormCanvas.show();
	},
	
	// hide input form
	hideRecipientForm: function() {
		recipientFormCanvas.hide();
	},
	
	destroy: function() {
        this.Super("destroy", arguments);
    },
	
	getExistingRecipients: function() {
		WebClientSvc.findRecipient(null, false, this.orgUnitId, this.callback("setRecipientForList"), this.callback("error"));
	},
	
	setRecipientForList: function( recipients ) {
		this._recipients = OPINIATOR.toArray(recipients.list);
		this.recipientList.setValue(this._recipients);
	},
	
	// show remove button
	showRemoveButton: function() {
		var remove = RecipientRemoveID;
		remove.show();
	},
	
	// edit item
	editItem: function() {
		var listgrid = this.recipientList;
		var sel = listgrid.getSelectedRecord();
		this.showRecipientForm( sel );
	},
	
	removeItem: function() {
		var sel = this.recipientList.getSelectedRecord();
		if (sel != null) {
			this._pendingRecipient = sel.id;
			OPINIATOR.askOk("Do you want to delete the recipient ?", this.callback("deleteRecipientReply"));	
		}
	},
	
	deleteRecipientReply: function( ok ) {
		if (ok) {
			WebClientSvc.deleteRecipient(this._pendingRecipient, this.callback("_deleteRecipient"), this.callback("error"));
			delete this._pendingRecipient;
		}
	},
	
	_deleteRecipient: function( recipientId ) {
		var index = this._recipients.findIndex("id", recipientId);
		if (index > -1) {
			this._recipients.removeAt(index);
			this.hideRecipientForm();		
		}
		
		// hide Remove button when list has no record.
		if (this._recipients.length == 0) {
			RecipientRemoveID.hide();
		}		
	},
	
	error: function (code, msg)
        {        
        switch ( msg )
            {
                default:
                OPINIATOR.warn(msg);
                break;
            }
        },
	
	callback: function (methodName) { 
		return {target:this, methodName:methodName};
	}    
	
});
