/**
 * @author albert.sole
 */
function UsersEditorForm(config){	
		
	var saveButtonText = getLanguageForElement("saveButtonText", selectedLangId);
	var deleteButtonText = getLanguageForElement("deleteButtonText", selectedLangId);		
	var updateButtonText = getLanguageForElement("updateButtonText", selectedLangId);		
		
	this.config = config;
		
	this.selectedUser = null;
		
	/**
	 * grid to show all users
	 */
	
	this.showUsersGrid = getShowAllUsersGrid(this.config.usersQueryURL, 'user', 
		function(e,scope){
			var record = scope.showUsersGrid.getSelectionModel().getSelected();
			var userId = record.get('id');
			
			//we request again the same information that we have because I don't know how
			//to work with xml inside a Ext.store
			ajaxSendRequestUserInfo(userId, scope);
		}
	, this);   
	this.showUsersGrid.getStore().load();     				
		
	/*************************************************************
	 ****************** COMPONENTS ITEM PANEL*********************
	 *************************************************************/
	//image and category fields selectors are mandatory
	//combo boxes for selecting the icons
	this.nameTextBox = getTextFieldComponent(null,"name",null,375);
	this.passwordTextBox = getPasswordFieldComponent(null,"password",null,375);
	this.userCodeTextBox = getTextFieldComponent(null,"user code",null,375);
	this.userEmailTextBox = getEmailFieldComponent(null,"email",null,375);
																
	this.edit_usersGroupsChooser = new GmSoft.components.UserGroupEditor({
		groupsURL: this.config.groupsQueryURL
	});																	
	
	//Add the buttons
	//save button
	this.edit_UsersButtonSave = new Ext.Button(
		{
			text: saveButtonText,
			scope: this,
			minWidth: 100,			
			xtype: 'button',
			handler: function(This,e){
				//check if required field have value
				var userName = This.scope.nameTextBox.getValue();
				var userPassword = This.scope.passwordTextBox.getValue();
				var userGroups = This.scope.edit_usersGroupsChooser.getXMLSelectedGroupID();
				var userEmail = This.scope.userEmailTextBox.getValue();
				var userCode = This.scope.userCodeTextBox.getValue();

				ajaxSendCreateUser(userName, userPassword, userEmail, userCode, userGroups, this);
				
	        }				
		}
	);
	
	//update button
	this.edit_UsersButtonUpdate = new Ext.Button(
		{
			text: updateButtonText,
			xtype: 'button',
			minWidth: 100,		
			disabled: true,	
	        scope: this,			
	        handler: function(This,e){
				var selectedId = This.scope.selectedUser;	
				var userName = This.scope.nameTextBox.getValue();
				var userPassword = This.scope.passwordTextBox.getValue();
				var userGroups = This.scope.edit_usersGroupsChooser.getXMLSelectedGroupID();		
				var userEmail = This.scope.userEmailTextBox.getValue();
				var userCode = This.scope.userCodeTextBox.getValue();				
				
				
				ajaxSendUpdateUser(selectedId, userName, userPassword, userEmail, userCode, userGroups, this);	
	        }			
		}		
	);	

	//delete button
	this.edit_UsersButtonDelete = new Ext.Button({
			text: deleteButtonText,
			xtype: 'button',
			disabled: true,
			minWidth: 100,
	        scope: this,
	        handler: function(This, e){
					var selectedId = This.scope.selectedUser;
					
					ajaxSendDeleteUser(selectedId,this);
	        }	
	});
		
	//functions to enable and disable buttons
	this.enableUpdateDeleteItemButtons = function(){
		this.edit_UsersButtonUpdate.enable();
		this.edit_UsersButtonDelete.enable();	
	};
	
	this.disableUpdateDeleteItemButtons = function(){
		this.edit_UsersButtonUpdate.disable();
		this.edit_UsersButtonDelete.disable();
	};
	/*************************************************************
	 ********************* END ITEM PANEL*************************
	 *************************************************************/	
	
	this.cleanForm = function(){
		this.nameTextBox.setValue('');
		this.passwordTextBox.setValue('');
		this.userCodeTextBox.setValue('');
		this.userEmailTextBox.setValue('');
		this.edit_usersGroupsChooser.removeAllSelections();
	};
	
	/**
	 * Main panel
	 */
	this.border = new Ext.form.FormPanel({
	    title: "Edit users",	
		border:'false',
		bodyStyle: 'padding: 20px 10px 20px 10px; text-align: left;',
	    width: 520,
	    items: [{
			width: 515,
			autoHeight : true,
			bodyBorder: false,
			border: false,		
			bodyStyle:'padding:0px 0px 20px 0px;',
			items: [this.showUsersGrid]		
	    },
			this.nameTextBox,
			this.passwordTextBox,
			this.userCodeTextBox,
			this.userEmailTextBox,
			this.edit_usersGroupsChooser ],
		buttons: [this.edit_UsersButtonSave,this.edit_UsersButtonUpdate,this.edit_UsersButtonDelete]
	});
	
	this.border.render(this.config.renderTo);
}

//Create new language
function ajaxSendRequestUserInfo(userId, thisScope){
	ajaxGenericCall('XmlGMServlet?action_type=user_group_actions&action=get_user_info',
					function(conn, response, options){
						var failure = lookForXMLFailureResponse(conn.responseXML);
						if (failure != null) { //in case there was an error show it
							showErrorDialog('ERROR!!', failure);
						}else {
							var scope = response.scope;
							var result = conn.responseXML;
							
							mapUserToForm(result, scope);
							scope.enableUpdateDeleteItemButtons();
						}
					},
					thisScope,
					{
						user_id: userId
					}
	);
}

