/**
 * @author albert.sole
 * This file provides basic components
 */
/**
 * This function returns a combo box that automatically queries the info from the parameter url
 * @param {Object} comboId: id to set to the comboBox 
 * @param {Object} label: labelToDisplay
 * @param {Object} mappingElement: element that will be shown into the combobox
 * @param {Object} displayField: tag that embeds the mappingElement
 * @param {Object} queryURL: url to request the XML file
 */

function getComboSelector(comboId, label, queryField, mappingElement, queryURL, functionToExecOnSelection,scope){
	
	this.label = label;  
	
	this.selectedRecord = null;
	
	this.mappingElement = mappingElement;
	
	//Create the factory to retrive elements form the server
	//create a store for the combobox
	this.fileRecord = new Ext.data.Record.create([
			{name: mappingElement, mapping: mappingElement, type:'string'},
			{name: 'id', mapping: 'id', type:'string'}
	]);
	
	if(!Ext.isEmpty(queryURL,false)){
		this.proxy = new Ext.data.HttpProxy({url: queryURL});
	    // create the Data Store
	    this.store = new Ext.data.Store({
	        // load using HTTP
	        proxy: this.proxy,
	        // the return will be XML, so lets set up a reader
	        reader: new Ext.data.XmlReader({
	               // records will have a "category" tag
	               record: queryField
	           }, this.fileRecord)
	    });			
	}else{
	    // create the Data Store
	    this.store = new Ext.data.Store({});			
	}
		
	//overwrite the beforload to load the language parameter	
	this.store.addListener('beforeload', function(This,options) {
		this.store.baseParams.lang = selectedLangId;
	},this);
	
	//add some listeners in case of error.
	this.store.addListener('loadexception',function(This,records,options){		
        Ext.Msg.show({
            title:'Load data error',
            msg:'Could not load from: ' + queryURL ,
            buttons: Ext.Msg.OK,
            icon: Ext.MessageBox.INFO
        });		
	});		
	//select a default value when everything is loaded	
	this.store.addListener('load', function(records, options){
		//select default value
		var firstValue = this.store.getAt(0);
		if(firstValue == null){
			this.getCombo().setValue('Empy...');
		}else{
			this.getCombo().setValue(firstValue.get(mappingElement));
		}		
	},this);	
	
	this.combo = new Ext.form.ComboBox(
		{
			id: comboId,                
			fieldLabel: label,
			xtype:'combo',
			store: this.store,
			displayField:mappingElement,
			//listWidth: 'auto', //this does not work in ie6
			listWidth: '280', //this does not work in ie6			
			resizable:true,
			width: 250,
			mode: 'remote',				
			lazyinit:'false',
			triggerAction: 'all',
			//emptyText:'Select...',			
			forceSelection : true, //no user text allowed
			selectOnFocus:true,
			listeners: 
		      { select: functionToExecOnSelection },					
		    allowBlank:false,
			scope: scope
		}			
	);
	
	//save the record each time is selected	
	this.combo.addListener('select', function(combo, record, index){
		//keep the selected value
		this.selectedRecord = record;
	},this);
	
	//functions getters and setters
	this.getCombo = function(){
		return this.combo;
	}	
	
	this.getValue = function(){
		return this.combo.getValue();
	}
	
	this.getName = function(){
		return this.label;
	}	
	
	//refresh the combo box, and select the first item
	//when done
	if (!Ext.isEmpty(queryURL, false)) {
		this.refresh = function(){
			this.store.load();
			this.getCombo().render();
		}
	}else{
		this.refresh = function(){
		}		
	}
	
	this.getValue = function(){
		return this.selectedRecord;
	}
	
	this.setValue = function(value){
		this.getCombo().setValue(value);
		this.getCombo().render();
	}	
	
	this.setComboValue = function(value){
		this.getCombo().setValue(value);
		this.getCombo().render();
	}
}

