Ext.namespace('brodos.ux');
/**
 * @class brodos.ux.FeatureSelection
 * @extends Ext.Panel
 * @constructor
 * Creates a new FeatureSelection
 * @param {Object/Array} config A config object
 */
brodos.ux.FeatureSelection = Ext.extend(Ext.Panel,{
    closeAction:'hide',
	modal: true,
    plain: true,
    autoHeight:true,
    height:'auto',
    layout: 'column',
    border: false,
    minHeight: 140,
    leftList: [],
    tmpLeftList: [],
    rightLists: [],
    selected: [],
    selectedSalesDepartment: null,
    additional: '',
    wdir: '',
    service:'',
    leftWrench: {
        border: false,
        columnWidth: .1
    },
    rightWrench: {
        border: false,
        columnWidth: .1
    },
	initComponent : function(config) {
        brodos.ux.FeatureSelection.superclass.initComponent.call(this, arguments);
		Ext.apply(this, config);
        this.win = this.findParentByType('window');
        this.on('render',this.build,this);
	},
    build: function() {
        Ext.Ajax.request({
            url: this.wdir+this.service,
            params: {
                systemid: this.systemid,
                action: 'load'
            },
            success: function(result,request){
                this.leftList = Ext.decode(result.responseText).leftlist;
                this.rightLists = Ext.decode(result.responseText).rightlists;
				for(var i = 0; i<this.leftList.length; i++) {
					this.tmpLeftList.push(this.leftList[i]);
				}
                this.add(new Ext.Panel({columnWidth:.05,border:false,html:'&nbsp;'}));
                this.add(new Ext.Panel({columnWidth:.45,
                    border: false,
                    bodyStyle: 'margin-bottom: 15px;',
                    html:'<div style="margin-top:3px;font-weight:bold;font-size:15px;">'+this.titleLeft+':</div>'
                }));
                this.add(new Ext.Panel({columnWidth:.5,
                    border: false,
                    bodyStyle: 'margin-bottom: 15px;',
                    html:'<div style="margin-top:3px;font-weight:bold;font-size:15px;">'+this.titleRight+':</div>'
                }));
                for(var j = 0;j < this.selected.length; j++) {
                    this.generateRow(j);
                }
				this.updateLeftList();
                this.generateRow(null);
            },
            failure: function(result,request){
            },
            scope: this
        });
    },
	updateLeftList: function() {
		this.tmpLeftList = [];
		var issalesdepartment = true;
		for(var i = 0; i < this.selected.length; i++) {
			if(this.selected[i].issalesdepartment == 1) {
				issalesdepartment = false;
                this.selectedSalesDepartment = this.selected[i].leftid;
				break;
			}
		}
		//Ext.iterate(this.rightLists, function(key, item){
		for(var i = 0; i<this.leftList.length; i++) {
			//if('L'+this.leftList[i][0] == key) {
			if(this.leftList[i][2] == '1' && !issalesdepartment && this.selectedSalesDepartment !=  this.leftList[i][0]) {
				continue;
			} else {
				this.tmpLeftList.push(this.leftList[i]);
			}
			//}
		}
		//},this);
	},
    destroyRow: function(row) {
        Ext.Ajax.request({
            url: this.wdir+this.service,
            params: {
                id: row.lid,
                action: 'delete'
            },
            success: function(result,request){
                var success = Ext.decode(result.responseText).success;
                if(success) {
                    var elPassed = false;
                    for(var k = 0; k < this.selected.length; k++) {
                        if(row.lid == this.selected[k].id) {
                            elPassed = true;
                        }
                        if(elPassed) {
                            this.selected[k] = this.selected[k+1];
                        }
                    }
                    this.selected.pop();
					this.updateLeftList();
					this.tmpCombo.getStore().removeAll();
					this.tmpCombo.getStore().loadData(this.tmpLeftList);
                    this.remove(row);
                    this.doLayout();
                    if(this.win) this.win.syncShadow();
                } else {
                    Ext.Msg.alert(localization.getStringForKey('_CAT_INFORM_ERROR_TITLE'), '<br>'+'Internal error!');
                }
            },
            failure: function(result,request){
                Ext.Msg.alert(localization.getStringForKey('_CAT_INFORM_ERROR_TITLE'), '<br>'+'Internal error!');
            },
            scope: this
        });
    },
    buildComboLine: function(id, leftid, rightid) {
        var leftCombo = new Ext.form.ComboBox({
            typeAhead: true,
            triggerAction: 'all',
            selectOnFocus:false,
            editable: false,
            mode: 'local',
            columnWidth: .4,
			disabled: !(id == null),
            store: new Ext.data.Store({
                reader: new Ext.data.ArrayReader({}, [
                   {name: 'valueId'},
                   {name: 'valueDescription'},
				   {name: 'issalesdepartment'}
                ]),
                data:this.tmpLeftList
            }),
            listeners: {
                select: {
                    fn: function(field, newValue, index) {
                        /**
                         * countnsalesdepartments wird dafür verwendet, um einem Kunden nicht mehr als 3 Vertreter aus einer Verakaufsabteilung zuzuweisen.
                         */
                        var countnsalesdepartments = 0;
                        Ext.each(this.selected,function(item,index,runingarray){
                           if(item.issalesdepartment == '1')countnsalesdepartments++;
                        });
                        
                           if(countnsalesdepartments == 3 && field.store.getAt(index).get('issalesdepartment') == '1')
                           {
                               Ext.Msg.alert(localization.getStringForKey('_CAT_INFORM_DEPARTMENT_MAX_TITLE'), '<br>'+ brodos.translation.get("_CAT_DEPARTMENTS_MAX_DEPARTMENTS_SELECTED"));
                               field.setValue('');
                               return;
                           }
                        
						rightCombo.getStore().removeAll();
						if(this.rightLists['L'+newValue.get('valueId')] !== undefined) {
							rightCombo.getStore().loadData(this.rightLists['L'+newValue.get('valueId')]);
						} else {
                                Ext.Msg.alert(localization.getStringForKey('_CAT_INFORM_ERROR_TITLE'), localization.getStringForKey('_CAT_INFORM_DEPARTMENT_NO_PERSONS_ASSIGNED'));
						}
						rightCombo.enable();
                    },
                    scope: this
                }
            },
            valueField: 'valueId',
            displayField: 'valueDescription'
        });
		if(id == null) this.tmpCombo = leftCombo;
		
		var rightCombo = new Ext.form.ComboBox({
            typeAhead: true,
            triggerAction: 'all',
            selectOnFocus:false,
            editable: false,
            mode: 'local',
            disabled: true,
            columnWidth: .4,
            store: new Ext.data.Store({
                reader: new Ext.data.ArrayReader({}, [
                   {name: 'valueId'},
                   {name: 'valueDescription'}
                ]),
                data:(this.rightLists['L'+leftid] !==undefined)?this.rightLists['L'+leftid]:[]
            }),
            listeners: {
                select: {
                    fn: function(field, newValue, index) {
                        var rowPanel = field.findParentByType('panel').findParentByType('panel');
						Ext.Ajax.request({
							url: this.wdir+this.service,
							params: {
								action: 'save',
								systemid: this.systemid,
								additional: this.additional,
								leftid:leftCombo.getValue(),
								rightid: newValue.get('valueId')
							},
							success: function(result,request){
								var resultObject = Ext.decode(result.responseText);
								if(resultObject.success !== undefined) {
									var success = resultObject.success;
									if(success) {
										if(resultObject.id !== undefined) {
											rowPanel.lid = resultObject.id;
											leftCombo.disable();
											rightCombo.disable();
											rowPanel.find('iconCls', 'cross-button-image')[0].show();
											var leftRecord = leftCombo.findRecord(leftCombo.valueField, leftCombo.getValue());
											this.selected.push({
												id:String(resultObject.id),
												leftid:leftRecord.get('valueId'),
												rightid:newValue.get('valueId'),
												leftvalue:leftRecord.get('valueDescription'),
												rightvalue:newValue.get('valueDescription'),
												issalesdepartment: leftRecord.get('issalesdepartment')
											});
											this.updateLeftList();
											this.generateRow(null);
										}
									} else {
										rightCombo.setValue(rightid);
										Ext.Msg.alert(localization.getStringForKey('_CAT_INFORM_ERROR_TITLE'), '<br>'+'Internal error!');
									}
								} else {
									rightCombo.setValue(rightid);
									Ext.Msg.alert(localization.getStringForKey('_CAT_INFORM_ERROR_TITLE'), '<br>'+'Internal error!');
								}
							},
							failure: function(result,request){
								Ext.Msg.alert(localization.getStringForKey('_CAT_INFORM_ERROR_TITLE'), '<br>'+'Internal error!');
							},
							scope: this
						});
                    },
                    scope: this
                }
            },
            valueField: 'valueId',
            displayField: 'valueDescription'
        });
        leftCombo.setValue(leftid);
        rightCombo.setValue(rightid);
        var box = {
			columnWidth: .9,
			border: false,
			layout:'column',
			items:[leftCombo,this.leftWrench,rightCombo,this.rightWrench]
        };
        return box;
    },
    generateRow: function(j) {
        if(j != null) {
            var id = this.selected[j].id;
            var leftid = this.selected[j].leftid;
            var rightid = this.selected[j].rightid;
        } else {
            var id = null;
            var leftid = null;
            var rightid = null;
        }
        var row = new Ext.Panel({
            border: false,
            columnWidth: 1,
            saved:id?true:false,
            layout:'column',
            lid: id,
            bodyStyle: 'margin-bottom: 15px;',
            items: [{
                columnWidth: .05,
                border: false,
                html:'<div style="margin-left:4px;margin-top:2px;font-size:15px;">&nbsp;</div>'
            },
                this.buildComboLine(id,leftid,rightid),
            {
                columnWidth: .05,
                border: false,
                items: [{
                    xtype:'button',
                    hidden: (j != null)?false:true,
                    iconCls : 'cross-button-image',
                    listeners: {
                        click:{
                            fn:function(btn, e) {
                                this.destroyRow(row);
                                this.updateLeftList();
                            },
                            scope:this
                        }
                    }
                }]
            }]
        });
        this.add(row);
        this.doLayout();
        if(this.win) this.win.syncShadow();
    }
});
Ext.reg('featureselection', brodos.ux.FeatureSelection);