if(typeof brodos.address === 'undefined') brodos.address = {};
Ext.namespace("brodos.address");
/*
 * @description Addresspanel zeigt ein Grid mit einer Auflistung von Adressen
 *Die Kommunikation findet mit der Schnittstelle deliveryaddresses.php statt.
 *deliveryaddresses.php kann unter der Url /index.php/mpath/services_deliveryaddresses erreicht werden
 * @name Addresspanel
 * @augments config
 * @config config {url: string 'URL zur Schnittstelle bei der die daten für das Grid angefragt werden',
 *                 urlParams: object{customerno,systemid,action}'mit welchen parameter soll die Anfrage für das grid starten. Die daten müssen vorhanden sein'
 *                 title: string 'Titeltext für die Gridanzeige',
 *                 }
 * @example addresswindow=  new brodos.address.addressPanel(
 *                          {
 *                             url : brodos.config.get('WDIR') + '/index.php/mpath/services_deliveryaddresses',
 *                             addressValidationURL : brodos.config.get('WDIR') + '/index.php/mpath/services_deliveryaddresses',
 *                             title : brodos.translation.get('_MASK_SHOW_DELIVERY_ADDRESSES'),
 *                             createNewAddressWindowTitle : brodos.translation.get('_MASK_DELIVERADRESS_NEW_TITLE'),
 *                             editAddressWindowTitle : brodos.translation.get('_MASK_DELIVERADRES_EDIT_TITLE'),
 *                             baseUrl : brodos.config.get('WDIR'),
 *                             DSIUrl : brodos.config.get('WDIR')+ '/index.php/mpath/services_dsi',
 *                             defaultCountryKey : '<?=$defaulcountrykey?>',
 *                             urlParams : {customerno:'<?=$customerno?>',systemid:'<?=getSystemid($tbo_conn,$DID)?>', action:'getData'}
 *                          });
 */
brodos.address.addressPanel = function (config)
{
     this.title = '';
     this.activeRecord = null;
     this.selectedRowIndex = null;
    // this.width = 785;
     this.c_t_Store_loaded = false;
     this.addressValidationURL = config.addressValidationURL ? config.addressValidationURL : '';
     this.defaultLanguageKey = config.defaultLanguageKey ? config.defaultLanguageKey : 'DEU';
     this.defaultCountryKey = config.defaultCountryKey ? config.defaultCountryKey : 'DEU';
     brodos.address.addressPanel.superclass.constructor.call(this, config);
}

/*
 * @description Adresswindow Zeigt ledeglich ein Fenster an in dem eine Adresse angezeigt oder editiert wird.
 * @name addressWindow
 * @event doneButtonPressed : doneButtonPressed wird gefeuert wenn im Anzeigefenster auf den Fertig-Button geclickt wird
 * dabei wird ein object geworfen mit den Werten {name1 : 'Wert aus name1 Feld'
 *                                               ,name2 : Wert aus name2 Feld
 *                                               ,name3 : Wert aus name3 Feld
 *                                               ,street: Wert aus Straße Feld
 *                                               ,houseno:Wert aus Nausnummer Feld
 *                                               ,zipcode: Wert aus Postleitzahl Feld
 *                                               ,countrykey: Ein ausgewählter Land Key aus der Länderliste
 *                                               ,city  : Wert aus Ort Feld
 *                                               ,salutationkey: Ein ausgewählter Arede Key aus der Anredeliste
 *                                               ,titlekey : Ein ausgewählter Titel Key aus der Titelliste
 *                                               ,isDirty  : Ein Flag wenn einer der Werte geändert wurde}
 *
 * @config object configObj { title   : Titel für die Kopfzeile im fenster
 *                           ,country_store: Store für die Länderliste
 *                           ,addressValidationURL: Url für die Addressvalidierung/vervollständigung
 *                           ,title_store : Store für die Titelliste
 *                           ,defaultCountryKey: 'DEU'}
 *                           
 * @example new brodos.address.addressWindow(configObj);
 *
 */
brodos.address.addressWindow = function (config)
{
     this.width = 500;
     this.addressValidationURL = config.addressValidationURL ? config.addressValidationURL : '';
     this.modal = true;
     this.bodyStyle = 'background-color:#fff';
     this.border = false;
     this.autoWidth = false;
     this.isDirty = false;
     this.valid_address = true;
     this.acceptAddress = true;
     this.defaultCountryKey = config.defaultCountryKey ? config.defaultCountryKey : 'DEU';
     this.defaultLanguageKey = config.defaultLanguageKey ? config.defaultLanguageKey : 'DEU';
     brodos.address.addressWindow.superclass.constructor.call(this, config);
};