function FieldSetWithFields(langID,fieldSetName,fields,fieldType){
	
	var staticHTMLURL = 'XmlGMServlet?action_type=get_info&action=get_static_html';
	
	//keep the language id and define getter
	this.languageID = langID;
	this.getLanguageID =  function(){
		return this.languageID;
	}
	
	this.fieldSet = new Ext.form.FieldSet({
	    xtype:'fieldset',
	    title: fieldSetName,
	    collapsible: true,
	    collapsed: true,
		autoHeight:true		
	});
	
	this.fields = new Array(fields.length);
	
	//one field value in the variable
	for(i=0 ; i<fields.length ; i++){
		//create the required component
		var field = null	
		if(fieldType[i]=='textarea')	
			field = getTextAreaComponent(this.fieldSet.getId() + '_' + fieldSetName + "_" + fields[i],fields[i],fields[i],300);
		else if(fieldType[i]=='textfield')
			field = getTextFieldComponent(this.fieldSet.getId() + '_' + fieldSetName + "_" + fields[i],fields[i],fields[i],300);
		else if(fieldType[i]=='field_destination_combo'){
			field = new GmSoft.components.ComboSelector(
												{
											  		label: fields[i],
											  		queryField: 'file',
											  		mappingElement: 'url',
											  		queryURL: staticHTMLURL,
											  		functionToExecOnSelection: Ext.emptyFn,
											  		scope: this 
												});	
		}
		//keep the component
		this.fields[i]=field;
		//add the component to the main frame
		this.fieldSet.add(field);
	}
		
	this.getFieldSet = function(){return this.fieldSet};
	
	this.getXMLFieldValues = function(){
		var xml = '<lang_fields id =\'' + this.languageID + '\'>';		
				
		//one field value in the variable
		var i = 0;
		for(i=0 ; i<this.fields.length ; i++){		
		    var field = this.fields[i];
			var name = field.getName();
			var value = field.getValue(true);
			//xml = xml + '<' + name + '>' + value + '</' + name + '>';
			xml = xml + '<' + name + '>' + '<![CDATA[' + value + ']]>' + '</' + name + '>';
		}		
		
		xml = xml + '</lang_fields>';
		return xml;
	};

	this.setXMLFieldValues = function(xmlDoc){
		//one field value in the variable
		var i = 0;
		for(i=0 ; i<this.fields.length ; i++){		
			var fieldName = this.fields[i].getName();
			var element = xmlDoc.getElementsByTagName(fieldName)[0].firstChild;
			
			if(element == null) element = "";
			
			//check if element has value otherwise we don't assign value
			var fields = element.nodeValue;		
			this.fields[i].setValue(fields);				
		}
	}
	
	this.clearFields = function(){
		//one field value in the variable
		var i = 0;
		for(i=0 ; i<this.fields.length ; i++){		
			this.fields[i].setValue("");
		}		
	}
}

function getTextFieldComponent(id,label,name,width){
	if(width == null){
		width = 350;
	}	
	return new Ext.form.TextField({
	        width: width,
			enableKeyEvents: true,
	        id: id,
			bodyStyle: 'vertical-align:middle',
	        fieldLabel: label,
	        name: name
	    });	
}

function getPasswordFieldComponent(id,label,name,width){
	if(width == null){
		width = 350;
	}	
	return new Ext.form.TextField({
	        width: width,
			enableKeyEvents: true,
	        id: id,
			inputType: "password",
			bodyStyle: 'vertical-align:middle',
	        fieldLabel: label,
	        name: name
	    });	
}

function getEmailFieldComponent(id,label,name,width){
	if(width == null){
		width = 350;
	}	
	return new Ext.form.TextField({
	        width: width,
			enableKeyEvents: true,
	        id: id,
			bodyStyle: 'vertical-align:middle',
	        fieldLabel: label,
			//vtype: 
			//vtypeText: "No valid"
	        name: name
	    });	
}

function getNumberFieldComponent(id,label,name,width){
	if(width == null){
		width = 350;
	}
	return new Ext.form.NumberField({
	        width: width,
	        id: id,
	        fieldLabel: label,
	        name: name
	    });	
}

function getTextAreaComponent(id,label,name,width){
	if(width == null){
		width = 350;
	}	
	return new Ext.form.TextArea({
	        width: width,
			height: 200,
	        id: id,
	        fieldLabel: label,
	        name: name
	    });	
}

// Using encapsulation (as opposed to inheritance/extend) in Ext.
// Based on Animal's code posted at http://extjs.com/forum/showthread.php?t=18478
/**
 * Component to choose a image file from the server
 * properties:
 * 		- String imageID : id of the combo
 * 		- Ext.BoxComponent iconImageBox : box where the selected image will be displayed
 *		- getComboSelector edit_menu_itemsImageCombo: image combo from the specified class
 *		- associative array initialConfig: configuration of the object. 
 */		 
Ext.namespace('GmSoft.components');
// DeskIcon constructor
GmSoft.components.ImageSelector = function(config) {
 
 	var mainPageEditorEditorImageText = getLanguageForElement("mainPageEditorEditorImageText", selectedLangId);
 
 	this.imageID = config.comboID + 'image';
 
 	this.selectImage = function(imageURL){
		(Ext.getDom(this.imageID)).src = imageURL;
		this.edit_menu_itemsImageCombo.setComboValue(imageURL);
	}
 
     this.iconImageBox = new Ext.BoxComponent({
        xtype: 'box',
        width: 25,
        heigh: 25,
		border: true,
        autoEl: {
            tag: 'img',
            align: 'middle',			
            id: this.imageID,
            src: config.defaultImage
        }
    });	
	
	this.edit_menu_itemsImageCombo = new getComboSelector(	config.comboID,
																	mainPageEditorEditorImageText,
																	'file',
																	'url',																	
																	config.iconsURL,
																	function(combo, value, index){
																		//first get the id and change image
																		var url = value.get('url');
																		var domElem = Ext.getDom(combo.scope.imageID); 
																		url = replaceAll(url, "\\", "/");
																		domElem.src = url;
																	},this);	
																	
	this.elementWidth = 400;
	if(config.comboWidth){
		this.edit_menu_itemsImageCombo.getCombo().setWidth(config.comboWidth);
		this.elementWidth = 150 + config.comboWidth;
	}
	
	this.getCombo = function(){
		return this.edit_menu_itemsImageCombo.getCombo();
	}																	
 
    // Create a config object that will be passed to the Panel constructor.
    // The use of Ext.apply preserves the properties passed in the config object
    this.initialConfig = Ext.apply(config, {
        border: false,
        width: this.elementWidth + 50,
        layout: 'column',		
        items: [{					
            border: false,
			width: this.elementWidth,
			bodyStyle:'padding:4px 0px 0px 0px',			
            items: [{
	            layout: 'form',			
	            border: false,
	            items: [this.edit_menu_itemsImageCombo.getCombo()]			
			}]					
		},{			
            border: false,
			bodyStyle:'padding:4px 0px 0px 0px',				
            items: [{
	            layout: 'form',			
	            border: false,
	            items: [this.iconImageBox]			
			}]				
		}]
    });
 
    // Create a Panel instance and bind it to this DeskIcon instance
    this.panel = new Ext.Panel(this.initialConfig);
}; 
// The DeskIcon prototype defines all the methods shared by the DeskIcon instances
GmSoft.components.ImageSelector.prototype = {
    myApplicationSpecificFunction: function(p1, p2, p3) {
        // Perform application-specific processing
    },
 
    // Make this class usable by a Container, so that we can add and remove it.
    // Create delegates in the scope of our contained Panel which reference Panel's methods
    render: Ext.Panel.prototype.render.createDelegate(this.panel),
    destroy: Ext.Panel.prototype.destroy.createDelegate(this.panel),
	fireEvent: Ext.Panel.prototype.destroy.createDelegate(this.panel)
};