//Create new language
function ajaxSendCreateUser(userName, userPassword, userEmail, userCode, userGroups, thisScope){
	ajaxGenericCall('XmlGMServlet?action_type=user_group_actions&action=create_user',
					function(conn, response, options){
						var failure = lookForXMLFailureResponse(conn.responseXML);
						if (failure != null) { //in case there was an error show it
							showErrorDialog('ERROR!!', failure);
						}else {
							var scope = response.scope;
							var result = getResponseText(conn.responseXML);
							showInfoDialog('INFO', result);								

							scope.disableUpdateDeleteItemButtons();
							scope.showUsersGrid.getStore().load();     	
							scope.cleanForm();	
						}
					},
					thisScope,
					{
						user_name: userName,
						password: userPassword,
						email: userEmail,
						user_code: userCode,
						groups: userGroups
					}
	);
}

//Create new language
function ajaxSendDeleteUser(userId, thisScope){
	ajaxGenericCall('XmlGMServlet?action_type=user_group_actions&action=delete_user',
					function(conn, response, options){
						var failure = lookForXMLFailureResponse(conn.responseXML);
						if (failure != null) { //in case there was an error show it
							showErrorDialog('ERROR!!', failure);
						}else {
							var scope = response.scope;
							var result = getResponseText(conn.responseXML);
							showInfoDialog('INFO', result);								

							scope.disableUpdateDeleteItemButtons();
							scope.showUsersGrid.getStore().load();   
							scope.cleanForm();  		
						}
					},
					thisScope,
					{
						user_id: userId
					}
	);
}

//Create new language
function ajaxSendUpdateUser(userId, userName, userPassword, userEmail, userCode, userGroups, thisScope){
	ajaxGenericCall('XmlGMServlet?action_type=user_group_actions&action=update_user',
					function(conn, response, options){
						var failure = lookForXMLFailureResponse(conn.responseXML);
						if (failure != null) { //in case there was an error show it
							showErrorDialog('ERROR!!', failure);
						}else {
							var scope = response.scope;
							var result = getResponseText(conn.responseXML);
							showInfoDialog('INFO', result);								

							scope.disableUpdateDeleteItemButtons();
							scope.showUsersGrid.getStore().load();     
							scope.cleanForm();		
						}
					},
					thisScope,
					{
						user_id: userId,
						user_name: userName,
						password: userPassword,
						email: userEmail,
						user_code: userCode,						
						groups: userGroups
					}
	);
}

/**
 * Function to show data into the userForm 
 * @param {Object} d: XML document containing the following attributes
	<gmsoft_response>
	    <xsl/>
	    <xml>
	        <user>
	            <id>1</id>
	            <name>albert</name>
	            <email>1@2.com</email>
	            <code>12345</code>
	            <groups>
	                <group>
	                    <id>1</id>
	                    <name>ANONYMOUS</name>
	                </group>
	                <group>
	                    <id>2</id>
	                    <name>ADMIN</name>
	                </group>
	            </groups>
	        </user>
	    </xml>
	</gmsoft_response>
 */
function mapUserToForm(doc,scope){
	//read name
	var name = findDirectTextNodeValue(doc.getElementsByTagName('name')[0]);
	if (name != null && name != '') {
		scope.nameTextBox.setValue(name);
	}else{
		scope.nameTextBox.setValue('');		
	}
	
	//read id
	var selectedUser = findDirectTextNodeValue(doc.getElementsByTagName('id')[0]);
	if (selectedUser != null && selectedUser != '') {
		scope.selectedUser = selectedUser;
	}else{
		scope.selectedUser = '-1';		
	}
	
	//read email
	var userEmail = findDirectTextNodeValue(doc.getElementsByTagName('email')[0]);
	if (userEmail != null && userEmail != '') {
		scope.userEmailTextBox.setValue(userEmail);
	}else{
		scope.userEmailTextBox.setValue('');
	}
	
	//read userCode
	var userCode = findDirectTextNodeValue(doc.getElementsByTagName('code')[0]);
	if (userCode != null && userCode != '') {
		scope.userCodeTextBox.setValue(userCode);
	}else{
		scope.userCodeTextBox.setValue('');
	}

	//get the groups in array from 
	var groups = userGroupsToArrays(doc);
	
	//update the groups into the gui component
	scope.edit_usersGroupsChooser.setGroupsRecords(groups['ids'],groups['names']);
}

/**
 * This funciton will return a associative array like {ids:[], names: []}
from the following xml:
<groups>
    <group>
        <id>1</id>
        <name>ANONYMOUS</name>
    </group>
    <group>
        <id>2</id>
        <name>ADMIN</name>
    </group>
</groups>
 */
function userGroupsToArrays(doc){
	
	var ids = new Array();
	var names = new Array();
	
	var xmlData = doc.getElementsByTagName("group");	
	for (i = 0; i < xmlData.length; i++) {
		var node = xmlData[i];
		var id = findDirectTextNodeInsideTagValue(node,'id');
		var name = findDirectTextNodeInsideTagValue(node,'name');
		
		ids[i] = id;
		names[i] = name;
	}

	return {ids: ids, names: names};	
}