Ext.extend(brodos.address.addressWindow, Ext.Window,
{
    resizable:false,
    listeners:{show:{fn:function(){
                            this.manageView(this.salutationkey)
                            }
                            }
    },
    manageView : function(salutationkey){
        if (salutationkey == 'H' || salutationkey == 'F') {
            this.item_title.showCt();
            this.item_name2.show();
            this.item_name1.setWidth(130);
            this.item_name1.setFieldLabel(brodos.translation.get('_CS_FIRSTLASTNAME'));
                            }
        else 
                            {
            if (salutationkey == 'FI') 
            {
                this.item_name1.setFieldLabel(brodos.translation.get('_CS_COMPANYNAME'));
                            }
            else
            {
                this.item_name1.setFieldLabel(brodos.translation.get('_CS_NAME1'));
                       }
            this.item_name1.setWidth(270);
            this.item_title.hideCt();
            this.item_name2.hide();
            }
        this.doLayout();
    },
    initComponent : function (config)
    {
         brodos.address.addressWindow.superclass.initComponent.apply(this, arguments);
        /*
         * Store for title select title combobox
         */
        if( !Ext.isObject(this.title_store)){
            this.title_store = new Ext.data.Store({
                baseParams: {
                    action: 'getData',
                    subject: 'SYSTITLE',
                    queryXml: '<?xml version="1.0" encoding="UTF-8"?><data-query xmlns="http://brodos.net/schemas/dataStorage/2008/01"><query-definition key="query1"><paging limit="1000" maxcount="1000"></paging><column name="TITLEKEY" /><column name="DESCRIPTION" /></query-definition></data-query>'
                },
                url: this.DSIUrl,
                reader: new Ext.data.XmlReader({
                    record: 'row',
                    id: '@key',
                    fields: [
                        {name: 'key', mapping: 'column[name=TITLEKEY]'},
                        {name: 'description', mapping: 'column[name=DESCRIPTION]'}
                    ]
                })
            });
            this.title_store.load();
        }
        /*
         * Store for country select
         */
        if (!Ext.isObject(this.country_store)) {
            this.country_store = new Ext.data.Store({
                    baseParams: {
                        action: 'getData',
                        subject: 'COUNTRYDESCRIPTION',
                        queryXml: '<?xml version="1.0" encoding="UTF-8"?> <data-query xmlns="http://brodos.net/schemas/dataStorage/2008/01"><query-definition><paging limit="1000" maxcount="1000"/><column name="COUNTRYKEY"/><column name="COUNTRYNAME"/><column name="COUNTRYDEFAULTNAME"/><filter-relation><filter operation="EQ" op2="' + this.defaultLanguageKey + '" op1="LANGKEY"></filter></filter-relation><order-list><column direction="ASC" name="COUNTRYDEFAULTNAME"></column></order-list></query-definition></data-query> '
                    },
                    url   : this.DSIUrl,
                    reader: new Ext.data.XmlReader({
                        record: 'row',
                        id: '@key',
                        fields: [
                            {name: 'key', mapping: 'column[name=COUNTRYKEY]'},
                            {name: 'description', mapping: 'column[name=COUNTRYDEFAULTNAME]'}
                        ]
                    })
                });
                this.country_store.load();
        }
        /*
        * DelayedTask Steuert beim Aufruf wann die gewüschte Aktion verzögert ausgeführt werden soll.
        */
        this.delayedTask = new Ext.util.DelayedTask();
        
        this.alort = "";
        this.cityname = "";
        this.foundZipcode = "";
        this.districtKey = "";
        this.streetKey = "";
        this.cityStore = new Ext.data.JsonStore(
        {
            //url: this.addressValidationURL,
            restful: true,
            root: 'values',
            fields: ['alort', 'city', 'longname', 'districtKey', 'district', 'zipcode']
            ,autoLoad: false
        });
        this.zipStore = new Ext.data.JsonStore(
        {
            //url: this.addressValidationURL,
            restful: true,
            root: 'values',
            fields: ['alort', 'city', 'longname', 'districtKey', 'district', 'zipcode']//,
            ,autoLoad: false
        });
        this.streetStore = new Ext.data.JsonStore(
        {
            //url: this.addressValidationURL,
            restful : true,
            root    : 'values',
            fields  : ['alort', 'name', 'longname', 'streetKey', 'district', 'zipcode']
           // ,autoLoad: false
        });
        /*
         * Salutation combobox
         */
        this.item_salutation = new Ext.form.ComboBox(
        {
            name            : 'salutation',
            fieldLabel      : brodos.translation.get('_CS_SALUTATION'),
            editable        : false,
            disableKeyFilter: true,
            forceSelection  : true,
            value           : this.salutationkey,
            emptyText       : brodos.translation.get('_MASK_NOCHOICE'),
            triggerAction   : 'all',
            store           : [[ '', brodos.translation.get('_MASK_NOCHOICE')],
                                [ 'H', brodos.translation.get('_MASK_MR')],
                                [ 'F', brodos.translation.get('_MASK_MS')],
                                ['FI', brodos.translation.get('_MASK_FIRMA')]],
            listeners: {
                'select': {
                    fn: function(cmb, rec, ind) {
                        var val = rec.get('field1');
                        this.manageView(val);
                    }
                    ,scope: this
                }
            }
        });
        var a = Ext.data.Record.create([
            {name: 'key'},
            {name: 'description'}
        ]);
        var b = new a({
                key: '',
                description: brodos.translation.get('_CS_NOCHOICE')
            });
        this.title_store.insert(0,b);
        
        /*
         * Title combobox
         */
        this.item_title = new Ext.form.ComboBox({
            name            : 'title',
            width           : 100,
            fieldLabel      : brodos.translation.get('_CS_TITLE'),
            editable        : false,
            disableKeyFilter: true,
            forceSelection  : true,
            emptyText       : brodos.translation.get('_MASK_NOCHOICE'),
            triggerAction   : 'all',
            store           : this.title_store,
            value           : this.titlekey,
            displayField    : 'description',
            valueField      : 'key',
            mode            : 'local'
        });
        /*
         * Country combobox
         */
        this.item_country = new Ext.form.ComboBox({
            name            : 'country',
            width           : 270,
            fieldLabel      : brodos.translation.get('_MASK_COUNTRY'),
            editable        : true,
            disableKeyFilter: true,
            forceSelection  : true,
            emptyText       : brodos.translation.get('_MASK_NOCHOICE'),
            triggerAction   : 'all',
            store           : this.country_store,
            displayField    : 'description',
            value           : this.countrykey ? this.countrykey : this.defaultCountryKey,
            valueField      : 'key',
            typeAhead       : true,
            mode            : 'local'
        });
        /*
         * Salutation combobox
         */
        this.item_salutationtitle = new Ext.Panel({
            layout      : 'column',
            border      : false,
            defaults    : {labelWidth:130,layout: 'form',xtype: 'panel',border: false},
            items       : [{

                width   : 250,
                defaults: {anchor: '-20'},
                items   : [this.item_salutation]
            },{
                width       : 155,
                defaults    : {anchor: '0'},
                labelWidth  : 50,
                items       : [this.item_title]
            }]
        });
        /*
         * Name1 textfield
         */
        this.item_name1 = new Ext.form.TextField({
            name        : 'name1',
            labelSeparator: ':',
            fieldLabel: brodos.translation.get('_CS_FIRSTLASTNAME'),
            value       : this.name1,
            scope       :this,
            autoCreate  : {tag: "input", type: "text", maxlength: "50", autocomplete: "off"},
            listeners   : {change:{fn:function(textfield){this.acceptAddress = true;},scope:this}}
        });
        /*
         * Name2 textfield
         */
        this.item_name2 = new Ext.form.TextField({
            name        : 'name2',
            value       : this.name2,
            width       : 135,
            scope       :this,
            autoCreate  : {tag: "input", style:'width:130px',type: "text", maxlength: "50", autocomplete: "off"},     
            listeners   : {change:{fn:function(textfield){this.acceptAddress = true;},scope:this}}
        });
        
        this.item_name1_name2 = new Ext.form.CompositeField({
            width   : 270,
            items   : [this.item_name1,this.item_name2]
        });
        
        /*
         * Name3 textfield
         */
        this.item_name3 = new Ext.form.TextField({
            name        : 'name3',
            value       : this.name3,
            scope       :this,
            autoCreate  : {tag: "input", type: "text", maxLength: "50", autocomplete: "off"},
            fieldLabel  : brodos.translation.get('_CS_NAMEADDITION'),
            width       : 270
        });

        /*
         * Panel whitch contains name1 and name2
         */
        /* this.item_name1_name2 = new Ext.Panel({
            layout   : 'form',
            labelWidth:120,
            border   : false,
            width    : 400,
            items    : [this.item_name1,this.item_name2,this.item_name3]
        }); */
        /*
         * Street Texfield with ComboBox functionality
         */
        this.item_street = new Ext.form.ComboBox({
            name            : 'streetname',
            fieldLabel      : brodos.translation.get('_CS_STREET')+' / '+brodos.translation.get('_CS_HOUSENO'),
            forceSelection  : false,
            hideTrigger     : true,
            store           : this.streetStore,
            value           : this.street,
            valueField      : 'name',
            displayField    : 'name',
            scope           : this,
            typeAhead       : true,
            triggerAction   : 'all',
            mode            : 'local',
            width           : 225,
            listeners       : {
                              keyup:{fn:function(TextField,Event){
                                        if(this.alort != "" && TextField.getRawValue().length > 2 && this.item_country.getValue() == "DEU" )
                                        {
                                            if(this.addressValidationURL != ''){
                                                var confObj = {
                                                    streetname : TextField.getRawValue(),
                                                    alort:this.alort
                                                };
                                                var DHLAddressHandler = new brodos.address.DHLAddressHandler({gatewayURL:this.addressValidationURL});
                                                this.delayedTask.delay(750,DHLAddressHandler.getStreetFacility, DHLAddressHandler,[confObj]);
                                                DHLAddressHandler.on('requestsuccess',function(success){
                                                    TextField.store.loadData(success);
                                                },this);
                                                DHLAddressHandler.on('requesterror',function(success){},this);
                                            }
                                        }
                                    },scope:this
                              },
                              select:{fn:function(combo, record, index){
                                      if(record.get('zipcode') != this.item_zipcode.getValue())
                                      {
                                          this.item_zipcode.setValue(record.get('zipcode')) ;
                                          this.item_zipcode.setRawValue(record.get('zipcode')) ;
                                      }
                                    },scope:this
                              },
                              change:{fn:function(textfield){this.acceptAddress = true;},scope:this}
            }
        });
        /*
         * Houseno textfield
         */
        this.item_houseno = new Ext.form.TextField({
            name        : 'housno',
            value       : this.houseno,
            autoCreate  : {tag: "input", type: "text", maxlength: "10", width:150, autocomplete: "off"},
            hideLabel   : true,
            msgDisplay  : 'block',
            scope       : this,
            width       : 40,
            listeners   : {change:{fn:function(textfield){this.acceptAddress = true;},scope:this}}
        });
        /*
         * A panel witch contains Street and Houseno fields
         */
        this.item_streethouseno = new Ext.form.CompositeField({
        combineErrors: false,
            items   : [this.item_street,this.item_houseno]
        });
        /*
         * this template is used to show zipcode with City
         */
        this.tpl = new Ext.XTemplate(
            '<tpl for=".">',
                '<div class="x-combo-list-item" style="font-size: 10px">',
                    '<div style="display: table;">',
                        '<div style="display: table-row;">',
                            '<div style="display: table-cell; min-width: 3em;">{zipcode}</div>',
                            '<div style="display: table-cell;">({longname})</div>',
                        '</div>',
                    '</div>',
                '</div>',
           '</tpl>'
        );
        /*
         * Zipcode textfield with combobox functionality
         */
        this.item_zipcode = new Ext.form.ComboBox({
            name            : 'zipcode',
            width           : 45,
            fieldLabel      : brodos.translation.get('_MASK_ZIPCODE')+' / ' + brodos.translation.get('_MASK_CITY'),
            tpl             : this.tpl,
            forceSelection  : false,
            hideTrigger     : true,
            store           : this.zipStore,
            value           : this.zipcode ,
            valueField      : 'zipcode',
            displayField    : 'zipcode',
            msgDisplay      : 'block',
            typeAhead       : true,
            triggerAction   : 'query',
            listWidth       : '200',
            mode            : 'local',
            selectOnFocus:true,
            listeners:  {keyup:{fn: function(TextField,Event)
                            {
                                var erlaubt = TextField.getRawValue().search(/[a-zA-Z _\/\*\-\,\.\+]/);
                                var len =TextField.getRawValue();
                                if(Event.isNavKeyPress()){
                                    erlaubt = 1;
                                }
                                if(len.length > 2 &&  len.length < 6 && this.item_country.getValue() == "DEU" && erlaubt < 0){
                                    if( this.addressValidationURL != ''){
                                        var DHLAddressHandler = new brodos.address.DHLAddressHandler({gatewayURL:this.addressValidationURL});
                                        this.delayedTask.delay(750,DHLAddressHandler.getZipFacility, DHLAddressHandler,[{zipcode:len}]);
                                        DHLAddressHandler.on('requestsuccess',function(success){TextField.store.loadData(success);},this);
                                        DHLAddressHandler.on('requesterror',function(success){},this);
                                    }
                                }
                            },scope:this
                        },
                        select:{fn:function(combo, record, index ){
                                    this.item_city.setValue(record.get('city')) ;
                                    this.item_city.setRawValue(record.get('city')) ;
                                    this.alort = record.get('alort');
                                    this.foundZipcode = record.get('zipcode');
                                    this.districtKey = record.get('districtKey');
                                    if(this.item_street.getRawValue() != "" && this.item_zipcode.getRawValue() != ""){
                                        var DHLAddressHandler = new brodos.address.DHLAddressHandler({gatewayURL:this.addressValidationURL});
                                        DHLAddressHandler.checkStreet({alort:this.alort,streetname:this.item_street.getRawValue()});
                                        DHLAddressHandler.on('requestsuccess',function(result){
                                        if(result.status == false) this.item_street.markInvalid(brodos.translation.get('_MASK_STREET_DONT_MATCH_TO_ZIPCODE'));
                                     },this);
                                }
                            },scope:this
                        },
                        change:{fn:function(textField){
                                if(textField.store.getCount() == 1) {
                                    this.item_city.setValue(textField.store.getAt(0).get('city')) ;
                                    this.item_city.setRawValue(textField.store.getAt(0).get('city')) ;
                                }
                                this.acceptAddress = true;
                                
                            },scope:this
                        },
                        blur:{fn:function(textField){
                                if(textField.store.getCount() == 1 ) {
                                    this.item_city.setValue(textField.store.getAt(0).get('city')) ;
                                    this.item_city.setRawValue(textField.store.getAt(0).get('city'));
                                    this.alort = textField.store.getAt(0).get('alort');
                                }
                            },scope:this
                        }
                    }
        });

        this.item_city = new Ext.form.ComboBox({
            name            : 'city',
            value           : this.city,
            hideLabel       : true,
            forceSelection  : false,
            labelSeperator  : '' ,
            hideTrigger     : true,
            store           : this.cityStore,
            valueField      : 'name',
            displayField    : 'longname',
            width           : 220,
            typeAhead       : true,
            msgDisplay      : 'block',
            mode            : 'local',
            listeners:  {keyup:
                        {fn: function(TextField,Event)
                            {
                                var wert = TextField.getRawValue();
                                var ortsteil = wert.search(/OT .*/);
                                if(ortsteil < 0)ortsteil = wert.search(/\,.*/);
                                if(ortsteil > 0) wert = wert.substring(0, ortsteil - 1);
                                var erlaubt = 0;
                                if(!Event.isNavKeyPress()){
                                    erlaubt = 1;
                                }                                
                                
                                if(wert.length > 1 && this.item_country.getValue() == "DEU" && erlaubt==1 && this.addressValidationURL != ''){
                                    if(this.addressValidationURL != ''){
                                        var DHLAddressHandler = new brodos.address.DHLAddressHandler({gatewayURL:this.addressValidationURL});
                                        this.delayedTask.delay(750,DHLAddressHandler.getCityFacility,DHLAddressHandler,[{'city':wert}]);
                                        DHLAddressHandler.on('requestsuccess',function(success){TextField.store.loadData(success);},this);
                                        DHLAddressHandler.on('requesterror',function(success){},this);
                                    }
                                }
                            },scope:this
                        },
                        select:{fn:function(combo, record, index ){
                                if(record.get('zipcode') != "")
                                {
                                    combo.setValue(record.get('city')) ;
                                    combo.setRawValue(record.get('city')) ;
                                    this.item_zipcode.setValue(record.get('zipcode')) ;
                                    this.item_zipcode.setRawValue(record.get('zipcode')) ;
                                    this.foundZipcode = record.get('zipcode');
                                }
                                else{
                                    combo.setValue(record.get('city')) ;
                                    combo.setRawValue(record.get('city')) ;
                                }
                                this.districtKey = record.get('districtKey');
                                this.alort = record.get('alort');
                                var street = this.item_street.getRawValue();
                                var zipcode = this.item_zipcode.getRawValue();
                                if(street != "" && zipcode.length == 5 && this.item_country.getValue() == "DEU" && this.addressValidationURL != ''){
                                        var DHLAddressHandler = new brodos.address.DHLAddressHandler({gatewayURL:this.addressValidationURL});
                                        DHLAddressHandler.checkStreet({alort:this.alort,streetname:this.item_street.getRawValue()});
                                        DHLAddressHandler.on('requestsuccess',function(result){
                                        if(result.status == false) this.item_street.markInvalid(brodos.translation.get('_MASK_STREET_DONT_MATCH_TO_CITY'));
                                     },this);
                                }
                            },scope:this
                       },
                       change:{fn:function(textField){
                                this.acceptAddress = true;
                                
                       },scope:this}
                    }
        });
        this.item_zipcodecity = new Ext.form.CompositeField({
            combineErrors: false,
            items       : [this.item_zipcode,this.item_city]
        });

        this.item_AddressWindowDoneButton = new Ext.Panel({
            layout      : 'column',
            xtype       : 'panel',
            defaults    : {layout:'form',border:false},
            border      : false,
            items       :[{columnWidth :0.8,
                            hidden      :true,
                            id          :'validationMessage',
                            style       :'margin-top:15px; padding-left:10px;',
                           // hideMode    :'visibility',
                            items       :{xtype:'label',
                                          cls:'x-form-invalid-msg',
                                          text : brodos.translation.get('_MASK_NOT_VALID_ADDRESS_MESSAGE')
                                         }
                         },
                         {columnWidth :0.8,
                            hidden      :true,
                            id          :'correctenessMessage',
                            style       :'margin-top:5px; padding-left:10px;',
                            hideMode    :'visibility',
                            items       :{xtype:'label',
                                          cls:'x-form-invalid-msg',
                                          text : brodos.translation.get('_MASK_NOT_ADDRESS_NOT_ALL_VALUES_MESSAGE')
                                         }
                         },
                        {buttons: [new brodos.button.Done({
                           listeners:{click:{fn:function()
                                        {
                                            if(
                                                this.item_name1.isDirty()      ||
                                                this.item_name2.isDirty()      ||
                                                this.item_name3.isDirty()      ||
                                                this.item_street.isDirty()     ||
                                                this.item_houseno.isDirty()    ||
                                                this.item_zipcode.isDirty()    ||
                                                this.item_country.isDirty()    ||
                                                this.item_city.isDirty()       ||
                                                this.item_salutation.isDirty() ||
                                                this.item_title.isDirty()
                                            )this.isDirty = true;

                                            var editvalues = {
                                                    name1       : this.item_name1.getValue()
                                                   ,name2       : this.item_name2.getValue()
                                                   ,name3       : this.item_name3.getValue()
                                                   ,street      : this.item_street.getRawValue()
                                                   ,houseno     : this.item_houseno.getValue()
                                                   ,zipcode     : this.item_zipcode.getRawValue()
                                                   ,countrykey  : this.item_country.getValue()
                                                   ,city        : this.item_city.getRawValue()
                                                   ,salutationkey: this.item_salutation.getValue()
                                                   ,titlekey    : this.item_title.getValue()
                                                   ,isDirty     : this.isDirty
                                               };
                                            if(editvalues.isDirty)//Würde Eingabe getättigt
                                            {
                                                if(this.checkfields())//sind alle Felder gesetzt?
                                                {
                                                    this.findById('correctenessMessage').hide();
                                                    var selectedcountrykey = this.item_country.getValue();
                                                    if(selectedcountrykey == 'DEU' && this.addressValidationURL != '' && this.acceptAddress)//Ist es ne Deutsche Addresse und Validationurl ist gesetzt
                                                    {
                                                        var checkvalues = editvalues;
                                                        var wert = editvalues.city;

                                                        var ortsteil = wert.search(/OT .*/);//ist ein Ortsteil in Ort mit angegeben?
                                                        if(ortsteil < 0)ortsteil = wert.search(/\,.*/); //ist ort mit Komma zusammengesezt?

                                                        checkvalues.streetname = editvalues.street;

                                                        checkvalues.city = ortsteil > 0 ? wert.substring(0,ortsteil-1) : wert;

                                                        var DHLAddressHandler = new brodos.address.DHLAddressHandler({gatewayURL:this.addressValidationURL});
                                                        DHLAddressHandler.on('requestsuccess',function(result){
                                                                if(result.status != "0"){
                                                                    if(result.status == '3'){
                                                                        this.item_zipcode.markInvalid(brodos.translation.get('_MASK_ZIP_CITY_NOT_MATCH'));
                                                                        this.item_city.markInvalid(brodos.translation.get('_MASK_ZIP_CITY_NOT_MATCH'));
                                                                    }
                                                                    if(result.status == '5'){
                                                                        this.item_street.markInvalid(brodos.translation.get('_MASK_NO_SUCH_STREET_IN_CITY'));
                                                                    }
                                                                    if(result.status == '4'){
                                                                        this.item_houseno.markInvalid(brodos.translation.get('_MASK_NO_SUCH_HOUSENO_IN_ZIPCODE_RANGE'));
                                                                    }
                                                                    this.findById('validationMessage').show();
                                                                    this.acceptAddress = false;
                                                                }
                                                                else
                                                                {
                                                                    this.fireEvent('doneButtonPressed',editvalues);
                                                                    this.destroy();
                                                                }
                                                         },this);
                                                        DHLAddressHandler.isValidAddress(checkvalues);                                                        
                                                    }
                                                    else
                                                    {
                                                        this.fireEvent('doneButtonPressed',editvalues);
                                                        this.destroy();
                                                    }
                                                }
                                                else{
                                                    this.findById('correctenessMessage').show();
                                                    this.acceptAddress = !this.acceptAddress;
                                                    if(this.acceptAddress)
                                                    {
                                                        this.fireEvent('doneButtonPressed',editvalues);
                                                        this.destroy();
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                this.fireEvent('doneButtonPressed',editvalues);
                                                this.destroy();
                                            }
                                        }
                                        ,scope:this
                                    }
                             }
                            })]
                        ,columnWidth:0.15
                    }//,{columnWidth:0.05}
                ]
        });
        this.checkfields = function(){
            var str = this.item_street;
            var zip = this.item_zipcode;
            var loc = this.item_city;
            var hou = this.item_houseno;
            var sal = this.item_salutation;
            var n1 = this.item_name1;
            var n2 = this.item_name2;
            var ret = true;
            var zipval = zip.getRawValue();
            var regnum = /[A-Z a-z\+\-_.\&\%\°\^\!\"\§\$\@\/\(\)\=\?\`\´\#\µ\<\>\@\²\³\{\}]/;
           /* if(sal.getValue() == 'FI' || sal.getValue() == ''){
                if(Ext.util.Format.trim(n1.getValue()) == ''){
                    n1.markInvalid(brodos.translation.get('_MASK_NAME1_IS_EMPTY'));
                    ret = false;
                }
            }
            else{
                if(Ext.util.Format.trim(n1.getValue()) == ''){
                    n1.markInvalid(brodos.translation.get('_MASK_FIRSTNAME_IS_EMPTY'));
                    ret = false;
                }
                if(Ext.util.Format.trim(n2.getValue()) == ''){
                    n2.markInvalid(brodos.translation.get('_MASK_FIRSTNAME_IS_EMPTY'));
                    ret = false;
                }
            }*/
            if(Ext.util.Format.trim(hou.getRawValue()) == ''){
                hou.markInvalid(brodos.translation.get('_MASK_HOUSENO_IS_EMPTY'));
                ret = false;
            }
            if(Ext.util.Format.trim(loc.getRawValue()) == ''){
                loc.markInvalid(brodos.translation.get('_MASK_CITY_IS_EMPTY'));
                ret = false;
            }
            if(Ext.util.Format.trim(zip.getRawValue()) == ''){
                zip.markInvalid(brodos.translation.get('_MASK_ZIPCODE_IS_EMPTY'));
                ret = false;
            }
            else if(regnum.test(zipval) && this.item_country.getValue() == 'DEU'){
                zip.markInvalid(brodos.translation.get('_MASK_ZIPCODE_MUST_NUMERIC'));
                ret = false;
            }
            else if(Ext.util.Format.trim(zip.getRawValue()).length != 5 && this.item_country.getValue() == 'DEU'){
                zip.markInvalid(brodos.translation.get('_MASK_ZIPCODE_WRONG_LENGTH'));
                ret = false;
            }
            if(Ext.util.Format.trim(str.getRawValue()) == ''){
                str.markInvalid(brodos.translation.get('_MASK_STREET_IS_EMPTY'));
                ret = false;
            }
            if(this.valid_address)this.valid_address = ret;
            else this.valid_address = true;
            if(!ret)this.item_AddressWindowDoneButton.findById('correctenessMessage').show();
            return ret;
        }
        this.editAddressWindowContent = new Ext.Panel({
            layout      : 'form',
            labelWidth  : 130,
            //autoWidth   : true,
            width       : '100%',
            style       : 'margin:10px;',
            border      : false,
            items       :[
                 this.item_salutationtitle
                ,this.item_name1_name2
                ,this.item_name3
                ,this.item_streethouseno
                ,this.item_zipcodecity
                ,this.item_country
                ,this.item_AddressWindowDoneButton
            ]
        });
        this.add(this.editAddressWindowContent);
        this.doLayout(this);
        Ext.QuickTips.init();
        Ext.form.Field.prototype.msgTarget='under';
  }    
});

Ext.extend( brodos.address.addressPanel, Ext.Window,
{
    layout      :'fit',
    width       :900,
    border      :false,
    AddressEditWindow :null,
    closeAction : 'hide',
    initComponent: function(config){
        brodos.address.addressPanel.superclass.initComponent.apply(this, arguments);
        /*
         * Store for title select title combobox
         */
        if( !Ext.isObject(this.title_store)){
            this.title_store = new Ext.data.Store({
                baseParams: {
                    action: 'getData',
                    subject: 'SYSTITLE',
                    queryXml: '<?xml version="1.0" encoding="UTF-8"?><data-query xmlns="http://brodos.net/schemas/dataStorage/2008/01"><query-definition key="query1"><paging limit="1000" maxcount="1000"></paging><column name="TITLEKEY" /><column name="DESCRIPTION" /></query-definition></data-query>'
                },
                url: this.DSIUrl,
                reader: new Ext.data.XmlReader({
                    record: 'row',
                    id: '@key',
                    fields: [
                        {name: 'key', mapping: 'column[name=TITLEKEY]'},
                        {name: 'description', mapping: 'column[name=DESCRIPTION]'}
                    ]
                })
            });
        }
        /*
         * Store for country select
         */
        if (!Ext.isObject(this.country_store)) {
            this.country_store = new Ext.data.Store({
                    baseParams: {
                        action: 'getData',
                        subject: 'COUNTRYDESCRIPTION',
                        queryXml: '<?xml version="1.0" encoding="UTF-8"?> <data-query xmlns="http://brodos.net/schemas/dataStorage/2008/01"><query-definition><paging limit="1000" maxcount="1000"/><column name="COUNTRYKEY"/><column name="ISO"/><column name="COUNTRYNAME"/><column name="COUNTRYDEFAULTNAME"/><filter-relation><filter operation ="EQ" op2="' + this.defaultLanguageKey + '" op1="LANGKEY"></filter></filter-relation><order-list><column direction="ASC" name="COUNTRYDEFAULTNAME"></column></order-list></query-definition></data-query> '
                    },
                    url   : this.DSIUrl,
                    reader: new Ext.data.XmlReader({
                        record: 'row',
                        id: '@key',
                        fields: [
                            {name: 'key', mapping: 'column[name=COUNTRYKEY]'},
                            {name: 'description', mapping: 'column[name=COUNTRYDEFAULTNAME]'}
                        ]
                    })
                });
        }
        if(!this.c_t_Store_loaded)
        {
            this.c_t_Store_loaded = true;
            this.country_store.load();
            this.title_store.load();
        }
        this.checkColumn = new Ext.grid.CheckColumn({
               header: brodos.translation.get("_MASK_STANDARD"),
               dataIndex: 'isstandard',
               width: 50,
               onMouseDown: function(e, t)
                   {
                       if(t.className && t.className.indexOf('x-grid3-cc-'+this.id) != -1)
                       {
                            var index = this.grid.getView().findRowIndex(t);
                            var record = this.grid.store.getAt(index);
                            e.stopEvent();
                            var lauf = 0;
                            this.grid.store.each(function(a)
                            {
                                if(lauf++ != index)a.set(this.dataIndex,false);
                            },this);

                           
                            if (record)
                            {
                                record.set(this.dataIndex, !record.get(this.dataIndex));
                                this.grid.fireEvent('standardChecked',{index:index,columnname:this.dataIndex},t);
                            }
                            this.grid.store.commitChanges();
                        }
                }
            });
        var addressListCBSellection = new Ext.grid.CheckboxSelectionModel();
        this.addressList = new Ext.grid.GridPanel({
                border:false,
                autoHeight:true,
                loadMask:true,
                enableColumnResize:true,
                enableColumnMove : false,
                enableHdMenu:false,
                tbar:[{xtype:'button',
                       cls: 'x-btn-icon',
                       icon: brodos.config.get('WDIR')+'/images/new.gif',
                       scope:this,
                       listeners:{click: {fn:function()
                                    {
                                        var configObj = {baseUrl : this.baseUrl
                                                        ,title   : this.createNewAddressWindowTitle
                                                        ,country_store: this.country_store
                                                        ,addressValidationURL:this.addressValidationURL
                                                        ,title_store : this.title_store
                                                        ,defaultCountryKey:this.defaultCountryKey ? this.defaultCountryKey :  'DEU'
                                                        ,defaultLanguageKey:this.defaultLanguageKey ? this.defaultLanguageKey :  'DEU'
                                                        };
                                        this.AddressEditWindow = new brodos.address.addressWindow(configObj);
                                        this.AddressEditWindow.show();
                                        this.AddressEditWindow.on('doneButtonPressed',function(obj){
                                            if(obj.isDirty)
                                            {
                                                obj.action = 'insert';
                                                obj.customerno = this.urlParams.customerno;
                                                obj.systemid = this.urlParams.systemid;
                                                Ext.Ajax.request({
                                                   url: this.url,
                                                   success: function (response, options)
                                                   {
                                                       var result =  Ext.decode(response.responseText);
                                                       if(result.success) this.addressList.store.load();
                                                       else Ext.MessageBox.alert(brodos.translation.get('_MASK_ERROR'), brodos.translation.get('_MASK_MESSAGE_CAN_NOT_INSERT_ADDRESS_ERROR'));
                                                   },
                                                   failure: function()
                                                   {
                                                       Ext.MessageBox.alert(brodos.translation.get('_MASK_ERROR'), brodos.translation.get('_MASC_MESSAGE_ADDERSSMANAGE_NO_CONNECT'));
                                                   },
                                                   params: obj,
                                                   scope:this
                                                });
                                            }
                                        }, this);
                                },scope:this}
                       }
                    },
                      {xtype:'button',
                       cls: 'x-btn-icon',
                       icon: brodos.config.get('WDIR')+'/images/del.gif',
                       listeners:{click: {
                                    fn:function(){
                                        try {
                                            //var a = this.addressList.getSelectionModel().getSelected().get('id');
                                            var a = this.addressList.getSelectionModel().getSelections();
                                            var ret = new Array();
                                            for(var i = 0; i < a.length;i++){
                                                ret[i]=a[i].get('id');
                                            }
                                            if(ret.length > 0)
                                            {
                                            Ext.Ajax.request({
                                               url: this.url,
                                               success: function (response, options)
                                               {
                                                   var result =  Ext.decode(response.responseText);
                                                       if(result.success){
                                                           this.addressList.store.load();
                                                       }
                                                       else if (result.code == 2)Ext.MessageBox.alert(brodos.translation.get('_MASK_INFO'), brodos.translation.get('_MASK_MESSAGE_CAN_NOT_DELETE_MAIN_ADDRESS_ERROR'));
                                                   else Ext.MessageBox.alert(brodos.translation.get('_MASK_ERROR'), brodos.translation.get('_MASK_MESSAGE_CAN_NOT_DELETE_ADDRESS_ERROR'));
                                               },
                                               failure: function()
                                               {
                                                   Ext.MessageBox.alert(brodos.translation.get('_MASK_ERROR'), brodos.translation.get('_MASC_MESSAGE_ADDERSSMANAGE_NO_CONNECT'));
                                               },
                                               method : 'POST',
                                                   params: {action:'delete', addressid:Ext.encode(ret)},
                                               scope:this
                                            });
                                        }
                                        }
                                        catch(e){}
                                    }
                                   ,scope:this}
                           }
                       }],
                store: new Ext.data.JsonStore({
                                url:this.url,
                                baseParams:this.urlParams,
                                root: 'rowdata',
                                autoLoad:false,
                                listeners:{load:{fn:function(){
                                     /*
                                      * wenn ein neuer Datensatz hinzukommen sollte, so soll der zuvor ausgewählter Datensatz markiert werden da Reload des Stores
                                      * den zuvor ausgewählten Datensatz löscht
                                      */
                                    if(this.selectedRowIndex) this.addressList.getSelectionModel().selectRow(this.selectedRowIndex);
                                },scope:this}},
                    fields: [
                                {name: 'id',    mapping:'ADDRESSID'}
                               ,{name:'name1',  mapping:'NAME1'}
                               ,{name:'name2',  mapping:'NAME2'}
                               ,{name:'name3',  mapping:'NAME3'}
                               ,{name:'street', mapping:'STREET'}
                               ,{name:'houseno',mapping:'HOUSENO'}
                               ,{name:'zipcode',mapping:'ZIPCODE'}
                               ,{name:'city',   mapping:'CITY'}
                               ,{name:'countryname', mapping:'COUNTRYNAME'}
                               ,{name:'countrykey',mapping:'COUNTRYKEY'}
                               ,{name:'isstandard',mapping:'STANDARDADDRESS', type: 'bool'}
                               ,{name:'salutationkey', mapping:'SALUTATIONKEY'}
                               ,{name:'titlekey', mapping:'TITLEKEY'}
                            ]
                }),
                columns: [
                    addressListCBSellection,
                    {header: brodos.translation.get("_MASK_NAME1"), id:'id',dataIndex: 'name1',resizable:true},
                    {header: brodos.translation.get("_MASK_NAME2"), id:'id',dataIndex: 'name2',resizable:true},
                    {header: brodos.translation.get("_CS_NAMEADDITION"), id:'id',dataIndex: 'name3',resizable:true},
                    {header: brodos.translation.get("_MASK_STREET_HOUSENO"), id:'id',renderer: function(val,meta,rec,rind,cind,store)
                                                    {
                                                        var street = rec.get("street") || '';
                                                        var houseno = rec.get("houseno") || '';
                                                        return Ext.util.Format.trim(street+ " "+ houseno);
                                                    },resizable:true},
                    {header: brodos.translation.get("_MASK_ZIPCODE"), id:'id',dataIndex: 'zipcode',resizable:true},
                    {header: brodos.translation.get("_MASK_CITY"), id:'id',dataIndex: 'city',resizable:true},
                    {header: brodos.translation.get("_MASK_COUNTRY"), id:'id', dataIndex: 'countryname',resizable:true},
                    this.checkColumn,
                    {header: brodos.translation.get("_MASK_EDIT"),dataIndex:'id', width:60,
                        renderer: function(value)
                        {
                            return '<img src="../../images/edit.gif"  alt="'+brodos.translation.get("_MASK_EDIT")+'" title="'+brodos.translation.get("_MASK_EDIT")+'">';
                        },resizable:true
                    }
                ],
                sm: addressListCBSellection,
                plugins: this.checkColumn,
                listeners:{
                    cellclick: {
                        fn: function(grid, rowindex, columnindex, eventObject ) {
                            this.activeRecord = grid.store.getAt(rowindex);
                            this.selectedRowIndex = rowindex;
                            if(columnindex == 9)
                            {
                                if(!this.c_t_Store_loaded)
                                {
                                    this.c_t_Store_loaded = true;
                                    this.country_store.load();
                                    this.title_store.load();
                                }
                                var configObj = {title       : this.editAddressWindowTitle,
                                               country_store : this.country_store
                                               ,title_store  : this.title_store
                                               ,defaultCountryKey : this.defaultCountryKey
                                               ,defaultLanguageKey : this.defaultLanguageKey
                                               ,addressValidationURL : this.addressValidationURL
                                               ,name1       : this.activeRecord.get('name1')
                                               ,name2       : this.activeRecord.get('name2')
                                               ,name3       : this.activeRecord.get('name3')
                                               ,street      : this.activeRecord.get('street')
                                               ,houseno     : this.activeRecord.get('houseno')
                                               ,zipcode     : this.activeRecord.get('zipcode')
                                               ,countrykey  : this.activeRecord.get('countrykey')
                                               ,city        : this.activeRecord.get('city')
                                               ,salutationkey: this.activeRecord.get('salutationkey')
                                               ,titlekey    : this.activeRecord.get('titlekey')
                                               ,baseUrl     : this.baseUrl
                                              };
                                this.AddressEditWindow = new brodos.address.addressWindow(configObj);
                                this.AddressEditWindow.show();
                                this.AddressEditWindow.on('doneButtonPressed',function(addressdata)
                                {
                                    if(addressdata.isDirty)
                                    {
                                        addressdata.action = 'update';
                                        addressdata.addressid = this.activeRecord.get('id');
                                        if(addressdata.salutationkey == 'FI' || addressdata.salutationkey == '')
                                        {
                                            addressdata.name2 = '';
                                        }
                                        Ext.Ajax.request({
                                           url: this.url,
                                           success: function (response, options)
                                           {
                                               var result =  Ext.decode(response.responseText);
                                               if(result.success)
                                               {
                                                   this.addressList.store.load();
                                               }
                                               else if (result.code == 2)Ext.MessageBox.alert(brodos.translation.get('_MASK_INFO'), brodos.translation.get('_MASK_MESSAGE_CAN_NOT_UPDATE_MAIN_ADDRESS_ERROR'));
                                               else Ext.MessageBox.alert(brodos.translation.get('_MASK_ERROR'), brodos.translation.get('_MASK_MESSAGE_CAN_NOT_UPDATE_ADDRESS_ERROR'));
                                           },
                                           failure: function()
                                           {
                                               Ext.MessageBox.alert(brodos.translation.get('_MASK_ERROR'), brodos.translation.get('_MASC_MESSAGE_ADDERSSMANAGE_NO_CONNECT'));
                                           },
                                           params: addressdata,
                                           scope:this
                                        });
                                    }
                                },this);
                            }
                        },scope: this
                    },
            'standardChecked':{fn:function(checkedIndex,t){
                                 var updatedata = {'action':'updateStandard'
                                                  ,'customerno':this.urlParams.customerno
                                                  ,'systemid':this.urlParams.systemid
                                                  ,'addressid': this.addressList.store.getAt(checkedIndex.index).get('id')
                                              };

                                Ext.Ajax.request({
                                   url: this.url,
                                   success: function (response, options)
                                   {
                                        var result =  Ext.decode(response.responseText);
                                        if(!result.success) Ext.MessageBox.alert(brodos.translation.get('_MASK_ERROR'), brodos.translation.get('_MASK_MESSAGE_CAN_NOT_UPDATE_STD_ADDRESS_ERROR'));
                                   },
                                   failure: function()
                                   {
                                       Ext.MessageBox.alert(brodos.translation.get('_MASK_ERROR'), brodos.translation.get('_MASC_MESSAGE_ADDERSSMANAGE_NO_CONNECT'));
                                   },
                                   params: updatedata
                                });
                                t.parentNode.parentNode.className = t.parentNode.parentNode.className.replace('x-grid3-dirty-cell','');
                         },scope:this},
                 load:{fn:function(){
                        this.syncShadow();
                         },scope:this}
                }
        });
        this.addButton(new brodos.button.Done(
                        {
                            scope:this,
                            listeners:
                            {click:{fn:function(button, event)
                                      {
                                          var allselected = this.addressList.getSelectionModel().getSelections();
                                          var returnvalues = null;
                                          if(allselected.length==1){
                                              this.activeRecord = allselected[0];
                                              returnvalues = {
                                                                name1       : this.activeRecord.get('name1')
                                                               ,name2       : this.activeRecord.get('name2')
                                                               ,name3       : this.activeRecord.get('name3')
                                                               ,street      : this.activeRecord.get('street')
                                                               ,houseno     : this.activeRecord.get('houseno')
                                                               ,zipcode     : this.activeRecord.get('zipcode')
                                                               ,countrykey  : this.activeRecord.get('countrykey')
                                                               ,city        : this.activeRecord.get('city')
                                                               ,salutationkey: this.activeRecord.get('salutationkey')
                                                               ,titlekey    : this.activeRecord.get('titlekey')
                                                               ,countAddresses: this.addressList.store.getTotalCount()
                                                           };
                                          }
                                          else
                                          {
                                                var std = false;
                                                this.addressList.store.each(function(a,b)
                                                {
                                                    if(a.get('isstandard')) std = b;
                                                },this);
                                                if(std != false)
                                                {
                                                    var stdrow = this.addressList.store.getAt(std);
                                                      returnvalues = {
                                                                        name1       : stdrow.get('name1')
                                                                       ,name2       : stdrow.get('name2')
                                                                       ,name3       : stdrow.get('name3')
                                                                       ,street      : stdrow.get('street')
                                                                       ,houseno     : stdrow.get('houseno')
                                                                       ,zipcode     : stdrow.get('zipcode')
                                                                       ,countrykey  : stdrow.get('countrykey')
                                                                       ,city        : stdrow.get('city')
                                                                       ,salutationkey: stdrow.get('salutationkey')
                                                                       ,titlekey    : stdrow.get('titlekey')
                                                                       ,countAddresses: this.addressList.store.getTotalCount()
                                                                   };
                                                }
                                          }
                                          /*
                                          if(this.selectedRowIndex)
                                          {
                                              returnvalues = {
                                                                name1       : this.activeRecord.get('name1')
                                                               ,name2       : this.activeRecord.get('name2')
                                                               ,name3       : this.activeRecord.get('name3')
                                                               ,street      : this.activeRecord.get('street')
                                                               ,houseno     : this.activeRecord.get('houseno')
                                                               ,zipcode     : this.activeRecord.get('zipcode')
                                                               ,countrykey  : this.activeRecord.get('countrykey')
                                                               ,city        : this.activeRecord.get('city')
                                                               ,salutationkey: this.activeRecord.get('salutationkey')
                                                               ,titlekey    : this.activeRecord.get('titlekey')                                                               
                                                               ,countAddresses: this.addressList.store.getTotalCount()
                                                           };
                                          }
                                          else
                                          {
                                            var std;
                                            this.addressList.store.each(function(a,b)
                                            {
                                                if(a.get('isstandard')) std = b;
                                            },this);

                                            var stdrow = this.addressList.store.getAt(std);
                                              returnvalues = {
                                                                name1       : stdrow.get('name1')
                                                               ,name2       : stdrow.get('name2')
                                                               ,name3       : stdrow.get('name3')
                                                               ,street      : stdrow.get('street')
                                                               ,houseno     : stdrow.get('houseno')
                                                               ,zipcode     : stdrow.get('zipcode')
                                                               ,countrykey  : stdrow.get('countrykey')
                                                               ,city        : stdrow.get('city')
                                                               ,salutationkey: stdrow.get('salutationkey')
                                                               ,titlekey    : stdrow.get('titlekey')
                                                               ,countAddresses: this.addressList.store.getTotalCount()
                                                           };
                                          }*/
                                          this.fireEvent('doneButtonPressed',returnvalues);
                                          this.hide();
                                      },scope:this
                                  }
                            }
                        }));
        this.add(this.addressList);
        this.addressList.store.load();
        this.doLayout(this);
    }
});