/**
 * Component to choose a categories 
 */		 
GmSoft.components.CategoryEditor = function(config) {
	
	var mainPageEditorEditorImageText = getLanguageForElement("mainPageEditorEditorImageText", selectedLangId);
	var removeButtonText = getLanguageForElement("removeButtonText", selectedLangId);
	var addButtonText = getLanguageForElement("addButtonText", selectedLangId);
	var editCategoriesLabelText = getLanguageForElement("editCategoriesLabelText", selectedLangId);
	var quickLinkChooserColumnName = getLanguageForElement("quickLinkChooserColumnName", selectedLangId);
	
 
 	this.allowedCategories = config.allowedCategories;
 
 
     this.iconImageBox = new Ext.BoxComponent({
        xtype: 'box',
        id: 'selected_image_box',
        width: 25,
        heigh: 25,
        autoEl: {
            tag: 'img',
            align: 'middle',
            id: this.imageID,
            src: ''
        }
    });
	
	this.edit_menu_itemsCategoryCombo = new getComboSelector(		config.comboID,
																	editCategoriesLabelText,
																	'category',
																	'name',																	
																	config.categoryURL,
																	Ext.emptyFn);
	this.edit_menu_itemsCategoryCombo.getCombo().setWidth(120);


	/**
	 * If noclean is true, the elements from the list will not be deleted
	 * @param {Object} noclean
	 */
	this.reload = function(noclean){
		if(!noclean) this.store.removeAll();
		this.edit_menu_itemsCategoryCombo.refresh();
	}

    //the grid panel to show all/select one news names
	this.categoryRecord = Ext.data.Record.create([
		{name: 'id', type: 'string'},
		{name: 'name', type: 'string'}
	]);
	
    // create the Data Store
    this.store = new Ext.data.Store({        
        reader: new Ext.data.DataReader(null, this.categoryRecord)
    });
							
												
    this.dataGrid = new Ext.grid.GridPanel({
		store: this.store,
        columns: [{
            id: 'Name',
            header: quickLinkChooserColumnName,
            dataIndex: 'name',
            sortable: true
        }],
	    border: false,		
        width: '100%',
		autoHeight : true,
		sm: new Ext.grid.RowSelectionModel({singleSelect:true})
    });								

	this.addCategoryButton = new Ext.Button(
		{
			text: addButtonText,
			scope: this,	
	        handler: function(This,e){				
				var totalCount = This.scope.store.getCount();
				var allowedCategories = This.scope.allowedCategories;				
				if(totalCount < allowedCategories){
					//get the record
					var selection = This.scope.edit_menu_itemsCategoryCombo.getValue();					
					This.scope.store.add(selection);
				}
	        }			
		}
	);
	
 	this.removeCategoryButton = new Ext.Button(
		{
			text: removeButtonText,
			scope: this,	
	        handler: function(This,e){
				//remove the item
				This.scope.store.remove(This.scope.dataGrid.getSelectionModel().getSelected());
	        }			
		}		
	);
 
 	this.setComboLabel = new function(label){
		//this.edit_menu_itemsCategoryCombo.getCombo()		
	}
 
    // Create a config object that will be passed to the Panel constructor.
    // The use of Ext.apply preserves the properties passed in the config object
    this.initialConfig = Ext.apply(config, {
        border: false,
        width: 465,
        layout: 'column',	
		bodyStyle:'padding:4px 0px 10px 0px',
        border: false,
        items: [
			{					
	            border: false,
				width: 266,
	            items: [{
		            layout: 'form',			
		            border: false,
		            items: [this.edit_menu_itemsCategoryCombo.getCombo()]			
				}]					
			},{
	            border: false,				
				width: 50,
	            items: [{
		            layout: 'form',			
		            border: false,
					bodyStyle:'padding:0px 6px 0px 6px',					
		            items: [this.addCategoryButton]			
				}]				
			},{			
	            border: false,
				width: 95,
	            items: [{
		            layout: 'form',			
		            border: false,
		            items: [this.dataGrid]			
				}]				
			},{
	            border: false,
				width: 50,
	            items: [{
		            layout: 'form',			
		            border: false,
					bodyStyle:'padding:0px 6px 0px 8px',						
		            items: [this.removeCategoryButton]			
				}]				
			}
		]
    });
	
	this.getSelectedCategoriesID = function(){
		var result = new Array(this.store.getCount());
		
		//get all the ids and put them into an array
		var i = 0;
		for(i = 0 ; i<this.store.getCount() ; i++){
			var element = this.store.getAt(i)
			result[i] = this.store.getAt(i).get('id');
		}
		
		return result;
	}
	
	this.getXMLSelectedCategoriesID = function(){
		var result = '<categories>'
		
		//get all the ids and put them into an array
		var i = 0;
		for(i = 0 ; i<this.store.getCount() ; i++){
			result = result + '<category id=\'' + this.store.getAt(i).get('id') + '\'\/>';
		}		
		
		result = result + '</categories>';
		return result;
	}
 
 	this.setCategoryRecords = function(ids,names){
		var i = 0;
		
		//remove all elements	
		this.store.removeAll();
						
		if (ids.length == names.length) {
			for (i = 0; i < ids.length; i++) {
				var record = new this.categoryRecord({
					id: ids[i],
					name: names[i]					
				});
				
				this.store.add([record]);
			}
		}
	}
 
    // Create a Panel instance and bind it to this DeskIcon instance
    this.panel = new Ext.Panel(this.initialConfig);
}; 
// The DeskIcon prototype defines all the methods shared by the DeskIcon instances
GmSoft.components.CategoryEditor.prototype = {
    myApplicationSpecificFunction: function(p1, p2, p3) {
        // Perform application-specific processing
    },
 
    // Make this class usable by a Container, so that we can add and remove it.
    // Create delegates in the scope of our contained Panel which reference Panel's methods
    render: Ext.Panel.prototype.render.createDelegate(this.panel),
    destroy: Ext.Panel.prototype.destroy.createDelegate(this.panel)
};

