/**
 * @author albert.sole
 */
function UserGroupsEditorForm(config){	
		
	var saveButtonText = getLanguageForElement("saveButtonText", selectedLangId);
	var deleteButtonText = getLanguageForElement("deleteButtonText", selectedLangId);		
	var updateButtonText = getLanguageForElement("updateButtonText", selectedLangId);		
		
	this.config = config;
		
	this.selectedGroup = null;
		
	/**
	 * grid to show all users
	 */
	
	this.showGroupGrid = getShowAllUsersGroups(this.config.groupsQueryURL, 'group', 
		function(e,scope){
			var record = scope.showGroupGrid.getSelectionModel().getSelected();
			var userGroupId = 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
			ajaxSendRequestUserGroupInfo(userGroupId, scope);
		}
	, this);   
	this.showGroupGrid.getStore().load();     				
		
	/*************************************************************
	 ****************** COMPONENTS ITEM PANEL*********************
	 *************************************************************/
	//image and category fields selectors are mandatory
	//combo boxes for selecting the icons
	this.groupNameTextBox = getTextFieldComponent(null,"name",null,375);
																
	this.edit_group_itemsChooser = new GmSoft.components.GroupItemsEditor({
		groupItemsURL: this.config.groupItemsQueryURL
	});																	
	
	//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 groupName = This.scope.groupNameTextBox.getValue();
				var groupItems = This.scope.edit_group_itemsChooser.getXMLSelectedGroupID();

				ajaxSendCreateGroup(groupName, groupItems, 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.selectedGroup;
				var groupName = This.scope.groupNameTextBox.getValue();
				var groupItems = This.scope.edit_group_itemsChooser.getXMLSelectedGroupID();		
				
				ajaxSendUpdateGroup(selectedId, groupName, groupItems, 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.selectedGroup;
					
					ajaxSendDeleteGroup(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.groupNameTextBox.setValue('');
		this.edit_group_itemsChooser.removeAllSelections();
	};
	
	/**
	 * Main panel
	 */
	this.border = new Ext.form.FormPanel({
	    title: "Edit user groups",	
		border:'false',
		bodyStyle: 'padding: 20px 10px 20px 10px; text-align: left;',
	    width: 540,
	    items: [{
			width: 515,
			autoHeight : true,
			bodyBorder: false,
			border: false,		
			bodyStyle:'padding:0px 0px 20px 0px;',
			items: [this.showGroupGrid]		
	    },
			this.groupNameTextBox,
			this.edit_group_itemsChooser ],
		buttons: [this.edit_UsersButtonSave,this.edit_UsersButtonUpdate,this.edit_UsersButtonDelete]
	});
	
	this.border.render(this.config.renderTo);
}

//Create new language
function ajaxSendRequestUserGroupInfo(groupId, thisScope){
	ajaxGenericCall('XmlGMServlet?action_type=user_group_actions&action=get_user_group_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;
							
							mapGroupToForm(result, scope);
							scope.enableUpdateDeleteItemButtons();
						}
					},
					thisScope,
					{
						group_id: groupId
					}
	);
}

//Create new language
function ajaxSendCreateGroup(groupName, groupItems, thisScope){
	ajaxGenericCall('XmlGMServlet?action_type=user_group_actions&action=create_group',
					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.showGroupGrid.getStore().load();     	
							scope.cleanForm();	
						}
					},
					thisScope,
					{
						group_name: groupName,
						group_items: groupItems
					}
	);
}

//Create new language
function ajaxSendDeleteGroup(groupId, thisScope){
	ajaxGenericCall('XmlGMServlet?action_type=user_group_actions&action=delete_group',
					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.showGroupGrid.getStore().load();   
							scope.cleanForm();  		
						}
					},
					thisScope,
					{
						group_id: groupId
					}
	);
}

//Create new language
function ajaxSendUpdateGroup(groupId, groupName, groupItems, thisScope){
	ajaxGenericCall('XmlGMServlet?action_type=user_group_actions&action=update_group',
					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.showGroupGrid.getStore().load();     
							scope.cleanForm();		
						}
					},
					thisScope,
					{
						group_id: groupId,
						group_name: groupName,
						group_items: groupItems
					}
	);
}

/**
 * Function to show data into the userForm 
 * @param {Object} d: XML document containing the following attributes
	<?xml version="1.0" encoding="UTF-8" standalone="no"?>
	<gmsoft_response>
	    <xsl/>
	    <xml>
	        <group>
	            <id>1</id>
	            <name>ANONYMOUS</name>
	            <items>
	                <item>
	                    <id>26</id>
	                    <menu_item>Gm Time 1.0</menu_item>
	                </item>
	                <item>
	                    <id>51</id>
	                    <menu_item>GM Capture 2.0</menu_item>
	                </item>
	            </items>
	        </group>
	    </xml>
	</gmsoft_response>
 */
function mapGroupToForm(doc,scope){
	//read name
	var name = findDirectTextNodeValue(doc.getElementsByTagName('name')[0]);
	if (name != null && name != '') {
		scope.groupNameTextBox.setValue(name);
	}else{
		scope.groupNameTextBox.setValue('');		
	}
	
	//read id
	var selectedGroup = findDirectTextNodeValue(doc.getElementsByTagName('id')[0]);
	if (name != null && name != '') {
		scope.selectedGroup = selectedGroup;
	}else{
		scope.selectedGroup = '-1';		
	}

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

/**
 * This funciton will return a associative array like {ids:[], names: []}
from the following xml:
<items>
    <item>
        <id>26</id>
        <menu_item>Gm Time 1.0</menu_item>
    </item>
    <item>
        <id>51</id>
        <menu_item>GM Capture 2.0</menu_item>
    </item>
</items>
 */
function userGroupItemsToArrays(doc){
	
	var ids = new Array();
	var names = new Array();
	
	var xmlData = doc.getElementsByTagName("item");	
	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};	
}