/**
 * Component to choose a image file from the server
 * properties:
 * 		- String imageID : id of the combo
 * 		- Ext.BoxComponent iconImageBox : box where the selected image will be displayed
 *		- getComboSelector edit_menu_itemsImageCombo: image combo from the specified class
 *		- associative array initialConfig: configuration of the object. 
 */		 
GmSoft.components.QuickLinkChooser = function(config) {
	
	var quickLinkLabelText = getLanguageForElement("quickLinkLabelText", selectedLangId);
	var addButtonText = getLanguageForElement("addButtonText", selectedLangId);
	var removeButtonText = getLanguageForElement("removeButtonText", selectedLangId);
 	var quickLinkChooserColumnName = getLanguageForElement("quickLinkChooserColumnName", selectedLangId);
 
 
 	this.allowedQuickLinks = config.allowedQuickLinks;
 
 
     this.iconImageBox = new Ext.BoxComponent({
        xtype: 'box',
        id: 'selected_image_box',
        width: 25,
        heigh: 25,
        autoEl: {
            tag: 'img',
            align: 'middle',
            id: this.imageID,
            src: ''
        }
    });
	
	this.edit_menu_itemsQuickLinkCombo = new getComboSelector(		config.comboID,
																	quickLinkLabelText,
																	'item',
																	'name',																	
																	config.categoryURL,
																	Ext.emptyFn);

	this.edit_menu_itemsQuickLinkCombo.getCombo().setWidth(120);

	this.reload = function(){
		this.store.removeAll();
		this.edit_menu_itemsQuickLinkCombo.refresh();
	}

    //the grid panel to show all/select one news names
	this.categoryRecord = Ext.data.Record.create([
		{name: 'id', type: 'string'},
		{name: 'name', type: 'string'}
	]);
	
    // create the Data Store
    this.store = new Ext.data.Store({        
        reader: new Ext.data.DataReader(null, this.categoryRecord)
    });
							
												
    this.dataGrid = new Ext.grid.GridPanel({
		store: this.store,
        columns: [{
			width: '124',
            id: 'Name',
            header: quickLinkChooserColumnName,
            dataIndex: 'name',
            sortable: true
        }],
	    border: false,		
        width: '100%',
		autoHeight : true,
		sm: new Ext.grid.RowSelectionModel({singleSelect:true})
    });								

	this.addQuickLinkButton = new Ext.Button(
		{
			text: addButtonText,
			scope: this,	
	        handler: function(This,e){				
				var totalCount = This.scope.store.getCount();
				var allowedQuickLinks = This.scope.allowedQuickLinks;				
				if(totalCount < allowedQuickLinks){
					//get the record
					var selection = This.scope.edit_menu_itemsQuickLinkCombo.getValue();					
					This.scope.store.add(selection);
				}
	        }			
		}
	);
	
 	this.removeQuickLinkButton = new Ext.Button(
		{
			text: removeButtonText,
			scope: this,	
	        handler: function(This,e){
				//remove the item
				This.scope.store.remove(This.scope.dataGrid.getSelectionModel().getSelected());
	        }			
		}		
	);
  
    // Create a config object that will be passed to the Panel constructor.
    // The use of Ext.apply preserves the properties passed in the config object
    this.initialConfig = Ext.apply(config, {
        border: false,
        width: 500,
        layout: 'column',		
        border: false,
        items: [
			{					
	            border: false,
				width: 225,
	            items: [{
		            layout: 'form',			
		            border: false,
					labelWidth: 90,
		            items: [this.edit_menu_itemsQuickLinkCombo.getCombo()]			
				}]					
			},{
	            border: false,				
				width: 70,
	            items: [{
		            layout: 'form',			
		            border: false,
					bodyStyle:'padding:0px 10px 0px 10px',					
		            items: [this.addQuickLinkButton]			
				}]				
			},{			
	            border: false,
				width: 125,
	            items: [{
		            layout: 'form',			
		            border: false,
		            items: [this.dataGrid]			
				}]				
			},{
	            border: false,
				width: 70,
	            items: [{
		            layout: 'form',			
		            border: false,
					bodyStyle:'padding:0px 20px 0px 20px',						
		            items: [this.removeQuickLinkButton]			
				}]				
			}
		]
    });
	
	this.getSelectedQuickLinksID = function(){
		var result = new Array(this.store.getCount());
		
		//get all the ids and put them into an array
		var i = 0;
		for(i = 0 ; i<this.store.getCount() ; i++){
			var element = this.store.getAt(i)
			result[i] = this.store.getAt(i).get('id');
		}
		
		return result;
	}
	
	this.getXMLSelectedQuickLinksID = function(){
		var result = '<categories>'
		
		//get all the ids and put them into an array
		var i = 0;
		for(i = 0 ; i<this.store.getCount() ; i++){
			result = result + '<category id=\'' + this.store.getAt(i).get('id') + '\'\/>';
		}		
		
		result = result + '</categories>';
		return result;
	}
 
 	this.setQuickLinkRecords = function(ids,names){
		var i = 0;
		
		//remove all elements	
		this.store.removeAll();
						
		if (ids.length == names.length) {
			for (i = 0; i < ids.length; i++) {
				var record = new this.categoryRecord({
					id: ids[i],
					name: names[i]					
				});
				
				this.store.add([record]);
			}
		}
	}
 
    // Create a Panel instance and bind it to this DeskIcon instance
    this.panel = new Ext.Panel(this.initialConfig);
}; 
// The DeskIcon prototype defines all the methods shared by the DeskIcon instances
GmSoft.components.QuickLinkChooser.prototype = {
    myApplicationSpecificFunction: function(p1, p2, p3) {
        // Perform application-specific processing
    },
 
    // Make this class usable by a Container, so that we can add and remove it.
    // Create delegates in the scope of our contained Panel which reference Panel's methods
    render: Ext.Panel.prototype.render.createDelegate(this.panel),
    destroy: Ext.Panel.prototype.destroy.createDelegate(this.panel)
};

/**
 * This class is a combo box that automatically queries the info from the parameter url
 * config object with the following parameters
 * @param {Object} comboId: id to set to the comboBox 
 * @param {Object} label: labelToDisplay
 * @param {Object} mappingElement: element that will be shown into the combobox
 * @param {Object} displayField: tag that embeds the mappingElement
 * @param {Object} queryURL: url to request the XML file
		var config = {
	  		comboId: 'edit_menu_itemsDestinationCombo',
	  		label: 'destination',
	  		queryField: 'file',
	  		mappingElement: 'url',
	  		queryURL: 'XmlGMServlet?action_type=get_info&action=get_static_html',
	  		functionToExecOnSelection: Ext.emptyFn,
	  		scope: this
		}
 */
GmSoft.components.ComboSelector = function (config){
	
	this.defaultWidth = 282;
	if(config.comboWidth){
		this.defaultWidth = config.comboWidth;
	}
	
	this.config = config;
	/*comboId, label, queryField, mappingElement, queryURL, functionToExecOnSelection,scope*/
	
	this.selectedRecord = null;
	
	this.mappingElement = this.config.mappingElement;
	
	//Create the factory to retrive elements form the server
	//create a store for the combobox
	this.fileRecord = new Ext.data.Record.create([
			{name: this.config.mappingElement, mapping: this.config.mappingElement, type:'string'},
			{name: 'id', mapping: 'id', type:'string'}
	]);
	
    // create the Data Store
    this.store = new Ext.data.Store({
        // load using HTTP
        proxy: new Ext.data.HttpProxy({url: this.config.queryURL}),
        // the return will be XML, so lets set up a reader
        reader: new Ext.data.XmlReader({
               // records will have a "category" tag
               record: this.config.queryField
           }, this.fileRecord)
    });	
	//overwrite the beforload to load the language parameter	
	this.store.addListener('beforeload', function(This,options) {
		this.store.baseParams.lang = selectedLangId;
	},this);
	
	//add some listeners in case of error.
	this.store.addListener('loadexception',function(This,records,options){		
        Ext.Msg.show({
            title:'Load data error',
            msg:'Could not load from: ' + this.config.queryURL ,
            buttons: Ext.Msg.OK,
            icon: Ext.MessageBox.INFO
        });		
	},this);
			
	//select a default value when everything is loaded	
	this.store.addListener('load', function(records, options){
		//select default value
		var firstValue = this.store.getAt(0);
		if(firstValue == null){
			this.getCombo().setValue('Empy...');
		}else{
			this.getCombo().setValue(firstValue.get(this.config.mappingElement));
		}		
	},this);	
	
	
	var mode = 'remote';
	if(this.config.notRemote){
		mode = 'local';	
	}
	
	this.combo = new Ext.form.ComboBox(
		{
			id: this.config.comboId,                
			fieldLabel: this.config.label,
			xtype:'combo',
			store: this.store,
			displayField: this.config.mappingElement,
			//listWidth: 'auto', //this does not work in ie6
			listWidth: this.defaultWidth,
			resizable:true,
			width: this.defaultWidth,
			mode: mode,				
			lazyinit:'false',
			triggerAction: 'all',
			//emptyText:'Select...',			
			forceSelection : true, //no user text allowed
			selectOnFocus:true,
			//listeners: 
		    //  { select: this.config.functionToExecOnSelection },					
		    allowBlank:false
			//scope: this.config.scope
		}			
	);
	
	//save the record each time is selected	
	this.combo.addListener('select', function(combo, record, index){
		//keep the selected value
		this.selectedRecord = record;
		this.config.functionToExecOnSelection(combo, record, index);
	},this);
	
	//functions getters and setters
	this.getCombo = function(){
		return this.combo;
	}	
	
	//refresh the combo box, and select the first item
	//when done
	this.refresh = function(){
		this.store.load();
		this.getCombo().render();
	}	
	
	this.getValue = function(string){
		if(string)
			if(this.selectedRecord != null)
				return this.selectedRecord.get(this.config.mappingElement);
			else
				return "";
		else
			return this.selectedRecord;
	}
	
	this.getName = function(){
		return this.config.label;
	}
	
	this.setComboValue = function(value){
		this.getCombo().setValue(value);
		this.getCombo().render();
	}
	
	this.setValue = function(value){
		this.getCombo().setValue(value);
		this.getCombo().render();
	}		
	
	    // Create a config object that will be passed to the Panel constructor.
    // The use of Ext.apply preserves the properties passed in the config object
    this.initialConfig = Ext.apply(config, {
        border: false,
        layout: 'form',		
        border: false,
        items: [this.combo]
    });
    // Create a Panel instance and bind it to this DeskIcon instance
    this.panel = new Ext.Panel(this.initialConfig);	
}
GmSoft.components.ComboSelector.prototype = {
    myApplicationSpecificFunction: function(p1, p2, p3) {
        // Perform application-specific processing
    },
 
    // Make this class usable by a Container, so that we can add and remove it.
    // Create delegates in the scope of our contained Panel which reference Panel's methods
    render: Ext.Panel.prototype.render.createDelegate(this.panel),
    destroy: Ext.Panel.prototype.destroy.createDelegate(this.panel)
};

/**
 * This class is a color picker class where the user can choose a color
 */
GmSoft.components.ColorSelector = function (config){
		
	var colorPickerLableText = getLanguageForElement("colorPickerLableText", selectedLangId);
		
	this.config = config;
	
	this.selectedColor = this.config.defaultValue;

	this.setColor = function(hexColor){
		this.colorPalette.select(hexColor); 
	};

	this.getColor = function(){
		return this.selectedColor;
	};
	
	this.colorPalette = new Ext.ColorPalette({
		value: this.config.defaultValue,
		fieldLabel: colorPickerLableText,
		isFormField: true,
		itemCls: '',
		listeners: {
			render: function(c) {
				c.el.dom.className = 'x-color-palette';
			}
		}
	});	
	
	//update the selected color each time another color is selected
	this.colorPalette.on('select',function(This,color){
		this.selectedColor = color;
	},this);
	 
	    // Create a config object that will be passed to the Panel constructor.
    // The use of Ext.apply preserves the properties passed in the config object
    this.initialConfig = Ext.apply(config, {
        layout: 'form',
		bodyStyle: 'padding:5px 0px 0px 0px',				
        border: false,
        items: [this.colorPalette]
    });

    // Create a Panel instance and bind it to this DeskIcon instance
    this.panel = new Ext.Panel(this.initialConfig);	
}
GmSoft.components.ColorSelector.prototype = {
    myApplicationSpecificFunction: function(p1, p2, p3) {
        // Perform application-specific processing
    },
 
    // Make this class usable by a Container, so that we can add and remove it.
    // Create delegates in the scope of our contained Panel which reference Panel's methods
    render: Ext.Panel.prototype.render.createDelegate(this.panel),
    destroy: Ext.Panel.prototype.destroy.createDelegate(this.panel)
};

/**
 * This class shows all specific variable for a software product
 */
GmSoft.components.ProductSoftwareDescriptor = function (config){
		
	var colorPickerLableText = getLanguageForElement("colorPickerLableText", selectedLangId);
	var specificSoftwareDescriptionLableText = getLanguageForElement("specificSoftwareDescriptionLableText", selectedLangId);
	var isSoftwareLableText = getLanguageForElement("isSoftwareLableText", selectedLangId);
		
	this.config = config;	
	
	this.fieldSet = new Ext.form.FieldSet({
		xtype:'fieldset',
		title: specificSoftwareDescriptionLableText,
		collapsible: true,
		collapsed: true,
		autoHeight:true
	});	
	this.isSoftware = new Ext.form.Checkbox({
		fieldLabel: isSoftwareLableText	
	});
	
	this.fieldSet.add(this.isSoftware);
	
    // The use of Ext.apply preserves the properties passed in the config object
    this.initialConfig = Ext.apply(config, {
        layout: 'form',
		bodyStyle: 'padding:5px 0px 0px 0px',				
        border: false,
        items: [
			this.fieldSet
		]
    });

	this.getIsSoftwareValue = function(){
		return this.isSoftware.getValue();
	}
	
	this.setIsSoftwareValue = function(value){
		this.isSoftware.setValue(value);
	}

    // Create a Panel instance and bind it to this DeskIcon instance
    this.panel = new Ext.Panel(this.initialConfig);	
}
GmSoft.components.ProductSoftwareDescriptor.prototype = {
    myApplicationSpecificFunction: function(p1, p2, p3) {
        // Perform application-specific processing
    },
 
    // Make this class usable by a Container, so that we can add and remove it.
    // Create delegates in the scope of our contained Panel which reference Panel's methods
    render: Ext.Panel.prototype.render.createDelegate(this.panel),
    destroy: Ext.Panel.prototype.destroy.createDelegate(this.panel)
};

/**
 * Function to create a tree that maps a navigation menu stucture, as follows:
 * 	<?xml version="1.0" encoding="UTF-8" standalone="no"?>
	<gmsoft_response>
	    <xsl/>
	    <xml>
	        <RootMenu>
	            <category id="3" name="categoria tres"/>
	            <category id="1" name="categoria uno">
	                <item id="5">
	                    segundo link de la categoria 1
	                </item>
	                <item id="4">
	                    link de la categoria 1
	                </item>
	            </category>
	            <category id="2" name="categoria dos"/>
	        </RootMenu>
	    </xml>
	</gmsoft_response>
 * @param {Object} elName: id of the tree
 * @param {Object} url: location where to find the structure
 * @param {Object} rootXMLValue: tag name where to find the root node
 * @param {Object} callback: callback to execute once the tree is loaded
 */
function createNavMenuXmlTree(elName, url, rootXMLValue, categoryTag, itemTag, onCategoryDblClick, onItemDblClick, scope) {

	this.parseElement = rootXMLValue;
	this.categoryTag = categoryTag;
	this.itemTag = itemTag;

	this.getTree = function(){
		return this.tree;
	}

	this.tree = new Ext.tree.TreePanel({
			parseElement: rootXMLValue,
			root: new Ext.tree.TreeNode({
        		text : "FirstElement"
    		}),
			rootVisible : false,
	        animate:true, 
			height : 150,
			width : 515,
			//enableDD: false,
	        autoScroll:true,
			bodyBorder: false,
			border: false,
	        enableDD:true,
	        containerScroll: true,			
			scope: scope
		});
	
	this.p = new Ext.data.HttpProxy({url:url});
			
	//Events
	this.p.on("loadexception", function(o, response, e) {
		if (e) throw e;
	});

	this.tree.on('dblclick',function(node,e){
		var nodeType = node.attributes.nodeType;
		var nodeId = node.attributes.nodeId;
		//do the behabiour depending on the nodeType
		if(nodeType == 'category'){
			//this.scope.config.navigationTreeConfig.treeDoubleClickCategoryFunction(node,this,e);
			onCategoryDblClick(node,this,e);
		}else if(nodeType == 'item'){
			//this.scope.config.navigationTreeConfig.treeDoubleClickItemFunction(node,this,e);
			onItemDblClick(node,this,e);
		}
	});

	this.loadTree = function(){
		this.p.load({lang: selectedLangId}, {
			read: function(response){
				var doc = response.responseXML;
				var response = doc.getElementsByTagName(this.scope.parseElement)[0];
				//remove all old elements from root node
				var childs = this.scope.tree.getRootNode().childNodes;
				if(childs.length > 0){ //remove first child
					childs[0].remove();
				}
				//read the new elements
				this.scope.tree.getRootNode().appendChild(treeNodeFromXml2(response, this.scope.categoryTag, this.scope.itemTag));
				this.scope.tree.render();
			},
			scope:this
		}, Ext.emptyFn, this.tree);
	}
		
}

/**
 * Grid to see the news, the url must return the following xml structure
 * @param {Object} elName: element to query from the structure
 * @param {Object} url: url to query the structure
 * @param {Object} onDblClick: function to execute on doubl click
 * @param {Object} scope: scope that will be passed to the double click function
 */
function createNewsXmlList(elName, url, onDblClick, scope){
    //the grid panel to show all/select one news names
    // create the Data Store
    this.store = new Ext.data.Store({
        // load using HTTP        
        proxy: new Ext.data.HttpProxy({
            url: 'XmlGMServlet?action_type=news_actions&action=get_all_news'
        }),
        
        // the return will be XML, so lets set up a reader
        reader: new Ext.data.XmlReader({
            // records will have an "Item" tag
            record: 'news_item',
            id: 'id'
        	}, ['header', 'date'])
    });
    
    // create the grid
    this.newsGrid = new Ext.grid.GridPanel({
        store: this.store,
        columns: [{
            id: 'Name',
            header: 'Name',
            dataIndex: 'header',
            sortable: true
        }, {
            header: 'Date',
            dataIndex: 'date',
            sortable: true
        }],
	    border: false,		
        width: '100%',
		autoHeight : true,
        autoExpandColumn: 'Name',
        sm: new Ext.grid.RowSelectionModel({
            singleSelect: true
        })
    });
	
	this.getNewsGrid = function(){
		return this.newsGrid;
	}
    
    this.newsGrid.on('rowdblclick', function(This, rowIndex, e){
        var id = This.getStore().getAt(rowIndex).id;
		//read all the fields form the servlet
		this.selectedItem = id;
        ajaxSendReadNewsItem(id,"Spanish",this);
    }, this);
    
    //first load
	/*
    this.store.load({
        params: {
            lang: 'Spanish'
        }
    });*/
}

/**
 * This function maps and XML to a tree node with its childs
 * @param {Object} XmlEl: xml document object
 */
function treeNodeFromXml(XmlEl) {	
	//get all the necessary values to create the node tree
	var t = null;
	var menuItemType = null;
	var menuItemId = null;	
	if(XmlEl.nodeType == 3){  //this is a text node, we don't represent directly text nodes, so skip
		//t = XmlEl.nodeValue;
		t = '';
	}else if (XmlEl.nodeType == 1){
		t = XmlEl.tagName;
		menuItemId = findAttributValueInNode(XmlEl,'id');

		if(t == 'category'){  //read attributes name and id
			menuItemType = 'category';
			t = findAttributValueInNode(XmlEl,'name');
			if(t == null) t = '';
		}else if(t == 'item'){  //read attributes id, and look for direct text node
			menuItemType = 'item';
			t = findDirectTextNodeValue(XmlEl);
			if(t == null) t = '';
		}
	}else{
		return null; //if the element is an attribute return nothing
	}

	//	No text, no node.
	if (t.replace(/\s/g,'').length == 0) {
		return null;
	}		
	
	//create text node
	var result = new Ext.tree.TreeNode({
        text : t,
		nodeType: menuItemType, //this should be category or item
		nodeId: menuItemId //here we keep the id of the item or the category
    });

	//For Elements, process attributes and children
	if (XmlEl.nodeType == 1) {
		Ext.each(XmlEl.childNodes, function(el) {
		//Only process Elements and TextNodes
			if ((el.nodeType == 1) || (el.nodeType == 3)) {
				var c = treeNodeFromXml(el);
				if (c) {
					result.appendChild(c);
				}
			}
		});
	}
	return result;
}

/**
 * This function maps and XML to a tree node with its childs
 * @param {Object} XmlEl: xml document object
 */
function treeNodeFromXml2(XmlEl,categoryTag,itemTag) {	
	this.categoryTag = categoryTag;
	this.itemTag = itemTag;

	//get all the necessary values to create the node tree
	var t = null;
	var menuItemType = null;
	var menuItemId = null;	
	if(XmlEl.nodeType == 3){  //this is a text node, we don't represent directly text nodes, so skip
		t = '';
	}else if (XmlEl.nodeType == 1){
		t = XmlEl.tagName;
		menuItemId = findDirectTextNodeInsideTagValue(XmlEl,'id');
		removeDirectNode(XmlEl,"id");

		if(t == categoryTag){  //read attributes name and id
			menuItemType = 'category';
			t = findDirectTextNodeInsideTagValue(XmlEl,'name');
			removeDirectNode(XmlEl,"name");
			if(t == null) t = '';
		}else if(t == itemTag){  //read attributes id, and look for direct text node
			menuItemType = 'item';
			t = findDirectTextNodeInsideTagValue(XmlEl,'name');
			removeDirectNode(XmlEl,"name");
			if(t == null) t = '';
		}
	}else{
		return null; //if the element is an attribute return nothing
	}

	//	No text, no node.
	if (t.replace(/\s/g,'').length == 0) {
		return null;
	}		
	
	//create text node
	var result = new Ext.tree.TreeNode({
        text : t,
		nodeType: menuItemType, //this should be category or item
		nodeId: menuItemId //here we keep the id of the item or the category
    });

	//For Elements, process attributes and children
	if (XmlEl.nodeType == 1) {
		var childNodes = XmlEl.childNodes;
		var i;
		for( i = 0 ; i < childNodes.length ; i++){
			var el = childNodes[i];
			if ((el.nodeType == 1) || (el.nodeType == 3)) {
				var c = treeNodeFromXml2(el, this.categoryTag, this.itemTag);
				if (c) {
					result.appendChild(c);
				}
			}			
		}
	}
	return result;
}
